tags:

views:

81

answers:

4

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?

+1  A: 

If 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.

John Saunders
A: 

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.

Steven Sudit
If he'd wanted more than the name, he might have said so.
John Saunders
odiseh seemed interested in doing this in a clean, object-oriented way, so I think that the return type is fair game for analysis. Realistically, a single string isn't a good way to hold a person's name, so there's likely to be an Employee class anyhow, which provides a natural place for a static lookup method. If we need to support multiple sources, we can allow an overload with a repository interface. This likewise addresses the issues David Martin brings up, as the repository would deal with the transactioning, if any.
Steven Sudit
+1  A: 

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) { ... }

 }
Thilo
+1  A: 

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 :(

David Martin