I am currently rewriting one of my projects in Java and want to implement a service layer that will be used by different clients (CLI/GUI/Web) to communicate with my core application. For now it will mostly just delegate the same calls to the Business Model, but I want to add User authentication later on and I read, that a service layer is a good hook to do so.

But I don't know how to write a service layer in code, so that it's easily reusable with the rest of my code.

Here is what I could think of:

  • One Monolithic Service class that encapsulates all functionality of the application (Easy to inject into the client code, since it's one class that can be used to do everything)
  • Multiple Service classes, separating different functionality from each other (Better encapsulation, but more injection code)
  • Multiple Service classes with a Service Provider class that knows all the other service classes (Basically option 2, but easier to inject since the Service Provider can be used to access the whole Service Layer)
  • Static Service classes (Easy to access, but has all the drawbacks of static classes/methods)

Option 2 probably is the way to go, but hearing the term Service Layer, I somehow think of this big class providing me with everything I ever wanted to do with my application.

What is the correct way to implement a Service Layer?

  • 1
    What is the purpose of the injection? – Robert Harvey Jul 18 '16 at 21:47
  • Don't i need the instantiated service objects in my client code to perform some operation? Like you pass the model to the controller in a MVC scenario. I want to be able to also use my service layer locally, not only remotely. – Luca Fülbier Jul 18 '16 at 21:51
  • What problem are you trying to solve? This feels like a solution without a problem. – enderland Jul 19 '16 at 0:56
  • I want to know how to implement a service layer. The options i wrote down were just what i could think of. If one of them is the way to go that's also fine with me. – Luca Fülbier Jul 19 '16 at 6:27
  • 1
    "Multiple Service classes with a Service Provider class that knows all the other service classes " Have used this design in one of my Product which comprised of many modules which want to access the same set of different services. – sameerkn Jul 19 '16 at 8:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.