Skip to content

Question 9 - Law of Demeter #1

Open
@mesal

Description

@mesal

The "bad" example seems to apply the rule very well. The owner knows nothing about the Engine, just the Car. Moreover, the "good" example is also fine, though the method name suggests that the engine should be started in the Car.

A violation would be as follows:

public class Owner {
    private Car car;

    public Owner() {
        this.car = new Car();
    }

    public void startCar() {
        car.getEngine().start();
    }
}

public class Car {
    private Engine engine;

    public Car() {
        this.engine = new Engine();
    }
   public Engine getEngine(){
     return engine;
   }
    public void start() {
        engine.start();
    }
}

public class Engine {
    public void start() {
        System.out.println("Starting engine");
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions