我到处都了解到,当可以避免使用 if 语句时,使用它们是一种不好的做法。我正在尝试学习如何编写干净的代码,似乎某些设计模式也可能会有所帮助,所以我想知道是否可以重构这段代码以从中删除 if 语句,这是演示这一点的代码:
public class Printer {
private boolean on=false;
private Job currentJob=null;
private String name;
public String getName(){
return name;
}
public void setName(String name) {
this.name=name;
}
public void setOn(boolean _on){
this.on=_on;
}
public boolean getOn(){
return this.on;
}
public void setCurrentJob(Job _currentJob){
this.currentJob=_currentJob;
}
public Job getCurrentJob(){
return this.currentJob;
}
private boolean getOnStart(){
setOn(true);
return getOn();
}
public boolean start(){
setOn(true);
return on;
}
public boolean stop(){
setOn(false);
return !on;
}
public boolean suspend(){
if (!isPrinting()) {
throw new IllegalStateException("Error");
}
currentJob.setState(Job.WAINTING);
return true;
}
public boolean resume(){
if (this.currentJob==null && currentJob.getState()!=0) {
throw new IllegalStateException("Error");
}
currentJob.setState(Job.PRINTING);
return true;
}
public boolean cancel(){
if (this.currentJob==null && currentJob.getState()!=0) {
throw new IllegalStateException("Error");
}
currentJob = null;
return true;
}
public boolean print(Job aJob){
if (isAvailable()){
currentJob=aJob;
aJob.setPrinter(this);
aJob.setState(Job.PRINTING);
return true;
}
System.err.println("Error");
return false;
}
public boolean printingCompleted(){
if (isPrinting()){
currentJob.setPrinter(null);
currentJob.setState(Job.COMPLETED);
currentJob=null;
return true;
}
System.err.println("Error");
return false;
}
public void setSpooler(Spooler spool){
spool.join(this);
}
public boolean isAvailable(){
return on && currentJob==null;
}
public boolean isPrinting(){
return on && currentJob!=null;
}
}
最佳答案
错误或过度使用 if
有时会表明代码有异味,但我不会说应该避免它们。
就你而言,它们确实有点不确定。我会对你的逻辑进行类似的编码。
public void print(Job aJob) {
if (!isAvailable()) {
throw new IllegalStateException("Cannot print when printer not available.");
}
currentJob = aJob;
aJob.setPrinter(this);
aJob.setState(Job.PRINTING);
}
public void printingCompleted() {
if (!isPrinting()) {
throw new IllegalStateException("Attempt to complete printing when no printing in progress.");
}
currentJob.setPrinter(null);
currentJob.setState(Job.COMPLETED);
currentJob = null;
}
这提供了三个好处:
- 可以在其他地方处理/记录错误。
- 您不必返回
true
或false
来指示成功/失败(常见的味道)。 - 每种方法都有一个导出点(众所周知的气味)。
关于java - 如何重构代码以删除 if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30119938/