Skip to content
Advertisement

Is correct to have private method in service layer? [closed]

I am developing a service using Java and Spring Framework, I have business logic at the service layer, but I need to respect the single responsibility and I do a lot of validations and other things, currently, I have a private method the service class to do these things, but I think there are many methods, is it correct to have these methods in service or is it better to have it in another class in custom package?

Advertisement

Answer

Here is a simple example from https://howtodoinjava.com/java9/java9-private-interface-methods/ that demonstrates in which cases you could need somes private methods in your service.

import java.util.function.IntPredicate;
import java.util.stream.IntStream;

public interface CustomCalculator 
{
     default int addEvenNumbers(int... nums) {
       return add(n -> n % 2 == 0, nums);
}

     default int addOddNumbers(int... nums) {
      return add(n -> n % 2 != 0, nums);
     }

    private int add(IntPredicate predicate, int... nums) { 
      return IntStream.of(nums)
        .filter(predicate)
        .sum();
    }
}

In this case it’s not illogical to add this specific private method “add” because it serves in your public methods so it’s not an anti-pattern at all.

The problem could be in testing these private methods in tests.

By contrast, you shouldn’t have too much private methods in service. If so, you should separates these privates methods in an helper class and add them as a dependence in the service. This way, you could test them separately of the service.

Advertisement