Question

I would like my project to adhere to the SOLID principles and write clean code, but I am still not very clear on when I should separate from the service layer.

I have a Web Api 2.0 Controller called ParkingController which has the following method:

public List<Week> GetParkingPlaces(DateTime date)
{
    date = DateTime.Now.ToWesternEuropeStandardTime().Date;
    return _service.GetWeeks(date);
}

And the service methods:

public List<Week> GetWeeks()
{
    // About 10 lines of logic here, calling CreateDaysInWeek and looping here
    return weeks;
}

private Week CreateDaysInWeek(DateTime startOfWeek, List<ParkingPlace> parkingPlaces)
{
    // About 10 lines of logic to Create days in week.
    return new Week(daysInWeek);
}

I separated the method GetWeeks into two methods, one being a private method to make my code cleaner and more understandable. Now when I see this private method I think hmm am I violating SRP?

My question is: Should I separate these functions into their own class like WeeksWithDaysCreator or even WeeksCreator calling DaysCreator? Or should I just leave this in the Service Class?

Edit: I want to know how much code I should put in my Service layer and when I should separate code into its own class.

Was it helpful?

Solution

You should extract code into its own class if it is conceivable that it would be called by code other than the current caller, in particular by code that doesn't do essentially the same thing.

A perfect example for code that should be independent would be code that simply constructs the days of the week. Many conceivable callers could use this, therefore it is a good idea to factor it out even if there is actually only one caller and this will probably not change. The reason is simply that it is easier to think about only one task at a time: either date calculation or parking logic.

If your code does date manipulation and parking business logic it is less clear that this is functionality that could be used differently. You know better than we whether this is the case, but it might be.

A counterexample is a routine that performs complicated calculations on a line item in a complicated workflow (e.g. declaring taxes, verifying space shuttle code). Such special-purpose code is almost certainly of no use outside the context it is now in. Such code should certainly go into its own method, but a separate class is often overkill.

Licensed under: CC-BY-SA with attribution
scroll top