私はこのクラスを持っています: 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..
}
}
と:
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) {
}
}
あなたが見ることができるようにJavaがないので、コード
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
}
のこのブロックが反復的であるが、別の方法でそれを置くことはできません静的クラスをパラメータpublic void method(StaticClass) {}
として許可します。
上記のコードをどのようにリファクタリングすることができますか?私の最初の考えは、基本クラスを拡張するシングルトンを作ること、または共通のインターフェースを実装することでした。より良い解決策がありますか?
Enumsにチェックを入れましたか? – mc20
私は列挙型を思い出し、スイッチケースと抽出メソッドについて考えていきます。 – Nico
@ジョージ質問に2つの回答があります。それ以上の説明が必要な場合は、コメントに記入してください。投票は無料です。答えを受け入れることで2点が得られます。あなたは失うものは何もありません。あなたがコメントをしたり、回答を受け入れるのを止めてしまうような心配があれば教えてください。 – CKing