Where to add magic numbers in my project?

423 views Asked by At

I have a lot of magic numbers and strings in my project and I would like to replace them with constants. The thing is I remember I used, a lot of time ago, a class to hold all the constants that I would call in the code statically. It is a university project and I need to use Java design patterns.

I would like to know what's the best way to write the constants given the fact that many magic numbers are used across different classes, so I don't want to declare constants locally in each class.

I've read about resource files implemented via singleton classes, but I can't figure out why using a singleton class that makes calls to it longer than needed.

I'm writing code in Java for the server and Android for the client in case you need this info.

1

There are 1 answers

3
Dmitrii B On BEST ANSWER

use Enam or Class file for it. Every one of your packages can have some class for example it:

@NoArgsConstructor(access = PRIVATE)
public final class Constant {

    @NoArgsConstructor(access = PRIVATE)
    public static final class Date {

        public static final int Q_ONE_MONTH = 3;

        public static final int Q_TWO_MONTH = 6;

        public static final int Q_THREE_MONTH = 9;

        public static final int Q_FOUR_MONTH = 12;
    }

    @NoArgsConstructor(access = PRIVATE)
    public static final class Quarter {

        public static final int Q_ONE = 1;

        public static final int Q_TWO = 2;

        public static final int Q_THREE = 3;

        public static final int Q_FOUR = 4;
    }
}

These classes can be in each of your packages for everyone on their own or one class in a common project module.