Results 1 to 9 of 9
  1. #1
    Pavlo is offline Member
    Join Date
    Dec 2012
    Posts
    28
    Rep Power
    0

    Question Need help with code duplication reduce

    Hi

    I have two methods and they do almost same thing, but at some most inner nested level one of method have additional command.

    Java Code:
    method2(){
      ... same code ...
      for {
        ... same code ...
        if{
          ... same code ...
        }
      }
    }
    Java Code:
    method2(){
      ... same code ...
      for {
        ... same code ...
        if{
          ... same code ...
    
          differentOperation()
    
        }
      }
    }
    I would like to reduce code duplication here. What I was able to do is just create one method instead of two, which accepts boolean parameter, which indicates should differentOperation() method be called or not. But I not sure this is the best practice. Is it possible to solve this better somehow like with inheritance or in functional way? This code will be implemented in Spring @Service (I do not know is this can be used somehow here).

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    25

    Default Re: Need help with code duplication reduce

    You can do it if you pass in a function to the common method.
    The type of the interface depends on what is going to be done. A Consumer if you just have a single parameter with no return, for example.
    Java Code:
    private void method(Consumer<SomeClass> consumer) {
      ... same code ...
      for {
        ... same code ...
        if{
          ... same code ...
          consumer.apply(something);
        }
      }
    }
    Then your main methods would simply give a consumer:
    Java Code:
    public void method1() {
        method(method(t ->someMethodThatDoesTheExtraBits(t)));
    }
    
    public void method2() {
        method(method(t -> {}));
    }
    the first of which could be simplified by replacing the lambda with a method reference.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    Pavlo is offline Member
    Join Date
    Dec 2012
    Posts
    28
    Rep Power
    0

    Default Re: Need help with code duplication reduce

    This approach seems good for me. I tried and it works, but still not sure I did it the best possible way.

    The thing is I have to call Service.method(...) from other class (Caller). This makes myRepository property not in scope of lambda in Caller class, so I have to make a Map<String, Object> to pass parameter and Service instance object reference to lambda function body. The Service reference just used to access myRepository reference. I used type cast here. Could it be better?

    Java Code:
    public class Caller{
    
      Service serviceInstance;
    
      ...
    
      public void process(){
        serviceInstance.method(param -> {
          //take parameters from Map
          Map<String, Object> parametrers = (Map<String, Object>)param;
          String companyName = (String)parametrers.get("companyName");
          Service service = (Service)parametrers.get("service");
          // is this proper way to access myRepository ?
          service.myRepository.save(companyName);
        })
      }
    }
    Java Code:
    public class Service{
    
      @Autowired
      MyRespository myRepository;
    
      ...
    
      method(Consumer<SomeClass> consumer){
        //put parameters to Map
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("companyName", companyName);
        parameters.put("service", this);
        consumer.apply(parameters);
      }
    }
    Also I have to always create Map<String, Object> parameters in method body, because Service class not know will the consumer do anything or it is just empty lambda body {}.

  4. #4
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,192
    Rep Power
    12

    Default Re: Need help with code duplication reduce

    I think you're spending too much time worrying about efficiency where it probably doesn't matter. I would probably have used a switch on an enum myself because as much
    as I like Lambdas, etc, they can introduce lots of extra byte code in Java programs. But if you are intent on optimizing I would wait until the application is done and then run a profiler to see where any bottlenecks are. As Knuth said, "premature optimization is the root of all evil.'

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  5. #5
    Pavlo is offline Member
    Join Date
    Dec 2012
    Posts
    28
    Rep Power
    0

    Default Re: Need help with code duplication reduce

    It depends on what you want to achieve with optimization. I would say application execution time, or byte code is not a question here (at least in my case).

    The boolean flag as method input parameter, means, that you have to implement both cases logic in one method body (or at least put switch there). This makes it larger and harder to debug and test (Tight couple).

    Think about lambdas approach proposed. Now I am free to pass in method any function, and it is much more freedom than two options (true/false) in case of boolean. Also once I use lambdas, I do not need to change my Service.method logic every time I want to update the "differentOperation" part of method.

    By the way I still think it should be possible to make it less coupled with inheritance too, but inheritance sometimes confuses (To be honest lambdas too :) ).

    One more thing I can do - create custom interface instead of lambdas, and implement it in Caller class (or create new classes implementing this interface) and pass the instance to Service.method. Though as we have Consumer interface already in Java core, it seems fine here.

    Saying that I feel like it was too much noise with lambdas last year, but this case seems like have sense to give it a try.

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    25

    Default Re: Need help with code duplication reduce

    That wasn't what I was thinking exactly.

    Put both methods in the Service.
    The Caller shouldn't have to handle any of the logic of whatever processing this is.

    I assumed the original two (or more) methods were in the Service, so that's where I expected them to stay (and why I made the "generic" method private).

    By putting it outside the Service you are probably forcing too much knowledge of the Service logic onto the Caller.

    ETA: oh yes, and with that much extra code in the lambda I would have made it a method in its own right and made it a method reference.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  7. #7
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,192
    Rep Power
    12

    Default Re: Need help with code duplication reduce

    Quote Originally Posted by Pavlo View Post

    Think about lambdas approach proposed. Now I am free to pass in method any function, and it is much more freedom than two options (true/false) in case of boolean. Also once I use lambdas, I do not need to change my Service.method logic every time I want to update the "differentOperation" part of method.
    I responded to your example and description. Calling either one method or no method is simple to debug and requires minimal overhead. You never indicated that you
    would need to call an unspecified number of methods in the future. Clearly the latter does not scale well and lambdas or method references would be the way to go. You also implied this was an optimization issue. It is really a design issue.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  8. #8
    Pavlo is offline Member
    Join Date
    Dec 2012
    Posts
    28
    Rep Power
    0

    Default Re: Need help with code duplication reduce

    Quote Originally Posted by Tolls View Post
    That wasn't what I was thinking exactly.

    Put both methods in the Service.
    The Caller shouldn't have to handle any of the logic of whatever processing this is.

    I assumed the original two (or more) methods were in the Service, so that's where I expected them to stay (and why I made the "generic" method private).

    By putting it outside the Service you are probably forcing too much knowledge of the Service logic onto the Caller.

    ETA: oh yes, and with that much extra code in the lambda I would have made it a method in its own right and made it a method reference.
    Very helpful. I will try to do it this way

  9. #9
    Pavlo is offline Member
    Join Date
    Dec 2012
    Posts
    28
    Rep Power
    0

    Default Re: Need help with code duplication reduce

    Quote Originally Posted by jim829 View Post
    I responded to your example and description.
    Thanks for your input. Probably my question not clear enough. This is because I feel my code could be better but not sure what is the best solution. If would I know solution I would not ask.

Similar Threads

  1. ROW Duplication
    By KalemKutu in forum Apache POI
    Replies: 3
    Last Post: 01-21-2017, 02:50 PM
  2. Code duplication - must be a better way?
    By Dark Knight in forum New To Java
    Replies: 11
    Last Post: 03-26-2014, 12:05 AM
  3. JComboBox false duplication
    By rookiecoder in forum AWT / Swing
    Replies: 8
    Last Post: 09-26-2012, 11:08 AM
  4. Compare two Arrays, checking for duplication
    By Redefine12 in forum New To Java
    Replies: 4
    Last Post: 02-03-2012, 09:57 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •