mardi 7 février 2017

Handle constants in Java

I have this classes: package util;

public final class Constant {

    private Constant() {
        throw new AssertionError();
    }

    public static class Product {
        public static final String CODE = "Product";
        public static final String A = "product_5g2g";
        public static final String B = "product_a45h";
        public static final String C = "product_a3ag";
        //more constants..
    }

    public static class Employee {
        public static final String CODE = "Employee";
        public static final String A = "employee_1g3f";
        public static final String B = "employee_h52d";
        public static final String C = "employee_h5d2";
        //more constants..
   }

    public static class Client {
        public static final String CODE = "Client";
        public static final String A = "client_h5ad";
        public static final String B = "client_1df1";
        public static final String C = "client_6g23";
        //more constants..
    }
}

and:

package util;

import util.Constant.*;

public class Main {

    public void run() {
        if (isSelected(Product.CODE)) {
            if (isSelected(Product.A) || isSelected(Product.B)) {
                //do something
            }
            compute(Product.C);
            //more similar instruction that use constants from Product class
        }
        if (isSelected(Employee.CODE)) {
            if (isSelected(Employee.A) || isSelected(Employee.B)) {
                //do something
            }
            compute(Employee.C);
            //more similar instruction that use constants from Employee class
        }
        if (isSelected(Client.CODE)) {
            if (isSelected(Client.A) || isSelected(Client.B)) {
                //do something
            }
            compute(Client.C);
            //more similar instruction that use constants from Client class
        }
    }

    public boolean isSelected(String s) {
        return true;
    }

    public void compute(String s) {

    }
}

As you can see, this block of code

if (isSelected(StaticClass.CODE)) {
    if (isSelected(StaticClass.A) || isSelected(StaticClass.B)) {
        //do something
    }
    compute(StaticClass.C);
    //more similar instruction that use constants from Product class
}

is repetitive, but can't put it in a separate method because java don't permit a static class as a parameter public void method(StaticClass) {}.

How can I refactor the above code? My first thought was to make Singletons that extend a base class, or implement an common interface. There is a better solution?

Aucun commentaire:

Enregistrer un commentaire