gpt4 book ai didi

java - java代码的重构

转载 作者:行者123 更新时间:2023-12-01 15:35:09 24 4
gpt4 key购买 nike

我有一段代码根本没有重构。我在某种程度上重构了它......但陷入了我无法进一步思考任何事情的地步。

拖拉机.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;
}
}

拖拉机InDitchException.java

package com.farm;

public class TractorInDitchException extends Exception{

}

方法接口(interface).java

package com.farm;

public interface MethodsInterface {

public int getPositionX();
public int getPositionY();
public String getOrientation();
}

还有什么可以重构...请问有什么建议吗?

最佳答案

我会重写 TractorInDitchException 中的所有 Exception 构造函数。

它没有在任何地方使用。什么会导致你抛出异常?

您可以顺时针或逆时针转动,比罗盘点的控制更精细。我会重写该方法以传递航向角的增量。

为什么要硬连线位置和字段数组?将它们传递给构造函数。给出一些关于它们的含义的指示。

这里没有太多抽象。我可以想到关于拖拉机的许多其他内容:速度 vector 、加速度、重量、燃油消耗率、牵引能力等。对我来说,这感觉像是一个贫乏的领域模型。工作中几乎没有想象力。

关于java - java代码的重构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8981097/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com