Java - 获取/设置方法接收和返回“空”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6237635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 14:58:23  来源:igfitidea点击:

Java - Get/set methods receiving and returning "null"

javanullgetset

提问by AntoineG

I'm a beginner in Java. I'm trying, for training purpose, to build myself a chess game application. Within my class Case, that will be used to instanciate all the 64 cases of my board, I write get/set methods to find if there's a Piece occupant in the instances of the case.

我是 Java 的初学者。出于培训目的,我正在尝试为自己构建一个国际象棋游戏应用程序。在我的类 Case 中,它将用于实例化我板的所有 64 个案例,我编写了 get/set 方法来查找案例中是否有 Piece 占用者。

I read that returning "null" is a bad practice, so I throw an exception instead to signify that the case is free. But, I wonder how to set the occupant's pointer to "null"; can I simply push "null" as a parameter when I will call this method?

我读到返回“null”是一个不好的做法,所以我抛出一个异常来表示这个案例是免费的。但是,我想知道如何将占用者的指针设置为“空”;我可以在调用此方法时简单地将“null”作为参数推送吗?

Also, could taking/returning "null" be an acceptable/good practice?

另外,是否可以接受/返回“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;
}

Thanks!

谢谢!

[Update]

[更新]

Thanks to all of your for your comments, ideas, corrections and recommendations. Here is the updated version of my code for this part, and I feel satisfied with it, as it served its purpose (increase my understanding thru practice).

感谢大家的意见、想法、更正和建议。这是我这部分代码的更新版本,我对它感到满意,因为它达到了它的目的(通过实践增加我的理解)。

/*
 * 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;
}

回答by hvgotcodes

A space on the board being unoccupied is not exceptional. Its normal and will always be true for the majority of the board. You should not be throwing exceptions here; exceptions should only be thrown for an unexpected event that signify a significant problem with what you are trying to do.

板上空置的空间也不例外。这是正常的,并且对于董事会的大多数人来说永远如此。你不应该在这里抛出异常;异常应该只针对表示您正在尝试执行的操作存在重大问题的意外事件引发。

You can certainly pass null to a setter (except for a primitive type like int/long).

您当然可以将 null 传递给 setter(除了像 int/long 这样的原始类型)。

It might be better to add some convenience methods, an isEmpty method to your Space class:

最好在你的 Space 类中添加一些方便的方法,一个 isEmpty 方法:

public boolean isEmpty(){
   if (this.occupant == null) 
      return true;
   return false;
}

and also perhaps a clear method

也可能是一个明确的方法

public void clear() {
    this.occupant = null;
}

that way you don't have to test on the nullity of the getter result, and you don't need to pass null to set -- this has the added benefits of being easily testable, and creates a API that is meaningful to your Space class.

这样你就不必测试 getter 结果的无效性,也不需要传递 null 来设置——这具有易于测试的额外好处,并创建了一个对你的空间有意义的 API班级。

回答by Eric Burke

If you want to forbid null values, you should do it on the setter method:

如果你想禁止空值,你应该在 setter 方法上做:

public void setOccupant(Piece occupant) {
  if (occupant == null) throw new NullPointerException("occupant");
  this.occupant = occupant;
}

Note that some people prefer to throw IllegalArgumentException. Either way, the point is to "fail fast" as soon as someone sets a forbidden value.

请注意,有些人更喜欢抛出 IllegalArgumentException。无论哪种方式,关键是一旦有人设置了禁止值就“快速失败”。

Having said all of that, a chess board certainly can have empty positions, so allowing null seems to make more sense.

说了这么多,棋盘当然可以有空位,所以允许 null 似乎更有意义。

I suggest you read "Effective Java, 2nd Edition" by Josh Bloch.

我建议您阅读 Josh Bloch 的“Effective Java, 2nd Edition”。

回答by Aasmund Eldhuset

Where did you read that recommendation? In my opinion, there is absolutely nothing wrong about returning null, provided that nullconveys some useful information and does not indicate a severe error condition. In this case, it is perfectly normal for a chess cell to not contain a piece, and I would definitely expect getOccupant()to return null in that case.

你从哪里读到的那个推荐?在我看来, return 绝对没有错null,只要它null传达了一些有用的信息并且不表示严重的错误情况。在这种情况下,国际象棋单元不包含棋子是完全正常的,我肯定希望getOccupant()在这种情况下返回 null。

回答by Farshid Zaker

If the caller is aware of NULL return values, it's not bad to return NULL values by callee.

如果调用者知道 NULL 返回值,那么被调用者返回 NULL 值也不错。

回答by Zeym

Instead of returning null or throwing an exception, you should create a class "Empty", "None", "Void", something like that, that you would assign to all your Case that are empty.

您应该创建一个类“Empty”、“None”、“Void”,而不是返回 null 或抛出异常,您将分配给所有空的 Case。

回答by Abhishek Gayakwad

small suggestion no need of if block, you can simplify your code by simply returning the output of expression

小建议不需要 if 块,您可以通过简单地返回表达式的输出来简化代码

public boolean isEmpty(){
    return this.occupant == null
}