Correct use of "construction" when designing classes

I am new to object oriented programming and writing some of my first classes for a PHP application.

In some simpler classes, I declare function __construct()

and within this function call certain class methods. In some cases, I find myself instantiating a class in my application and don't need anything with the resulting object, because the class __construct()

called methods that did their job, leaving me nothing to do with the class.

I just don't like it. It seems dumb that I have a new object that I never do anything with.

Again, I stress that this only applies to some of my simpler classes. In more complex ones, I use class methods through the object and outside __construct()

.

Do I need to rethink how I code things, or am I okay?

+1


a source to share


2 answers


Well, the constructor is used to create a new instance of the class and for any necessary customization for that class. If you just create a class and leave it, it seems a little empty. Why not, for example, use static functions in a class as an organizing tool and just call them (or the function that calls them) rather than create a new instance that you will never use?



+4


a source


I just don't like it. It seems dumb that I have a new object that I never do anything with.

Yes, that should raise a red flag.

In general, you shouldn't let constructors have any side effects; They are meant to initialize the state of an object - nothing else. Of course, there are exceptions to this rule, but overall it's a good guideline. You should also refrain from doing any heavy computation in the constructor. Move this instead of a method.



Side effects are many things - changing global variables or static (class) variables; output to Wednesday (for example, calls print()

, header()

or exit()

); calls to a database or other external service, and even changes to the state of other objects.

A free side-effect function is also called a "pure" function, as opposed to a procedure, which is a function that has side effects. It is good practice to directly isolate pure functions from procedures (and perhaps even label them as such).

+2


a source







All Articles