Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Methods: One vs Many

getEmployeeNameByBatchId(int batchID)
getEmployeeNameBySSN(Object SSN)
getEmployeeNameByEmailId(String emailID)
getEmployeeNameBySalaryAccount(SalaryAccount salaryAccount)

or

getEmployeeName(int typeOfIdentifier, byte[] identifier) -> In this methods the typeOfIdentifier tells if identifier is batchID/SSN/emailID/salaryAccount

Which one of the above is better way implement a get method?

These methods would be in a Servlet and calls would be made from an API which would be provided to the customers.

like image 446
kittugadu Avatar asked Sep 17 '08 07:09

kittugadu


2 Answers

Why not overload the getEmployeeName(??) method?

getEmployeeName(int BatchID)
getEmployeeName(object SSN)(bad idea)
getEmployeeName(String Email)
etc.

Seems a good 'many' approach to me.

like image 110
Stephan Avatar answered Sep 28 '22 07:09

Stephan


You could use something like that:

interface Employee{
    public String getName();
    int getBatchId();
}
interface Filter{
    boolean matches(Employee e);
}
public Filter byName(final String name){
    return new Filter(){
        public boolean matches(Employee e) {
            return e.getName().equals(name);
        }
    };
}
public Filter byBatchId(final int id){
    return new Filter(){
        public boolean matches(Employee e) {
            return e.getBatchId() == id;
        }
    };
}
public Employee findEmployee(Filter sel){
    List<Employee> allEmployees = null;
    for (Employee e:allEmployees)
        if (sel.matches(e))
            return e;
    return null;
}
public void usage(){
    findEmployee(byName("Gustav"));
    findEmployee(byBatchId(5));
}

If you do the filtering by an SQL query you would use the Filter interface to compose a WHERE clause.

The good thing with this approach is that you can combine two filters easily with:

public Filter and(final Filter f1,final Filter f2){
    return new Filter(){
        public boolean matches(Employee e) {
            return f1.matches(e) && f2.matches(e);
        }
    };
}

and use it like that:

findEmployee(and(byName("Gustav"),byBatchId(5)));

What you get is similar to the Criteria API in Hibernate.

like image 22
jrudolph Avatar answered Sep 28 '22 08:09

jrudolph