Java - 获取/设置接收和返回"null"的方法

Ant*_*neG 8 java null get set

我是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;
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

[更新]

感谢您的所有意见,想法,更正和建议.以下是此部分代码的更新版本,我对此感到满意,因为它有助于实现其目的(通过实践增加我的理解).

/*
 * 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;
}
Run Code Online (Sandbox Code Playgroud)

hvg*_*des 10

董事会空闲的空间并不例外.它是正常的,对于大多数董事会来说都是如此.你不应该在这里抛出异常; 只应针对意外事件抛出异常,这意外事件表示您尝试执行的操作存在严重问题.

您当然可以将null传递给setter(除了int/long之类的基本类型).

向Space类添加一些便捷方法,一个isEmpty方法可能更好:

public boolean isEmpty(){
   if (this.occupant == null) 
      return true;
   return false;
}
Run Code Online (Sandbox Code Playgroud)

也许还有一个明确的方法

public void clear() {
    this.occupant = null;
}
Run Code Online (Sandbox Code Playgroud)

这样您就不必测试getter结果的无效性,并且您不需要传递null来设置 - 这具有易于测试的额外好处,并创建对您的Space有意义的API类.


Eri*_*rke 6

如果要禁止空值,则应该在setter方法上执行此操作:

public void setOccupant(Piece occupant) {
  if (occupant == null) throw new NullPointerException("occupant");
  this.occupant = occupant;
}
Run Code Online (Sandbox Code Playgroud)

请注意,有些人更喜欢抛出IllegalArgumentException.无论哪种方式,只要有人设置了禁止值,关键是"快速失败".

说完这一切之后,棋盘肯定会有空位,所以允许null似乎更有意义.

我建议你阅读Josh Bloch的"Effective Java,2nd Edition".