A Swift codebase subclasses a base `NetworkService` class for each backend and for a test fake; should the team make classes `final` by default and use protocols with composition instead?
answer
- fake inherits the real init
- every open member is a promise
- Sendable needs final
- inject a protocol-typed dependency
- subclassing when designed for it
basics
~20 sUsually yes in Swift: make classes final by default and inject a protocol-typed dependency, because subclass fakes inherit real state and init, overrides form unchecked contracts, and only final classes can be Sendable. Keep subclassing for hierarchies designed for it.
solid answer
~40 sI'd lean to `final` by default. A Swift subclass inherits every stored property and must run the superclass's designated initializer, so `FakeNetworkService` still builds the real session. Every non-final member is a promise the base class must keep, and if `load()` stops calling an overridden `decode()`, subclasses break silently. Nothing forces `super` calls, and only final classes can conform to `Sendable`, which is an error in Swift 6 mode. Instead, the service is a `final class` that receives a `Transport` protocol in `init`, per-backend differences become values, and tests pass a stub struct. Subclassing stays for classes designed for it, such as framework classes with a documented override contract or a small closed hierarchy that shares stored state and init. Removing `final` should come with a written override contract.
code
swift · 28 linesstruct Request { var path: String }
protocol Transport: Sendable {
func send(_ request: Request) async throws -> [UInt8]
}
struct StubTransport: Transport { // the test fake: no inherited state
var canned: [UInt8]
func send(_ request: Request) async throws -> [UInt8] { canned }
}
final class ProfileService: Sendable { // final: no subclass can change it
private let transport: any Transport
private let basePath: String // per-backend difference as a value
init(transport: any Transport, basePath: String) {
self.transport = transport
self.basePath = basePath
}
func loadProfile(id: Int) async throws -> Int {
let bytes = try await transport.send(Request(path: basePath + "/profiles/" + String(id)))
return bytes.count
}
}
let service = ProfileService(transport: StubTransport(canned: [1, 2, 3]), basePath: "/v2")
print(try await service.loadProfile(id: 7)) // 3go deeper
Recall that final stops subclassing and that a protocol can describe what a dependency must do, so a test can supply its own type.
Explain why a subclass fake runs the real initializer and inherits stored properties, and how injecting a protocol-typed dependency avoids both.
Name the concrete Swift costs: unforced super calls, silent breaks when the base changes its internals, unoverridable extension members, and the final requirement for Sendable in Swift 6 mode.
Set the default and the exception process. Use final by default, require a written override contract to open a class, migrate incrementally, and accept the cost of moving shared code into helpers.
## The situation A `NetworkService` base class holds a session, base URL, headers and a `load`/`decode` pipeline. Each backend subclasses it and overrides a few methods, and the tests subclass it again as `FakeNetworkService`. A design review proposes making classes **`final` by default** and replacing the hierarchy with **protocols and composition**. There is no single right answer, but in Swift the trade-off is concrete. ## What the subclass design costs in Swift 1. **A fake inherits the real thing.** A subclass carries every stored property of its superclass and must run a superclass designated initializer. `FakeNetworkService()` still builds the real session, as the second example shows. Tests pay for the real setup, and they break when the base initializer gains a parameter. 2. **Every non-final member is an extension point.** Each overridable method is a promise that the base class will keep calling it in the same way. If `load()` later stops calling `decode()` internally, every subclass that overrode `decode()` silently stops working. That is the fragile-base-class problem, and the compiler cannot see it. 3. **Nothing enforces `super` calls.** A subclass that forgets `super.prepare()` compiles cleanly. 4. **Concurrency.** A class can conform to `Sendable` only if it is `final`. That is a warning in Swift 5 mode and an error in Swift 6 mode, so a non-final service is awkward to share across tasks once a team adopts the Swift 6 language mode. 5. **Hooks depend on placement.** Non-`@objc` methods declared in extensions cannot be overridden, so the base class's file layout quietly decides which hooks exist. ## What protocols and composition give instead - The varying part becomes a **dependency**: a `Transport` protocol the service receives in its initializer. A test passes a small `StubTransport` struct with no inherited state. - Per-backend differences become **values** (a base path, a header set) or a separate strategy type, instead of overrides. - The service itself is `final` (or a struct), so its behaviour is exactly what its file says, and it can be `Sendable`. - Other modules extend it through the protocol, not through subclassing. Between modules, `public` classes cannot be subclassed outside their module at all, and `open` is the explicit opt-in. The rules are covered with access levels. | | Subclass per backend / fake | Protocol + composition | |---|---|---| | Fake's setup | runs the real `init` chain | builds only what it declares | | Contract | implicit: which methods call which | explicit: protocol requirements | | Base change risk | silent behaviour breaks | compile errors at conformers | | `Sendable` | needs `final`, so no subclasses | final class or struct, straightforward | | Shared stored state | inherited for free | passed in or duplicated | ## When subclassing is still the right tool - A **framework class designed for subclassing**, whose documentation spells out which methods to override and when to call `super`. - A **small, closed hierarchy inside one module** whose members genuinely share stored state and an initializer chain, where reference identity matters and the author owns every subclass. - Overridable **`class func` factories** in a hierarchy that already exists for those reasons. ## A rule a lead can set 1. Write `final class` by default and enforce it in review or with a lint rule. 2. Removing `final` requires a short note: which members are overridable, whether overrides must call `super`, and in what order. 3. Inject dependencies through protocols, and give tests structs or final classes, not subclasses of production types. 4. Migrate incrementally. Mark the service `final`, see which subclasses break, and extract exactly those overridden members into a protocol. The cost is real. Some shared code moves into helpers or protocol extensions, and protocol-oriented design has its own pitfalls, covered with protocols. But the hierarchy's hidden contracts become compile-checked ones.
- What would make you keep a base class instead of a protocol here?If the backends genuinely share a lot of stored state and initialization, the hierarchy is small and lives in one module, and the team owns every subclass. Then a base class with a few documented, deliberately non-final hooks can be simpler than spreading state across protocols. I would still mark every other member `final` and keep fakes out of the hierarchy.
- How do you migrate an existing hierarchy without a big-bang rewrite?Mark the leaf services `final` first; nothing changes for callers. Then extract the members subclasses actually override into a protocol, inject it through `init`, and replace each subclass with a conforming type or a value. Move tests to stub structs as you go. The compiler errors from adding `final` show exactly which overrides exist.
- Does `final` by default matter across module boundaries?Less, because a `public` class already cannot be subclassed outside its module. Only `open` allows that. The default mainly protects code inside your own module, where any visible class can be subclassed and any visible member overridden unless it is `final`.
Subclassing a service is renting a furnished flat: you get every fixture, including ones you never wanted, and the landlord may rewire it while you live there. Composition is buying the one appliance you need and plugging it into a standard socket, the protocol.
- Subclassing the real service is the simplest way to fake it in tests
- Overriding is safe because the compiler checks every override
- final classes cannot be extended or conform to new protocols
- Inheritance should be banned outright in Swift codebases
- A public class can be subclassed from any module that imports it
Assumes Swift 6.4; a non-final class conforming to Sendable is a warning in Swift 5 language mode and an error in Swift 6 mode.