Object-oriented – Is it good practice to declare and set properties in abstract classes

object-orientedPHPsolid

I am using PHP and designing some abstract classes.

I can declare properties with constant values within my abstract class and access/overwrite them from any class which extends this without re declaring them within any of the extending classes.

A benefit to this is less repetitive typing but the downside that overtime the original structure/layout of these abstract properties is forgotten and could be left at there default static values or even forgotten(not used) completely.

How is this handled in professional environments? I assume this has been thought out before and is either favored or isn't?

I am trying to adhere to good OOP principles/rules such as SOLID, DRY and KISS but I haven't seen this specific issue talked about in these. (perhaps I missed it when researching?)

Best Answer

This may be a personal preference, but I avoid having base classes for the sake of sharing properties. Particularly in data classes. I don't mind the repetition, and I avoid locking my classes into a fixed "data" hierarchy.

There are enough problems with inheritance, particularly over time as the code base grows, that I am reluctant to share methods through a class hierarchy, and even more reluctant to share properties through a class hierarchy.

...

Hm. I just noticed that you mentioned "static" properties. Rather than static (i.e. global) properties in a base class, you're better off with a separate, single instance of something dispensed by a factory. Make sure you provide for concurrency to avoid race conditions.

Related Topic