Objects That: Have State vs Do Work

July 11, 2025 note-to-self full-stack

I'm self taught at developing. Been at it for a long time, but I've missed some of the pivots the world of developers - PHP specifically - have done, and when classes were introduced back in PHP 4, I didn't understand them or why someone would use them.

Back then, life was very procedural and we mixed PHP and HTML for the most part. We included db.inc in files that needed to use the database, and MVC was avant-gard.

I say all that because it took me a long time to understand how to use objects effectively. I'm not sure I still do. But, I'm still learning. This is something I recently finally understood. It definitely goes against how classes were used about a decade ago. And I see code all over the place that uses clases with state and I also see why we are going away from that.

So...

When to pass data in via constructor and when to use a class as stateless:

Constructors belong to objects that are data (entities/value objects) and need that data to function.

Stateless classes are for pure behaviors -- no stored data -- so each method call is crystal-clear and side-effect-free.

It was recommended that I split things into "things that have state" and "things that do work". And, that helped. Some objects have data in a specific structure. Other objects operate on data. But, it's generally considered best practice not to do both in an object. Having to maintain 5 year old code with state, and it's becoming clear the advantages.

Inject shared, structural dependencies (services, repositories, APIs) via the constructor.

Pass in data (DTOs, primitives, context, flags) as method parameters.

That way each class' constructor advertises "what it is", and each method signature advertises "what it needs to do this one thing."

I'm getting there.

These posts are for my own understanding. Reader beware. Info may be wrong but it reflects my current understanding.