【发布时间】:2011-06-04 15:31:37
【问题描述】:
我是 Java 初学者。出于培训目的,我正在尝试为自己构建一个国际象棋游戏应用程序。在我的类 Case 中,这将用于实例化我的所有 64 个案例,我编写了 get/set 方法来查找案例实例中是否有 Piece 占用者。
我读到返回“null”是一种不好的做法,所以我抛出一个异常来表示该案例是免费的。但是,我想知道如何将居住者的指针设置为“null”;当我调用这个方法时,我可以简单地将“null”作为参数吗?
另外,获取/返回“null”是否是一种可接受/良好的做法?
public Piece getOccupant(){
if (this.occupant == null)
throw new IllegalArgumentException(this.occupant + " is Empty");
return this.occupant;
}
public void setOccupant(Piece newOccupant){
this.occupant = newOccupant;
}
谢谢!
[更新]
感谢大家的 cmets、想法、更正和建议。这是我这部分代码的更新版本,我对它感到满意,因为它达到了它的目的(通过实践增加我的理解)。
/*
* Modifiers of Occupant
*/
/**
* Used to find if a Piece is located in this Cell
* @return a Piece reference to the occupant. Will send a
* null pointer if cell is empty
*/
public Piece getOccupant(){
return this.occupant;
}
/**
* Used to set a new occupant in the Cell.
* @param newOccupant is a reference to a Piece instance,
* and should be set to null if the cell is emptied, or using
* the method clear().
*/
public void setOccupant(Piece newOccupant){
this.occupant = newOccupant;
}
/**
* Used to verify if a Cell is empty of any occupant
* @return true if cell is empty.
*/
public boolean isEmpty(){
if(this.occupant == null)
return true;
return false;
}
/**
* Free the cell of any occupant, if any were
*/
public void clear(){
this.occupant = null;
}
【问题讨论】:
-
也许我错了,但我不明白为什么在这种情况下如果单元格没有居住者返回 null 会很糟糕。 1+ 满足您编写更好代码的愿望!
-
也许只有我一个人,但是在没有任何参数的方法中抛出 IllegalArgumentException 是不合适的。
-
请不要有可以返回null的API。这意味着您每次使用时都需要进行检查。