bulletproof-nodejs icon indicating copy to clipboard operation
bulletproof-nodejs copied to clipboard

How would you prevent a service becoming too large?

Open jshjohnson opened this issue 5 years ago • 1 comments

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?

jshjohnson avatar May 07 '19 08:05 jshjohnson

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 
  }

 
 }
}

santiq avatar May 08 '19 09:05 santiq