Skip to content

Commit 9555ed6

Browse files
authored
Merge pull request #8308 from woocommerce/issue/2228-docs-final-classes
Document that classes should be final by default
2 parents 0340eb2 + 9e5fb6b commit 9555ed6

File tree

1 file changed

+8
-0
lines changed

1 file changed

+8
-0
lines changed

docs/choosing-between-structs-and-classes.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,11 @@ But consider using `class` instead if:
1010
- You need to manage mutable states. Especially if there are more than a few `mutating` functions, the `struct` becomes harder to reason about.
1111
- You have to set a `struct` property declaration as `var` because it has a `mutating` function. In this case, a constant (`let`) `class` property may be easier to reason about.
1212

13+
### Classes should be marked as `Final` by default
14+
15+
When using classes, these should be marked as `final` by default so their behavior cannot be altered by subclassing and/or overriding. There's a few reasons for that:
16+
17+
- It favors composition over inheritance
18+
- The class could be missused or abused when subclassed or overriden, which could be problematic if the class is doing anything important. By making it `final` we disallow this at compiler time, and enforce that the class has to be used as it was written.
19+
- Marking a class as `final` tells the Swift compiler that the class methods should be called directly rather than looking them up in a method table (static vs dynamic dispatch), which [reduces function call overhead and increases performance](https://developer.apple.com/swift/blog/?id=27)
20+
- If inheritance is necessary later on, it can always be allowed, but the `final` modifier will create a reminder of its necessity and refactoring

0 commit comments

Comments
 (0)