Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use "final"?

Tags:

php

final

Is there any particular reason I should declare a class or a method final in day-to-day programming (web or otherwise)? Please provide a real-world example where it should be used.

BTW, I'm asking because I'm trying to pick an 'obscure' keyword and master it.

like image 471
Michał Tatarynowicz Avatar asked Feb 08 '09 20:02

Michał Tatarynowicz


2 Answers

It prevents other programmers from doing stuff with your classes that you don't intend for them to do. So rather than making a comment saying "don't use this class to do XXX", you can design it in such a way that they won't be tempted to override it and abuse it in that manner.

Edit: Since an example is requested, I'll describe a case where you might find this keyword handy... say you have a class which defines how two objects may communicate with each other, say, a listener and notifier. The listener class must obviously allow inheritance, but you might want to make the notifier class final so that it must be used in a "has-a" relationship. This way, you can make some assumptions from your listener objects about the nature of the messages they are receiving.

Otherwise, it would be possible to inherit from that class, do all sorts of crazy stuff like extend the messages and so on. If you don't want other programmers to do that, then you could make the class final. Also, this might make a lot more sense in a widely-used public API, as it also allows other programmers to readily understand which classes are ok to subclass.

Another example -- say you have a buffer-based stream processor, and inside of your read()/write() method, you maintain some data about the current state of your object (ie, the current byte or whatever). There is no way to guarantee that anyone subclassing this class would call the super's methods during processing -- and since such a class likely only contains a few methods, it's better to just make the whole thing final instead of each method. This again forces people using the class to "has-a", not "is-a", and thus, can control how you expect the code will be executed.

I would agree with you in that making an entire class final is probably something which you'd need to do once in a blue moon, but it's nice that PHP has this capability should you choose to exercise it.

like image 117
Nik Reiman Avatar answered Oct 12 '22 11:10

Nik Reiman


"Enforce Composition over Inheritance" puts it rather succinctly. You guarantee a certain behavior of your class that nothing else can interfere with, which, as the next section explains, can have security benefits as well.

like image 36
Sören Kuklau Avatar answered Oct 12 '22 13:10

Sören Kuklau