Hi I need to get name of an employee by his ID by querying to DB. It seems that need a class. But a class with only one method.....is it good idea or what else do you suggest?
views:
81answers:
4If that's the only piece of information you need about an employee, then yes, you only need a static class with a single static method:
public static class EmployeeRepository {
public static string GetEmployeeNameByID(int id) { ... }
}
When you need more, you can do more.
Maybe I'm answering the wrong question, but I can't help to think that maybe you should be looking at this in terms of loading an entire employee record by ID, rather than just getting the name. If so, then the simplest way would be to have a static method in the employee class that does this.
One class per table/entity type is reasonable. I suppose this class would be called a DAO class.
If that class has only one method for now, that is also fine. You can add more later.
No need to make the method static, though.
Specifically, you may want to make it a regular class (with instances), so that you can inject dependencies, such as the DataSource or Connection.
public class EmployeeDAO {
private final DataSource ds;
public EmployeeDAO(DataSource ds){
this.ds = ds;
}
public String getEmployeeNameByID(int id) { ... }
}
Don't use a static class. What happens when you want to use a transaction, or a specific connection? Passing a transaction or connection object into every call quickly becomes a pain.
Best to use a plain old class that you can later expand. Static classes can lead to the temptation to have static variables, which can lead to threading bugs. Personally I like to avoid this.
I'd have added this as a comment on Thilo's answer if I had enough rep :(