I am a novice programmer learning how to design API for my module. I thought of 2 types of service class to provide a API for other classes to use.
First example handles the logic by parameters, the second example handles by object way.
Which is a better approach / design for me to provide business methods for other classes to use?
As a general rule of thumb which should I use?
Example 1 – Service A
public class ServiceA {
private SampleDAO dao = new SampleDAO();
private static final String DRAFT_STATUS = "DRAFT";
private static final String APPROVED_STATUS = "APPROVED";
private static final String SUBMITTED_STATUS = "SUBMITTED";
public boolean isDocumentApprove(String documentId) {
Document doc = getDocument(documentId);
return (APPROVED_STATUS.equals(doc.getStatus()));
}
public boolean isDocumentDraft(String documentId) {
Document doc = getDocument(documentId);
return (DRAFT_STATUS.equals(doc.getStatus()));
}
public boolean isDocumentSubmited(String documentId) {
Document doc = getDocument(documentId);
return (SUBMITTED_STATUS.equals(doc.getStatus()));
}
private Document getDocument(String documentId) {
return (dao.getByDocumentId(documentId));
}
}
Example 2 – Service B
public class ServiceB {
private SampleDAO dao = new SampleDAO();
private static final String DRAFT_STATUS = "DRAFT";
private static final String APPROVED_STATUS = "APPROVED";
private static final String SUBMITTED_STATUS = "SUBMITTED";
public Document getDocument(String documentId) {
return (dao.getByDocumentId(documentId));
}
public boolean isDocumentApprove(Document doc) {
return (APPROVED_STATUS.equals(doc.getStatus()));
}
public boolean isDocumentDraft(Document doc) {
return (DRAFT_STATUS.equals(doc.getStatus()));
}
public boolean isDocumentSubmited(Document doc) {
return (SUBMITTED_STATUS.equals(doc.getStatus()));
}
}
If I had to choose, i would pick the the second example, because it contains less code duplication. In the first one, there is the same
Document doc = getDocument(documentId);statement in every method. So, here the general principle is “don’t repeat yourself”.Furthermore, in the first version you can pass any garbage as a string to the methods. Although you can pass null in the second version too, but it is easier to check for null than for invalid ids.