Final classes in PHP, Java and other languages

Use final classes or not use final classes? That is the question. And also when and how to do it right.







Why Use Final Classes



Minimize the field of view



When you see a class with a final prefix, you understand that this class cannot be extended by any other, which not only makes it more readable, but also allows you to be sure that the scope of the logic is limited to that particular class.



Encouraging a composition-over-inheritance approach 



The open / closed principle says: a class should be open for extension, but closed for change.



If for any reason (well understanding the reason itself) you decide to use inheritance, then just remove the final keyword and you're done.



If you can't extend the class "by default" (because it's final), you're helping yourself by thinking first of all about using composition instead of inheritance.



Why isn't this class final?



If we are aiming for composition rather than inheritance, then we should try to avoid inheritance as much as possible and only use it when really necessary. OOP inheritance is often misused.



Delusions



When we first studied OOP, we gave a classic example of inheritance. However, when Alan Kay created Smalltalk, inheritance was not his main concept. The main concept was messaging, that is, you can send messages to objects, and they encapsulate data and logic. You can change their behavior using various objects, which is actually composition. But in the end, the concept of inheritance is so popular that it ultimately overshadows composition.



Benefits of using final classes



  • . .
  • . , .
  • . , .
  • . , . .
  • . .
  • . , , .
  • . .




  • , , .
  • , , . , . , , .


[ ]



  • .
  • .
  • Use composition (via DI through the class constructor) to bring things together and minimize complexity.


Subtotal: Interfaces -> Final Classes -> Composition



All Articles