We have answer of your question!

100% solved queries, no empty question

Question: I'm creating a poker client, how can I make the exception handling more clean?


0

Advertisement


I'm checking if the values are valid. The if parts looks still messy for me, checking a lot of || operator, and there is multiple InvalidArgumentException, but I always check for that.

How can this be more clean ?

This is part of my script :

public Card(String cardCode) throws IllegalArgumentException {

    this.cardCode = cardCode;

    String cardColor = this.cardCode.substring(0, 1).toUpperCase();
    String cardValue = cardCode.substring(1).toUpperCase();
    Integer intCardValue = Integer.parseInt(cardValue);

    if (!colors.contains(cardColor))
    {
        throw new IllegalArgumentException("card color isn't valid: " + cardColor);
    }

    if (alphabeticCardValue.get(cardValue) == null || intCardValue > 10 || intCardValue < 2 ) {
        throw new IllegalArgumentException("card number isn't valid: " + intCardValue);
    }
}

Thank you

Question author Dmbdnr | Source

Answer


1


Advertisement


What you actually trying to do is validating the input. Using IllegalArgumentException is not appropriate, imo, because the purpose is of this exception is defined in JavaDoc as follows:

  • Thrown to indicate that a method has been passed an illegal or inappropriate argument.

What I would do is as follows:

  1. Define an enum for possible colors:

    public enum Color { BLACK, RED, ... }
    
  2. Define an enum for possible card values:

    public enum CardValues {
        TWO(2),
        THREE(3); // ...
    
        private int value;
    
        private CardValues(final int v) {
            value = v;
        }
    
        public getValue() { return value;}
    }
    
  3. Change the constructor as follows:

    public Card(Color color, CardValues cardValues) {
        if (color == null || cardValues == null) {
            throw new IllegalArgumentException("....");
        }
        // doSomething else
    }
    

    Note: IllegalArgumentException is an unchecked exception. So you don't need to specify it in the throws clause.

Answer author Ujulu

Advertisement


Tickanswer.com is providing the only single recommended solution of the question I'm creating a poker client, how can I make the exception handling more clean? under the categories i.e java , exception , coding-style , . Our team of experts filter the best solution for you.

Related Search Queries:

You may also add your answer!