Reputation: 2060
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()));
}
}
Upvotes: 0
Views: 501
Reputation: 543
Depends on the goal of your API.
Does the caller always have a DocumentID
and never a Document
instance?
Document
instance and only return a status).Does the caller sometimes have a DocumentID
and sometimes a Document
instance?
Document
class to include a getStatus()
method. That way if the caller has a Document
instance they can call document.getStatus()
instead of calling your service.Upvotes: 0
Reputation: 1412
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.
Upvotes: 1