Travis Himes
github.com/thimes/DemeterDemo
a.k.a. "Least Knowledge Principle"
Wikipedia Definition includes:
Consider this snippet of code:
...
if (car.getDrivetrain().getEngine().getGasType() == GasType.DIESEL) {
// TODO: do some cool stuff...
}
...
What stands out?
Rating: BAD
Consider this snippet of code:
...
if (car != null
&& car.getDrivetrain() != null
&& car.getDrivetrain().getEngine() != null
&& car.getDrivetrain().getEngine().getGasType() == DIESEL) {
// TODO: do some cool stuff...
}
...
Now what do you see?
Rating: LESS BAD
Consider this snippet of code:
...
if (car.getTypeOfGasUsed() == GasType.DIESEL) {
// TODO: do some cool stuff...
}
...
That's a lot nicer!
Rating: GOOD
Look at this:
...
if (car.usesGasType(GasType.DIESEL)) {
// TODO: do some cool stuff...
}
...
Do you see the difference?
Rating: BEST
Don't do this...
class Car {
...
boolean willRunOn(GasType gasType) {
return drivetrain != null
&& drivetrain.getEngine() != null
&& drivetrain.getEngine().getGasType() == gasType;
}
...
}
Why not?
Do this...
class Car {
...
boolean willRunOn(GasType gasType) {
return drivetrain != null && drivetrain.willRunOn(gasType);
}
...
}
class Drivetrain {
...
boolean willRunOn(GasType gasType) {
return engine != null && engine.willRunOn(gasType);
}
...
}
class Engine {
...
boolean willRunOn(GasType gasType) {
return correctGasType == gasType;
}
...
}
same name: coincidence, NOT an interface
boolean willRunOn(GasType gasType);
boolean willRunOnDiesel();
boolean willRunOnPetrol();
boolean willRunOnJetFuel();
boolean willRunOnRedBull();
boolean willRunOnPropane();
...
clone github.com/thimes/DemeterDemo