Object! = Null check

Is this a check to see if the object passed null or not, or should I use the equals () method?

public void addCard(Card card) throws IllegalArgumentException {
        if (card != null){
            cardList.add(card);
        } else {
            throw new IllegalArgumentException();
        }
    }
+5
source share
6 answers

I prefer to do it like this:

/**
 * Adds a card to the deck.
 *
 * @param the card to add.
 * @throws IllegalArgumentException if the card is null.
 */
public void addCard(final Card card) 
{
    if(card == null)
    {
        throw new IllegalArgumentException("card must not be null");
    }

    cardList.add(card);
}
  • less code to read
  • it separates the error condition from the expected condition (no else = no indent)
  • No one should see what is on line X to see that the map variable was zero = less time for people who are looking for what they did wrong.
  • No need to clutter up the code with useless throw instructions - you should javadoc though with the @throws clause

Other than that, you are doing it right, in my opinion.

+17
source

, . , , , :

public void addCard(Card card) {
    if (card == null) {
        throw new IllegalArgumentException("Attempt to add null card");
    }
    cardList.add(card);
}

, , , - , , . , , :)

, IllegalArgumentException - RuntimeException, , ( ).

+21

Java Josh Blosh :

/**
 * ads a card to card list.
 * 
 * @param card card to add. Can not be null
 * 
 */
public void addCard(Card card) {
      if (card == null) {
           throw new NullPointerException("Card can not be null")
      }  
      cardList.add(card);
    }

, -, RuntimeException. -, NullPointerException, - . -, javadoc, .

+6

commons-lang Validate . :

public void addCard(Card card) {
    Validate.notNull(card);
    cardList.add(card);
}

IllegalArgumentException ( 2- , )

+5

, !=. equals .

+3

If you just want to check if cards are not added, no null, your code will work fine. You just need to make sure that you are processing IllegalArgumentExceptionon call addCard.

+1
source

All Articles