Encapsulation
Encapsulation is one of the fundamental concepts in object-oriented programming (OOP). It describes the idea of bundling data and methods that work on that data within one unit
Encapsulation is not only a matter of getter/setter methods or public/private accessor modifiers. In object-oriented programming, encapsulation not only refers to information hiding but it also refers to bundling both the data and the methods (operating on that data) together in the same object. To achieve good encapsulation, there must a clear distinction between those methods you wish to expose to the public (the so called public interface) and the internal state of an object which must comply with its data invariants. In Scala there are many ways to achieve object-oriented encapulation.
For example, one of my preferred is:
trait AnInterface {
def aMethod(): AType
}
object AnInterface {
def apply() = new AnHiddenImplementation() //exposed to public
private class AnHiddenImplementation { //hidden
var aVariable: AType = _
def aMethod(): AType = {
// operate on the internal aVariable
}
}
}
Firstly, define the trait (the public interface) so to make immediately clear what the clients will see. Then write its companion object to provide a factory method which instantiate a default concrete implementation. That implementation can be completely hidden from clients if defined private inside the companion object.
No comments:
Post a Comment