开发者

null != null - any ideas on how to re-arrange the code or prevent this?

开发者 https://www.devze.com 2023-02-03 23:54 出处:网络
Currently debugging, and found an if-statement which for no (I thought...) reason gave me an NPE, obviously for a reason. Which seemed to be that the statement turned out to be if(false && (nu

Currently debugging, and found an if-statement which for no (I thought...) reason gave me an NPE, obviously for a reason. Which seemed to be that the statement turned out to be if(false && (null != null || null != Color)).

if(destination != null && (destination.getPiece() != null || destination.getPie开发者_如何转开发ce().getColour() != pieceColour)) - the if-statement

Both destination can be null and piece can be. The getColour() method returns an attribute of type Color from piece, which must be null if the piece is null. The piece at destination has a different pieceColour attribute then the one in the if-statement.

Specifically, how do I re-arrange (destination.getPiece() != null) ?


The logic in the second part of the statement is very confused.

getPiece().getColour() is not valid if getPiece() is null and vice-versa.

In other words, destination.getPiece() == null => destination.getPiece().getColour() is a NPE. Similarly, destination.getPiece().getColour() being anything => destination.getPiece() != null

Only thing that makes sense to me is:

if( destination != null && (destination.getPiece() == null || destination.getPiece().getColour() != pieceColour))

That is, the destination is not null, and either the piece is null or a different color.


Other answers work but for clarity I'd suggest storing the result of destination.getPiece() in a local variable:

if (destination != null)
{
    Piece piece = destination.getPiece();

    if (piece == null || piece.getColour() != pieceColour))
    {
        // Do stuff.
    }
}


Object obj = destination.getPiece();

if obj is null then (obj != null) return false but while checking obj.getColor() will throw NullPointerException. That is why, it should be like this :

if(destination != null && (destination.getPiece() != null && destination.getPiece().getColour() != pieceColour))


The simplest answer would be to split this into two if statements:

if(destination != NULL)
{
  if(destination.getPiece() != null || destination.getPiece().getColour() != pieceColour)
  {
    //Do stuff
  }
}


destination.getPiece() != null || destination.getPiece().getColour() != pieceColour

Should be:

destination.getPiece() != null && destination.getPiece().getColour() != pieceColour
0

精彩评论

暂无评论...
验证码 换一张
取 消