Search code examples
javacoding-style

Is it okay to create constant variables just for the sake of readability?


Imagine if I have this piece of code:

System.out.println("Is the product:\n"+
                    "1. National.\n"+
                    "2. International.");
int choice = input.nextInt(System.in);
if (choice == 1)
    (...)
else if (choice == 2)
    (...)

So is it okay to do the following?

final int NATIONAL = 1;
final int INTERNATIONAL = 2;
System.out.println("Is the product:\n"+
                        "1. National.\n"+
                        "2. International.");
int choice = input.nextInt(System.in);
if (choice == NATIONAL)
    (...)
else if (choice == INTERNATIONAL)
    (...)

I don't know, I just bought the Clean Code book by Uncle Bob and I started to question myself.


Solution

  • I believe constant is better than the magic number.
    With constant, you control the definition in one place and better naming. It'll affect your further maintainability of the code.
    And try using enum instead of constant in some situations. Enum has more pros than constant.
    In this case enum example is similar to the below code:

    enum UserInput {
        NATIONAL(1), INTERNATIONAL(2), UNKNOWN(-1);
    
        private int input;
    
        public int getInput() {
            return input;
        }
    
        UserInput(int i) {
            this.input = i;
        }
    
        public static UserInput getUserInput(int input) {
            for (UserInput userInput: UserInput.values()) {
                if (userInput.getInput() == input) {
                    return userInput;
                }
            }
            return UNKNOWN;
        }
    }
    
    //main
    public static void main(String[] args) {
            System.out.println("Is the product:\n"+
                    "1. National.\n"+
                    "2. International.");
            Scanner sc = new Scanner(System.in);
            int choice = sc.nextInt();
            switch (UserInput.getUserInput(choice)) {
                case NATIONAL: break;
                case INTERNATIONAL: break;
                default:
            }
        }
    
    
    

    check is for more: Why use Enums instead of Constants? Which is better in terms of software design and readability