简体   繁体   中英

Question about Cake Pattern

The Cake Pattern article suggests using traits as namespaces:

trait UserRepositoryComponent {  
  val userRepository: UserRepository  
  class UserRepository {...}
}

trait UserServiceComponent {this: UserRepositoryComponent =>   
  val userService: UserService    
  class UserService {...}  
}

class Context extends UserServiceComponent with UserRepositoryComponent {  
  val userRepository = new UserRepository  
  val userService = new UserService  
} 

However do we really need these "namespace traits" ( UserServiceComponent and UserRepositoryComponent ) if we can do the following?

trait UserRepository {...}

trait UserService {this: UserRepository => 
  ...
}

class Context extends UserRepositoryImpl with UserService

So, my question is when and why we need the "namespace" trait in the Cake Pattern .

There're 2 drawbacks in your approach:

  1. Context gets too much responsibility, mixing up methods from UserRepository , UserService , etc.;
  2. In the first snippet, you can control the order of initialization, or delay it for some components - eg, you can make userRepository a lazy val , which will significantly simplify testing, if you want to test userService only (and, thus, don't want to bootstrap the entire infrastructure);

Though I wouldn't recommend it, in the first case you can also change injecting entities at the runtime (using var s).

As with any pattern, you need it when it makes your code cleaner/more readable/more maintainable/more testable.

In this case, you may well want to create an alternate context for testing purposes, substituting some or all of the components used in the "production" version - a task which is more easily achieved, and more self-documenting, if done via the pattern as outlined in the article.

As Vasil pointed out, the separation of concerns here is a Good Thing(tm), and is pretty much the entire point of the cake pattern.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM