Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Implementing a UserDetailsService

Why do we separate the UserService and UserServiceImpl?

I am still new to Spring and Java best practices. Would it not be easier just to have UserServiceImpl implement the UserDetailsService and our findByUsername method in there? Maybe we plan on extending UserService later but right now it is pretty simple.

1 Answer

I think it's to go along best practices, to code against an interface. Imagine the following two scenarios:

  1. I put a pencil on a table and tell you to write something down.
  2. I put a pen on a table and tell you to write something down.

You would be able to write something down because both pen and pencil both "implement" the action "write" even though in different ways. You wrote with whatever was on the table, it didn't really matter what, because you know both pen/pencil can do it.

Now imagine this scenario:

  1. I put a pencil on a table and tell you to write something down a pen. You won't be able to do it because there is no pen. Because my instructions were tied to the concrete implementation of "write".

The same goes with the Service (write something down). The actions are geared towards it, so it doesn't matter which ServiceImpl (pen/pencil) it's being used. It allows for it to be changed in the future without breaking the code.

The benefit is that it allows to change concrete implementations without breaking existing code, it becomes flexible and extensible.

Hope it made more or less sense.

Thank you Pedro!

I was familiar with with programming to an interface but I figured that would have been done for more complex objects. Is the use of 'Impl' a fairly common Java naming convention?

I think the suffix β€œImpl” for a concrete implementation is as popular as the prefix β€œI” for an interface. It all depends on the coding rules that you choose to adapt. With that being said and for my Treehouse projects and I try to avoid those kind of notations as the IDE can tell apart what is what. I’m also a fan of Uncle Bob and try to follow his guidelines from Clean Code one of which being avoiding encodings/notations, which is the case. But then again, if coding in a Team then I think personal preferences should come second to the team’s already established style.

Thank you for the clarification Pedro!