COMP2511
💡 2.4 - Encapsulation
Recap: Program Design
Â
-
Programming via functions
- ​Input, output, processing
- Variables (data) are locally scoped
- No persistent state
-
What if we want persistent state?
- Our functions must have side effects (Imperative Programming)
- Operate on variables / data that lives at a higher scope
- How do we do this for large programs with multiple functions operating on shared mutable state?
- First attempt: A global data store, a series of functions to perform queries and mutations on the data
Decoupling
- Our data structure becomes tied, or coupled to our operations on that data
-
We must introduce layers of abstraction
- Data becomes hidden behind a public interface
- External clients of the Abstract Data Type can only interact with the data via the interface
- Decouples implementations from one another.
- Dependency Inversion: Programming to an interface, not to an implementation
- ​When we make a change in one place, we minimise the number of other places that break
Enforcing Encapsulation via Access Modifiers
- Java provides support for keeping data and methods "hidden" in classes via access modifiers
- Methods and fields (members) in a class can be public, private, protected, default
-
Public - accessible to all
- ​Fields should not be public unless they are immutable static constants (static final)
-
Private - only accessible to other members of the class
- ​Standard practice for all fields in classes
- Allow other classes to interact with the members via getters and setters
Enforcing Encapsulation via Access Modifiers
Â
-
Protected - only accessible to other members of the class or subclass
- Why keep fields hidden from child classes?
-
Default
- ​​Accessible to other classes in the same package
- Methods not intended to be used outside the package should be marked as default
- ​Fields should not be marked as default
Further Design Problems
- Problem 1: Shared mutable state is now wrapped up in classes - how do we propogate state between classes?
- Problem 2: Coupling exists in all shapes and sizes, not just on fields in classes
-
Hyrum's Law
- https://www.hyrumslaw.com
- "The Law of Implicit Interfaces"Â
COMP2511 22T3 - 2.4 - Encapsulation
By npatrikeos
COMP2511 22T3 - 2.4 - Encapsulation
- 246