One long class or many shorter classes?

2020-07-02 10:13发布

问题:

In PHP, is there any performance impact on using one long class with a lot of functions in it? Or is it advisable to use many small classes and call them separately when needed?

I am a newbie in OOPS and please ignore any silliness in the question. Thanks.

回答1:

It's advisable not to think about the performance before you have the code. From the maintainability and understandability viewpoint, of course, smaller classes, with smaller methods are superior. (see The Single Responsibility Principle)

When you need to optimize, you really can assemble (automatically) all your code into a single big file, and save some time on include-s.



回答2:

First, think about clean OOP design.

Very long classes with a lot of methods and properties are very difficult to understand.

A set of well-designed classes with meaningful class names, method names and variable names are very easy to understand especially when it comes to maintenance period.



回答3:

In general, people tend to make classes that are too large and complex -- this is because it's often difficult to see where the cohesion boundaries lie. So when you're starting out and a bit unsure, it's better to err on the side of making them too small: you can always coalesce smaller classes into a larger one... it's often much harder to refactor a large class into several small ones.



回答4:

You can and should put things in the same class as long they are directly related to the logic of the class you're creating. Size of the class doesn't mean a lot if you follow the OOP concepts.



回答5:

Personally for me I would much prefer to break the classes down into smaller files based on what they are for. If that's business objects then having a 'customer.class.php' 'account.class.php' etc would be my preference.

In most of the projects on which I've worked it's been like this, then a larger 'lib' or 'common' file which includes lots of various functions which are used all over the place.



回答6:

For the record, the size is not the important part to consider in a class. What's key to a class are the dependencies of the classes.

For example, a class that depends in the database should be separates in a special class, such a Repository / Dao / Dal / Persistence class.



标签: php oop class