Question

Example

I will explain the paradigm below but I am specifically talking about Liferay's Service Builder code for anyone who knows that platform.

Basically in Liferay you can definite a model and it's properties in an xml file. Let's say that we have a Student entity with the following properties: studentId, name, age, grade, gender. From that model Liferay builds the following classes

  • Student (interface for the model)
  • StudentImpl
  • StudentService (interface for the service)
  • StudentServiceImpl
  • StudentServiceUtil

In the StudentSericeImpl class you can write the implementation for any methods you want int your StudentService class. So let's say we have the following interface:

interface StudentService {
   public Student createStudent(String name, int age, double grade, boolean gender);
   public Student getStudent(long studentId);
}

Then your StudentLocalServiceImpl would implement those methods. However in your code you would never initialize your service or create a model like this.

StudentService studentService = new StudentServiceImpl() 
Student chris = studentService.createStudent("chris", 27, 36.23, false);

Instead you would use the util class.

Student chris = StudentServiceUtil.createStudent("chris", 27, 36.23, false);

You can then also implement the StudentService class in a few other ways. For example, you can create a StudentServiceSoap for remote use of a SOAP service.

Do you think this util class is useful, and if so for what reasons?

Was it helpful?

Solution

No I don't think this is good design.

The objects that need to use StudentService should have one injected. They should not themselves use a singleton-style interface like StudentServiceUtil. Here are a few reasons why:

  • If you're using this StudentServiceUtil, how can you configure two objects to use different instances of StudentService?
  • How can you unit-test the code that uses StudentServiceUtil? It's better to inject the interface, StudentService that you can mock directly.
  • The dependency on StudentService will be hidden if you use StudentServiceUtil. It won't be apparent that a class may change or fetch from the StudentService without inspection of the implementation.
Licensed under: CC-BY-SA with attribution
scroll top