Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One long class or many shorter classes?

Tags:

oop

php

class

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.

like image 874
Nirmal Avatar asked Dec 31 '09 11:12

Nirmal


People also ask

Why a large number of simple classes is better than small number of complex classes?

Classes with a single responsibility are better because they are easier to extend and easier to test. They are more reusable than complicated classes.

How many classes can I use in Java?

A single Java program contains two or more classes, it is possible in two ways in Java.

How big is too big for a class?

"There is a point at which small class sizes do not produce better outcomes. They produce worse outcomes," says author Malcolm Gladwell about teaching teenagers.


3 Answers

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.

like image 135
Ivan Krechetov Avatar answered Oct 01 '22 13:10

Ivan Krechetov


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.

like image 30
Upul Bandara Avatar answered Oct 01 '22 15:10

Upul Bandara


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.

like image 36
Stabledog Avatar answered Oct 01 '22 15:10

Stabledog