Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java private method signature clarity and better practice [closed]

I received the code review comment for below code snippet -

public void doWork(String a, Integer b) {
    ..
    ..
    SomeService service = getService();
    for (Integer i : numbers) {
      doMoreWork(a, b, service);
    }
}
private void doMoreWork(String a, Integer b, SomeService service) {
    ...
    ...
    ...
    service.doingMoreWork(a, b);
}

review suggestion -

  1. SomeService service = getService(); should be called within doMoreWork for signature clarity. so signature becomes doMoreWork(a, b) which is more clear to understand.

My question -

Since doMoreWork() is happening in a loop, I am passing a service object to it. doMoreWork() is just a private logical unit within a code, it should be fine to carry "service" as method argument. This method is never going to be public. What is the guideline in this case? How the clarity or readability is affected here?

(NOTE :

  1. There is not much performance overhead to getService() call so performance is not a criteria for me here.
  2. Service injection is not an option here. It needs to be fetched the way shown in the sample.
  3. doMoreWork() is not just about calling service.doingMoreWork(). It has some pre-steps to follow.

)

like image 650
Bruso Avatar asked Oct 31 '22 04:10

Bruso


1 Answers

If you refactor doMoreWork() to the following:

private void doMoreWork(String a, Integer b) {
    SomeService service = getService();
    service.doingMoreWork(a, b);
}

then you are making doMoreWork() dependent on getService() for its functionality. If you ever want to use a different method to obtain a SomeService object you will have to refactor this code. So you might want to stick with the original implementation for this reason.

If you are using a framework like Spring, you could have the SomeService injected into your class like this:

@Autowired
private SomeService service;

// use the injected service here
private void doMoreWork(String a, Integer b) {
    service.doingMoreWork(a, b);
}
like image 144
Tim Biegeleisen Avatar answered Nov 15 '22 03:11

Tim Biegeleisen