Search code examples
javaencapsulationaggregation

aggregation breaks encapsulation


I have been reading books trying to understand the various aspects of aggregation and composition.However I came across a point where I felt like aggregation can enhance loose coupling but can also break encapsulation.

Enhance loose coupling.

public class Car{
    private Engine engine;
    Car(Engine e){
        this.engine=e;
    }
}

In above any implementation of Engine class can be created and pushed to Car object at the time of creation, and since the Engine instance can live without car thus it is a perfect example of aggregation. ( this example may not be a great realworld example , but I think I made my point)

Now the client code has the full control over the Engine Object, thus it can change few states of the engine object passed to the Car,And Car's implementation would break the encapsulation since its object or state ( which is Engine) is no more has the right integrity in the Car.

is my understanding correct ?


Solution

  • The Engine can be broken by Car only if it is mutable, i.e. car can change engine's state. However you can either define immutable class Engine (that has only getters to access state and business methods that do not change state) or create interface Engine implemented by class EngineImpl. EngineImpl is not immutable. It includes functionality that can change its state. However it implements interface Engine that exposes only "immutable" methods towards client. So, car cannot change state of EngineImpl hidden behind read-only interface Engine. In this case the encapsulation is not broken.

    You are right: that this is not the real-world example: in real world driver controls engine via interface provided by his car and can break the engine :(