Michael
Michael

Reputation: 10303

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.

Upvotes: 3

Views: 821

Answers (2)

Vasil Remeniuk
Vasil Remeniuk

Reputation: 20627

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 - e.g., 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 vars).

Upvotes: 5

Kevin Wright
Kevin Wright

Reputation: 49705

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.

Upvotes: 2

Related Questions