I have a code which was not refactored at all. I refactored it to some extent..but stuck at a point where I cannot think of anything further.
Tractor.java:
package com.farm;
public class Tractor implements MethodsInterface{
private int[] position;
private int[] field;
private String orientation;
public Tractor(){
position = new int[]{0,0};
field = new int[]{5,5};
orientation = "N";
}
public void move(String command) {
if(command=="F"){
moveForwards();
}else if(command=="T"){
turnClockwise();
}
}
private void moveForwards() {
if(orientation=="N"){
position = new int[]{position[0], position[1]+1}; }else if(orientation == "E"){ position = new int[]{position[0]+1, position[1]}; }else if(orientation == "S"){ position = new int[]{position[0], position[1]-1}; }else if(orientation == "W"){ position = new int[]{position[0]-1, position[1]}; } if(position[0]>field[0]||position[1]>field[1]){
try {
throw new TractorInDitchException();
} catch (TractorInDitchException e) {
e.printStackTrace();
}
}
}
private void turnClockwise() {
if(orientation=="N"){
orientation = "E";
}else if(orientation == "E"){
orientation = "S";
}else if(orientation == "S"){
orientation = "W";
}else if(orientation == "W"){
orientation = "N";
}
}
public int getPositionX() {
return position[0];
}
public int getPositionY() {
return position[1];
}
public String getOrientation() {
return orientation;
}
}
TractorInDitchException.java
package com.farm;
public class TractorInDitchException extends Exception{
}
MethodsInterface.java
package com.farm;
public interface MethodsInterface {
public int getPositionX();
public int getPositionY();
public String getOrientation();
}
What else could be refactored...any suggestions please?
I'd override all the
Exception
constructors in yourTractorInDitchException
.It's not used anywhere. What will cause you to throw that exception?
You can turn clockwise or counterclockwise with finer control than compass points. I'd rewrite that method to pass in a delta in heading angle.
Why the hard-wired position and field arrays? Pass them into constructors. Give some indication as to what they mean.
Not much of an abstraction here. I could think of lots of other things to say about tractors: velocity vectors, acceleration, weight, fuel consumption rate, towing capacity, etc. This feels like an anemic domain model to me. There's little or no imagination at work.