Do polymorphism or conditionals promote better design?

前端 未结 12 1839
长情又很酷
长情又很酷 2020-12-02 06:37

I recently stumbled across this entry in the google testing blog about guidelines for writing more testable code. I was in agreement with the author until this point:

12条回答
  •  长情又很酷
    2020-12-02 07:12

    Not an expert in the implications for test cases, but from a software development perspective:

    • Open-closed principle -- Classes should be closed to alteration, but open to extension. If you manage conditional operations via a conditional construct, then if a new condition is added, your class needs to change. If you use polymorphism, the base class need not change.

    • Don't repeat yourself -- An important part of the guideline is the "same if condition." That indicates that your class has some distinct modes of operation that can be factored into a class. Then, that condition appears in one place in your code -- when you instantiate the object for that mode. And again, if a new one comes along, you only need to change one piece of code.

提交回复
热议问题