In my previous post on when you should add final, there is a comment from Dmitry:

public classes or properties are already not overridable. You use open for that.

He is correct, as per the design of Swift’s 5 access levels.

Yet also not entirely correct, because a public (or internal) can be overridden from the same module 😂

That’s why there is public final

final is to prevent overridability, especially in the SAME module. It prevents developers working on the same module from overriding it in the future.

On the other hand, public alone is to prevent overridability from OTHER modules.

The combination of public final prevents overridability totally, because of final keyword. The public keyword merely provide access for external modules.

What is open

The only way to override in OTHER modules is to use open instead of public.

You also can’t write open final because that would be a conflict between the 2 keywords.

When to use final

To emphasize again, there is no need to add final just to optimize for speed, as the compiler can infer most of the time (except when there is public access, hence public final does optimize for speed).

But before you rush off to add final to every public.. do remember the primary value of final is to prevent developers (yourself/colleagues) working on the same module from overriding. The benefit from speed optimization is secondary.

Also remember, it doesn’t stop your fellow developers from removing the keyword if they deemed safe to do so. I did remove many unnecessary finals 😆

Therefore the rule when writing a module is to avoid final, unless you’re 100% sure it will be problem when overridden by fellow developers.




Back to Home