开发者

betterment of code in OO php

I use php OO for my project. I have lots of families in my application around 7. So i have to use switch and do it in each file where i need to check the family. So i feel the performance is effected because of this开发者_C百科. So is there any way so that i can eliminate these switch cases and use some design patters or something like that. The present idea is to have a separate code base for each family, which i am not satisfied with completely. So looking for various options to solve this issue.


I can only quote Martin Fowler from his book Refactoring: Improving the Design of Existing Code.

Switch Statements

One of the most obvious symptoms of object-oriented code is its comparative lack of switch (or case) statements. The problem with switch statements is essentially that of duplication. Often you find the same switch statement scattered about a program in different places. If you add a new clause to the switch, you have to find all these switch, statements and change them. The object- oriented notion of polymorphism gives you an elegant way to deal with this problem.

Most times you see a switch statement you should consider polymorphism. The issue is where the polymorphism should occur. Often the switch statement switches on a type code. You want the method or class that hosts the type code value. So use Extract Method to extract the switch statement and then Move Method to get it onto the class where the polymorphism is needed. At that point you have to decide whether to Replace Type Code with Subclasses or Replace Type Code with State/Strategy. When you have set up the inheritance structure, you can use Replace Conditional with Polymorphism.

Consider buying and reading this book, it's one of the most precious works I have read.


That pattern would be Refactor Conditional With Polymorphism.

The idea is to make those various family types into objects of their own. The linked article is taken from Martin Fowler's book Refactoring: Improving the Design of Existing Code that was already quoted in that other answer. In fact, the linked site has the entire contents of the book.

Additional information can be found at http://www.refactoring.com/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜