bulletproof-nodejs
bulletproof-nodejs copied to clipboard
How would you prevent a service becoming too large?
Hey - thanks for this.
I have a question: how would you go about splitting up a "service" to prevent it getting too large considering a service could potentially contain all business logic?
You can do is use the Facade pattern.
"A facade is an object that provides a simplified interface to a larger body of code"
For example, imagine that you have the UserService class that became too large because of Search methods, (SearchByLocation, SearchByRelatedFriends, SearchByWhatever, )
You move the related methods to the UserSearchFacade, and then just inject the main on to the service.
Original service
class UserService {
constructor(private userModel){}
public SignUp() {}
public LogIn() {}
public Remove() {}
public SearchById(){}
public SearchByLocation(){}
public SearchByRelatedFriends(){}
private search() {}
}
User Search Facade
class UserSearchFacade {
constructor(private userModel){}
public SearchById(){}
public SearchByLocation(){}
public SearchByRelatedFriends(){}
private search() {}
// ... more search related methods
}
New User Service
class UserService {
constructor(private userModel,
private userSearchFacade){}
public SignUp() {}
public LogIn() {}
public Remove() {}
public Search(how, selector) {
switch(how) {
case 'location':
return this.userSearchFacade.SearchByLocation(selector)
break;
// ... more cases
default:
return this.userSearchFacade.SearchById(selector)
break
}
}
}