Reputation: 757
My question is about using final keyword im Swift code. I know that final helps compiler to compile code faster because of dynamic dispatch. So, if I definitely know that I will not inherit some of my classes, should I make all of them final?
Upvotes: 5
Views: 2622
Reputation: 9925
If your app or a framework uses a protocols over inheritance then you can define your class types as finals.
If you prefer to use an inheritance over protocols and your app or framework is tested with a Unit Tests then don't define your class types as finals when they are used for a dependency objects because they will not be able to be mocked.
Upvotes: 0
Reputation: 36297
There was this protective approach taught by the iOS Stanford course.
The approach was, define all your APIs private
. It increases encapsulation. Later if you needed to give away something then remove the privacy.
Because it's bad to do it the other way around ie design something public and then later change it to private.
Similarly here, I think making a class final
and then later deciding it shouldn't be final is better than making a class non-final, allowing multiple classes to subclass it and then later attempt to revert it back to final
because of some design decisions.
Upvotes: 9
Reputation: 576
You are fine to do so if you are 110% you won't attempt to subclass any of your 'final' classes, as your project won't compile if you do so.
The article below has some great information and should help you decide.
http://blog.human-friendly.com/the-importance-of-being-final
Upvotes: 2