OO Design - shortening a long list of methods
I have a simple application that loads data from an XML file into a database.
public class EmployeeLoader()
{
public void LoadEmpoyees()
{...}
public void LoadSalaries()
{...}
public void LoadRegistrationData()
{...}
public void LoadTaxData()
{...}
}
Is it good to have multiple "Load" methods as it sounds like a code smell since I have tweney Load methods? If so, how do you make the code more readable? Does each Load method load data into the corresponding table in the database via the repository?
a source to share
Actually, if it's broken down into well-known steps, it's very readable.
See this article: http://www.codinghorror.com/blog/2008/07/coding-without-comments.html
a source to share
Having them separate makes it more readable than the loading method with lots of templates to manage different scenarios
You have something like
public void Load() {
if (condition1 that makes me know I'm loading an employee) {
//whatever applies to this condition
}
if (condition2 that makes me know I'm loading salaries) {
//whatever applies to this condition
}
if (condition3 that makes me know I'm loading registrationData) {
//whatever applies to this condition
}
if (condition4 that makes me know I'm loading taxData) {
//whatever applies to this condition
}
}
Ugh.
Even if methods do very similar things, it might be a good idea to separate them and call similar methods. This way, if something changes, it will be a simple refactor =).
Finally, if the class gets too large (too many responsibilities), you might consider moving to more classes with more specific responsibilities.
a source to share
I am assuming that the loaded data will be saved in local fields / dictionaries and then used in another method.
if so, you can lazy load the values as needed.
public class EmployeeLoader
{
private List<String> _Employees = null;
public List<String> Employees
{
get
{
if (_Employees == null)
{
LoadEmployees();
}
return _Employees;
}
}
private void LoadEmployees()
{
//Load Data
}
}
in addition to the fact that you can still have one Load () method to force the values to be loaded into those backing fields.
a source to share