-
Notifications
You must be signed in to change notification settings - Fork 2.9k
When To Use Extensions
Extensions can be very useful when used sparingly, however when they are over used they can obscure code making the project much harder to read.
An example of a good way to use extensions is to add default behavior to a protocol when that functionality will be the same in many or all objects that conform to the protocol. This reduces code repetition, it’s easy to find when it lives right next to the protocol itself and it is easy to bypass because the object conforming to the protocol can still provide its own implementation when needed, thus it does not harm the future maintainability of the code or the testability of the code.
Another acceptable use case is when adding functionality to a class or struct that the codebase does not own, for example extending a UIKit object like UIButton. However we should be very careful with this use case because it is very easy to overuse and can obscure functionality as it can be hard to find if you don’t already know it exists. When adding an extension like this please consider first if the functionality you want to add will be used in multiple parts of the code base. If it is the case that it will only be used in the local context you are working in then please opt to create a local helper method in the area it is needed instead of as an extension.
Please don’t use extensions as a way to reduce the number of lines of code in a file by creating an extension of the class in a new file. This makes the code hard to find and it just obscures the real problem that the class you are extending is too big, has too much responsibility and should probably be broken down.
Please don’t use extensions as a way to improve navigation within a class or to manage protocol conformance. This obscures protocol conformance on a class as they will be scattered throughout the file and makes it harder to read or reason about what a class is doing.
Instead use // MARK: -
to add sensible break lines within a file.