Skip to content

Instantly share code, notes, and snippets.

@pawelpluta
Created January 19, 2021 20:31
Show Gist options
  • Save pawelpluta/b5e0deb7d17dbff7ae0de63bdebfdc28 to your computer and use it in GitHub Desktop.
Save pawelpluta/b5e0deb7d17dbff7ae0de63bdebfdc28 to your computer and use it in GitHub Desktop.
Article: Tell don't ask - watering before refactor
public class Watering {
private final RaisedBedRepository raisedBedRepository;
private final WaterValveRepository waterValveRepository;
public Watering(RaisedBedRepository raisedBedRepository, WaterValveRepository waterValveRepository) {
this.raisedBedRepository = raisedBedRepository;
this.waterValveRepository = waterValveRepository;
}
public boolean perform(WateringCommand command) {
// cut out: getting raised bed with plants and wattering bed
boolean successfullyWatered = waterBed(bed, valve);
return successfullyWatered;
}
private boolean waterBed(RaisedBed raisedBed, WaterValve waterValve) {
List<Plant> plants = raisedBed.getPlants();
for (Plant plant : plants) {
Integer moisture = plant.getSoilMoisturePercentage();
PlantType type = plant.getType();
boolean needsWatering = false;
switch (type) {
case VEGETABLE:
needsWatering = moisture < 60;
break;
case FLOWER:
needsWatering = moisture < 50;
break;
case TREE:
needsWatering = moisture < 45;
break;
}
if (needsWatering) {
try {
waterValve.setOpen(true);
plant.setSoilMoisturePercentage(moisture + 20);
plant.setWateringCount(plant.getWateringCount() + 1);
Thread.sleep(100); // wait for some water to flow
} catch (InterruptedException e) {
return false;
} finally {
waterValve.setOpen(false);
}
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment