Let's say I have a class car which has a motor.
The class motor is defined like this:
class Motor {
private String code;
public String getCode() {
return code;
}
}
How should the class car be defined, assuming we need to access the motor's code from whoever has access to the car?
class Car {
private Motor motor;
public Motor getMotor() {
return motor;
}
}
Which allows for this:
Car car = ...
Motor motor = car.getMotor();
String code = motor.getCode();
Or
class Car {
private Motor motor;
public String getMotorCode() {
return motor.getCode();
}
}
Which allows for this:
Car car = ...
String code = car.getMotorCode();
I assume the second option is best since it follows the Law of Demeter, which the first one doesn't. On the other hand, should the outer class define every single getter from the inner class(es)? Should the motor ever be exposed with a getMotor()
?
Aucun commentaire:
Enregistrer un commentaire