Encapsulation design
Drawing the line between what you want other code to be coupled to and what you don't
Hint: you want people to be coupled to as little as possible so changes to it affects others very little.
the succinct expression or depiction of the essential features of something.
- Google's dictionary
Indications your line is wrong:
- You make a mere performance improvement and other code breaks
- Changing code that doesn't change what the user experiences breaks code
Encapsulation is good for...
- Things with non-trivial implementation details
- anything with internal state
- anything where the API can be simpler than the underlying data structure
- Making invalid states impossible
Encapsulation is bad for...
-
encoding (fix: always have some sort of export function)
-
Understanding, sometimes it's just easier to understand the underlying datastucture (over abstraction). If it's just a body of text maybe it should just be a string. This is perhaps the greatest cost. This can be mitigated by first, avoiding abstraction till the API becomes clear, second, making a very minimal API, third, documenting that API like crazy
-
Using the wrong abstraction. This is the most dangerous part. If you're API is woefully broken and it starts to be depended on, you'll break a lot of code to fix it. This either means you'll never fix it, people will never upgrade, or everyone will have to pay the cost (hopefully small if done soon enough). However this problem is kind of unavoidable because it will either have the interface of the datastucture OR the one you provide. Choose the one that's best.