i'm using java, for example, i have 2 tables staff
(id, name, status_id, company_id) and company
(id, name), the corresponding entity looks like:
public class Staff {
private Integer id;
private String name;
private Integer statusId;
private Integer companyId;
private Company company;
}
public class Company {
private Integer id;
private String name;
private List<Staff> staffList;
}
for status_id
of table staff
, 0 means New, 1 represents Active and 2 stands for Inactive
.
I need to show New
, Active
or Inactive
on html page/excel when describe a staff status rather than 0, 1 or 2.
And I have a StaffDto
:
public class StaffDto {
private Integer id;
private String name;
private Integer statusId;
private String companyName;
}
my questions are:
statusName
(New/Active/Inactive) should be in StaffDto
, such that there is no need to calculate status name
according to statusId
on each client, right?statusName
base on statusId
?
I should write code likepublic class StaffDto {
private Integer statusId;
private String statusName;
public String getStatusName() {
switch(statusId) {
case 0: return "New";
case 1: return "Active";
case 2: return "Inactive";
}
}
}
is this a good practice? or something else(e.g. enum) is better?
if the logic of getting status name
is added in StaffDto
, what if there is another dtoj(e.g. ADto
) also need to show status name
, then I have to re-write this logic in ADto
?
what if one client need to show New
, Active
or Inactive
, while another client need to show A
, B
or C
or something else, then what should I return in StaffDto
? do I still return New
, Active
or Inactive
in StaffDto
, and other client need to calculate N
, A
or I
base on statusId
on their client? or should I return something else to client instead of xxxDto?
I too would go for enum
as you mentioned, bind the status code to the name
then, you do not have to rewrite the logic in DTO
s, Make your model have the enum
rather than code or name
enum can have its own methods like getShortName
for different representations
enum Status {
NEW(0), Active(1), InActive(2);
private final int code;
Status(int code) {
this.code = code;
}
public String getShortName() {
return this.name().substring(0, 1).toUpperCase();
}
public int getCode() {
return code;
}
}