我在代码中的很多地方都进行了硬编码比较,对此我并不满意。我正在寻找解决此问题的正确方法。
例子
public class Status {
public static final int ACTIVE = 1,
INACTIVE = 2,
ENDED = 3,
PAUSED = 4,
NEW = 5,
INIT = 6,
STARTED = 7;
private int id;
private String name;
public int getId(){ return this.id; }
public String getName(){ return this.name; }
//get and set the object from the db by the id
public Status(int id){}
}
public class Job {
private int id;
private Status stage;
//get and set the object from the db by the id
Job(int id){}
public boolean isStageStatusEnded(){
return this.stage.getId() == Status.ENDED;
}
}
我有这个数据库表:
mysql> desc statuses;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
+-------+-------------+------+-----+---------+----------------+
mysql> select * from statuses;
+----+----------+
| id | name |
+----+----------+
| 1 | ACTIVE |
| 2 | INACTIVE |
| 3 | ENDED |
| 4 | PAUSED |
| 5 | NEW |
| 6 | INIT |
| 7 | STARTED |
+----+----------+
如您所见,static final int
inStatus
类是表statuses
和return this.stage.getId() == Status.ENDED;
行的精确副本。现在,如果在任何时候值会改变(id
/ name
),我也必须改变static int
's。我不知道我该如何改变它,但如果你知道一种方法 - 分享它。