How to name repository and service interfaces?

徘徊边缘 提交于 2019-12-12 08:27:55

问题


How do you name repository and service interfaces and their implementing classes?

For example I have a model with the name Question. What would you name the repository (interface and implementation) and the service (interface/implementation).

After reading these posts: Java Interfaces/Implementation naming convention and Interface naming in Java I reconsidered what I already had done :)


回答1:


I think that there are roughly two approaches to naming in DDD:

1) Stereotype based. This is where you include class stereotype in its name. For example:

QuestionsRepository, TaxCalculatingService etc

2) Domain based. In this approach you use only domain language and omit any stereotypes in the class names. For example:

Questions (or AllQuestions), TaxCalculator etc.

Implementation classes would be named like SqlQuestions or InMemoryQuestions.

I tried both but I now prefer 2nd option as it seems to be more aligned with DDD mindset. It seems more readable and have a better signal-to-noise ratio. Following is a quote from a great article on repositories by Phil Calçado:

The concept of a Repository as a list of objects is not too hard to understand but it is very common for those classes to end up with methods that are not related to lists at all.

After coaching many teams in the adoption of a Ubiquitous Language and related patterns, I’ve found out that the best way to make people remember that Repositories are not DAO-like classes starts with how you name them.

Years ago Rodrigo Yoshima told me about his convention when naming Repositories. Instead of the more common naming style displayed below:

class OrderRepository {
   List<Order> getOrdersFor(Account a){...}
}

He promotes this:

class AllOrders {
   List<Order> belongingTo(Account a){...}
}

It looks like a small change but it helps a lot...

The whole article is well worth reading and bookmarking.




回答2:


I personally use FooService, FooServiceImpl, FooRepository and FooRepositoryImpl.

You might argue that the Impl suffix is noise, but

  • there's typically only one implementation, so there's no FirstFooService and SecondFooService
  • the concrete FooXxxImpl types are used nowhere in the code except in unit tests: dependencies are injected, and their type is the interface


来源:https://stackoverflow.com/questions/9400387/how-to-name-repository-and-service-interfaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!