Skip to content
Advertisement

DRY and Typing Specialization

while I was learning PHP, I thought of a (simple?) problem that I could not solve “properly”. Here it is:

  • I would like to create multiple “specialized containers”
  • I would like to avoid duplicated code

For example:

JavaScript

So, I could then create “specialized” bag:

JavaScript

I understood that it’s not possible in PHP, as it is breaking the Liskov Substitution Principle.

For example:

JavaScript

So, I read multiple post on the same “problem”, and none of them provided a clear solution, few mentioned the Observer Pattern, but I do not really see how to apply it. Maybe I am too tired / blinded by the C++ template approach…

Does anyone have any advise, example, or better approach ?

Thanks !

Advertisement

Answer

Yes, specializing collections like this is often the example given for the usefulness of “generic” or “templated” types. Rather than extending the base class, you would specialise it with a type parameter, giving something like this:

JavaScript

Unfortunately, those don’t exist in PHP, and are unlikely to any time soon because there are some fundamental problems with how they would fit into the existing language.

The best you can do in the meantime is to use some machine readable documentation which can be read by various static analysis tools and IDEs. Here for instance is Psalm’s documentation for it; a lot of other tools support the same syntax.

So the above example would be:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement