gpt4 book ai didi

java - 如何重构代码以删除 if 语句?

转载 作者:行者123 更新时间:2023-11-30 08:13:08 24 4
gpt4 key购买 nike

<分区>

我到处都了解到,在可以避免的情况下,使用 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;
}
}

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