Extensions shouldn’t be used to group code within the same source fileSW-R1028
Using extensions to group code within the same source file in Swift can lead to several issues and is generally considered a bad practice.
Firstly, it violates the Single Responsibility Principle by coupling unrelated functionality together. This makes the code harder to read, maintain, and refactor.
Secondly, extensions can lead to increased compile times since they are compiled separately from the original type, resulting in longer build times.
Finally, extensions can cause issues when using protocols and type casting. When a protocol extends a type, it is not automatically adopted by the extension. This can lead to unexpected behavior when using the protocol with the extended type.
To avoid these issues, it is recommended to use separate files to group related functionality and avoid using extensions solely for organization. This approach promotes the Single Responsibility Principle and helps to keep code maintainable and scalable.
Bad Practice
// In FileA.swift
class Language {}
extension Language {}
class Vehicle { class Boat {}}
extension Vehicle.Boat {}
Recommended
// In FileA.swift
protocol Human {}
class Box<T> {}
extension Box where T: Tools {}