开发者

OOP: when should i create a base class and when should i not?

I have a large class with lots of methods (25, interrelated of course). I'm not sure I should split it up and create a derivative and base class instead. I don't see any opportunity coming in the future f开发者_开发知识库or another class inheriting from the base. So what are the driving factors for breaking a large class down into smaller parts?


Yes, with 20+ methods, break it up.

Sometimes it needs experimentation.

Another option is to look at how to reduce the number of methods. For example do you have the same method (by name) taking different number and/or types of parameters? In that case you might look at commonalities between those signatures. This leads me to another suggestion.

If you have a method that takes more than - let's say 4 - parameters, then look at them and maybe there is an option to turn them into a class by themselves. This can result in some of the functionality moving out into the new class.

Look at the number of fields (= member variables) in your class. Can you group the methods in such a way that they operate largely on a subset of those member variables? Maybe you can turn these methods and the values they operate on into a new class.


what are the driving factors for breaking a large class down into smaller parts?

You should do it when it makes logical sense to do it in terms of separate objects. If all those methods you've defined truly do operate on a single object and couldn't logically be thought of as pertaining to different objects, then keep them in one.

I'm not sure I should split it up and create a derivative and base class instead

Not sure what you mean here. You would derive from a base class when you need an object that inherits some behaviours from a base class but modifies or adds others, but want your base class to remain as it is as well. You don't inherit just to break up your code into manageable chunks.


"Large Class" is a classic "code smell". See here: http://sourcemaking.com/refactoring/large-class

When you have a large class, it may or may not mean you have a good candidate for refactoring. That's what a "code smell" is... It may be your code is fine, but only a good hard look at it can you be sure.

Follow the advice given in the article I've linked. Even thought it wasn't written for PHP, the concepts and strategies still apply.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜