Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Matthias Noback:
Final classes by default, why?
Sep 12, 2018 @ 17:08:54

In this post to his site Matthias Noback makes the argument that, during your normal development, classes should be final by default and only changed if there's a need to extend them.

I recently wrote about when to add an interface to a class. After explaining good reasons for adding an interface, I claim that if none of those reasons apply in your situation, you should just use a class and declare it "final".

[...] For a couple of years now I've been using the final keyword everywhere (thanks to Marco Pivetta for <a href="https://ocramius.github.io/blog/when-to-declare-classes-final/>getting me on track!). When I see a class that's not final, it feels to me like it's a very vulnerable class. Its internals are out in the open; people can do with it what they want, not only what its creator has imagined.

Still, I also remember my initial resistance to adding final to every class definition, and I often have to defend myself during workshops, so I thought it would help if I explained all about it here.

He starts off by talking about the alternative - non-final classes - and some of the issues that can come with it (and class extension). He makes the suggestion that "replacing is better than overriding" and creates less complexity overall. He also answers a question about the use of the "Template Method" design pattern that would allow for improvement from base "skeleton" logic designed to be extended. He covers "composition over inheritance", the use case of extension and how "final" is a better direction.

tagged: final class exposure extension opinion override template composition

Link: https://matthiasnoback.nl/2018/09/final-classes-by-default-why/


Trending Topics: