PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 4, 2022

[FIXED] What is the right lambda for this inner class.SonarLint suggest me to "Make this anonymous inner class a lambda"

 November 04, 2022     anonymous-inner-class, java, lambda, sonarlint     No comments   

Issue

return new KeyGenerator() {
    @Override
    public Object generate(Object object, Method method, Object... objects) {
    String username = null;
    try {
        username = objectStorageService.getAuthDetail().getUsername();
        StringBuilder customisedkey = generateKey(object, method, objects);
        customisedkey.append(username);
        return customisedkey.toString();
    } catch (BaseException e) {
       LOGGER.error("Operation failed while generating Key", e);
       return null;
    }
}
};

SonarLint suggest me to "Make this anonymous inner class a lambda". but wasn't able to find a solution for this specific case


Solution

An anonymous inner class having just a single method can be converted in a lambda expression.

In particular this code:

return new KeyGenerator() {
    @Override
    public Object generate(Object object, Method method, Object... objects) {
    String username = null;
    try {
        username = objectStorageService.getAuthDetail().getUsername();
        StringBuilder customisedkey = generateKey(object, method, objects);
        customisedkey.append(username);
        return customisedkey.toString();
    } catch (BaseException e) {
       LOGGER.error("Operation failed while generating Key", e);
       return null;
    }
}
};

is equivalent to:

return (object, method, objects) -> {
    String username = null;
    try {
        username = objectStorageService.getAuthDetail().getUsername();
        StringBuilder customisedkey = generateKey(object, method, objects);
        customisedkey.append(username);
        return customisedkey.toString();
    } catch (BaseException e) {
       LOGGER.error("Operation failed while generating Key", e);
       return null;
    }
};

More in general a code similar to this one:

new MyClass() {
   public ReturnType myUniqueMethod(ParameterType p) {
       // body
   }
}

can be replaced with

(p) -> {
   // body
}

This operation can be generally executed automatically by modern IDE with a refactoring operation.



Answered By - Davide Lorenzo MARINO
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing