I am new to Java. I am trying to create a chess game application for training purposes. In my Case class, which will be used to initiate all 64 cases of my board, I write get / set methods to find out if there is a blacksmith person in cases.
I read that returning "null" is bad practice, so instead of throwing an exception, I make an exception to show that the case is free. But I am wondering how to set the pointer to "null"; can i just click "null" as a parameter when i call this method?
Also, can accept / return โnullโ an acceptable / good practice?
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 everyone for your comments, ideas, corrections and recommendations. Here is an updated version of my code for this part, and I feel satisfaction from it as it served its purpose (increase my understanding through practice).
public Piece getOccupant(){ return this.occupant; } public void setOccupant(Piece newOccupant){ this.occupant = newOccupant; } public boolean isEmpty(){ if(this.occupant == null) return true; return false; } public void clear(){ this.occupant = null; }
java set null get
Antoineg
source share