What Should I do to avoid code duplication in my methods in Service Layer?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I've problem with my code. I've service class with methods like add, update etc. In each method I retrieve information like authentication, from authentication username, from username User Object etc and I use this information to add new objects to my database without giving them manually but by token after login. It looks like below



 Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UserPrinciple userPrinciple = (UserPrinciple) authentication.getPrincipal();
String username = userPrinciple.getUsername();


I am using this code in three methods in my Service class. What should I do to reduce it to one using?










share|improve this question























  • Suppose that some time in future you have to change those lines. If you extract a method, you just modify that method. If you have copy-pasted code you have to modify every single copy of that code, and if you forget one of those lines who knows what can happen.

    – Lorelorelore
    Jan 3 at 17:10











  • Take a look here: softwareengineering.stackexchange.com/questions/87696/…

    – Lorelorelore
    Jan 3 at 17:11











  • The bigger problem is that you have hidden dependencies here. It's usually best to define a security boundary (often at the MVC controller level) and pass in the UserPrincipal to lower levels as a method parameter.

    – chrylis
    Jan 3 at 17:12


















0















I've problem with my code. I've service class with methods like add, update etc. In each method I retrieve information like authentication, from authentication username, from username User Object etc and I use this information to add new objects to my database without giving them manually but by token after login. It looks like below



 Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UserPrinciple userPrinciple = (UserPrinciple) authentication.getPrincipal();
String username = userPrinciple.getUsername();


I am using this code in three methods in my Service class. What should I do to reduce it to one using?










share|improve this question























  • Suppose that some time in future you have to change those lines. If you extract a method, you just modify that method. If you have copy-pasted code you have to modify every single copy of that code, and if you forget one of those lines who knows what can happen.

    – Lorelorelore
    Jan 3 at 17:10











  • Take a look here: softwareengineering.stackexchange.com/questions/87696/…

    – Lorelorelore
    Jan 3 at 17:11











  • The bigger problem is that you have hidden dependencies here. It's usually best to define a security boundary (often at the MVC controller level) and pass in the UserPrincipal to lower levels as a method parameter.

    – chrylis
    Jan 3 at 17:12














0












0








0








I've problem with my code. I've service class with methods like add, update etc. In each method I retrieve information like authentication, from authentication username, from username User Object etc and I use this information to add new objects to my database without giving them manually but by token after login. It looks like below



 Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UserPrinciple userPrinciple = (UserPrinciple) authentication.getPrincipal();
String username = userPrinciple.getUsername();


I am using this code in three methods in my Service class. What should I do to reduce it to one using?










share|improve this question














I've problem with my code. I've service class with methods like add, update etc. In each method I retrieve information like authentication, from authentication username, from username User Object etc and I use this information to add new objects to my database without giving them manually but by token after login. It looks like below



 Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UserPrinciple userPrinciple = (UserPrinciple) authentication.getPrincipal();
String username = userPrinciple.getUsername();


I am using this code in three methods in my Service class. What should I do to reduce it to one using?







java spring spring-boot spring-mvc






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 3 at 16:59









Rav3Rav3

729




729













  • Suppose that some time in future you have to change those lines. If you extract a method, you just modify that method. If you have copy-pasted code you have to modify every single copy of that code, and if you forget one of those lines who knows what can happen.

    – Lorelorelore
    Jan 3 at 17:10











  • Take a look here: softwareengineering.stackexchange.com/questions/87696/…

    – Lorelorelore
    Jan 3 at 17:11











  • The bigger problem is that you have hidden dependencies here. It's usually best to define a security boundary (often at the MVC controller level) and pass in the UserPrincipal to lower levels as a method parameter.

    – chrylis
    Jan 3 at 17:12



















  • Suppose that some time in future you have to change those lines. If you extract a method, you just modify that method. If you have copy-pasted code you have to modify every single copy of that code, and if you forget one of those lines who knows what can happen.

    – Lorelorelore
    Jan 3 at 17:10











  • Take a look here: softwareengineering.stackexchange.com/questions/87696/…

    – Lorelorelore
    Jan 3 at 17:11











  • The bigger problem is that you have hidden dependencies here. It's usually best to define a security boundary (often at the MVC controller level) and pass in the UserPrincipal to lower levels as a method parameter.

    – chrylis
    Jan 3 at 17:12

















Suppose that some time in future you have to change those lines. If you extract a method, you just modify that method. If you have copy-pasted code you have to modify every single copy of that code, and if you forget one of those lines who knows what can happen.

– Lorelorelore
Jan 3 at 17:10





Suppose that some time in future you have to change those lines. If you extract a method, you just modify that method. If you have copy-pasted code you have to modify every single copy of that code, and if you forget one of those lines who knows what can happen.

– Lorelorelore
Jan 3 at 17:10













Take a look here: softwareengineering.stackexchange.com/questions/87696/…

– Lorelorelore
Jan 3 at 17:11





Take a look here: softwareengineering.stackexchange.com/questions/87696/…

– Lorelorelore
Jan 3 at 17:11













The bigger problem is that you have hidden dependencies here. It's usually best to define a security boundary (often at the MVC controller level) and pass in the UserPrincipal to lower levels as a method parameter.

– chrylis
Jan 3 at 17:12





The bigger problem is that you have hidden dependencies here. It's usually best to define a security boundary (often at the MVC controller level) and pass in the UserPrincipal to lower levels as a method parameter.

– chrylis
Jan 3 at 17:12












2 Answers
2






active

oldest

votes


















1














Just move



Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UserPrinciple userPrinciple = (UserPrinciple) authentication.getPrincipal();
String username = userPrinciple.getUsername();


to the separate method.



Example:



private String getUserName() {
Authentication authentication =
SecurityContextHolder.getContext().getAuthentication();
UserPrinciple userPrinciple = (UserPrinciple) authentication.getPrincipal();
return userPrinciple.getUsername();
}





share|improve this answer































    0














    Refactor out the common code/behavior to a method and invoke that method where ever necessary. In this case, just follow what @MZxFK has suggested. Redundancy is an open enemy to to writing good code






    share|improve this answer
























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54026622%2fwhat-should-i-do-to-avoid-code-duplication-in-my-methods-in-service-layer%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      Just move



      Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
      UserPrinciple userPrinciple = (UserPrinciple) authentication.getPrincipal();
      String username = userPrinciple.getUsername();


      to the separate method.



      Example:



      private String getUserName() {
      Authentication authentication =
      SecurityContextHolder.getContext().getAuthentication();
      UserPrinciple userPrinciple = (UserPrinciple) authentication.getPrincipal();
      return userPrinciple.getUsername();
      }





      share|improve this answer




























        1














        Just move



        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserPrinciple userPrinciple = (UserPrinciple) authentication.getPrincipal();
        String username = userPrinciple.getUsername();


        to the separate method.



        Example:



        private String getUserName() {
        Authentication authentication =
        SecurityContextHolder.getContext().getAuthentication();
        UserPrinciple userPrinciple = (UserPrinciple) authentication.getPrincipal();
        return userPrinciple.getUsername();
        }





        share|improve this answer


























          1












          1








          1







          Just move



          Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
          UserPrinciple userPrinciple = (UserPrinciple) authentication.getPrincipal();
          String username = userPrinciple.getUsername();


          to the separate method.



          Example:



          private String getUserName() {
          Authentication authentication =
          SecurityContextHolder.getContext().getAuthentication();
          UserPrinciple userPrinciple = (UserPrinciple) authentication.getPrincipal();
          return userPrinciple.getUsername();
          }





          share|improve this answer













          Just move



          Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
          UserPrinciple userPrinciple = (UserPrinciple) authentication.getPrincipal();
          String username = userPrinciple.getUsername();


          to the separate method.



          Example:



          private String getUserName() {
          Authentication authentication =
          SecurityContextHolder.getContext().getAuthentication();
          UserPrinciple userPrinciple = (UserPrinciple) authentication.getPrincipal();
          return userPrinciple.getUsername();
          }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jan 3 at 17:14









          MZxFKMZxFK

          1106




          1106

























              0














              Refactor out the common code/behavior to a method and invoke that method where ever necessary. In this case, just follow what @MZxFK has suggested. Redundancy is an open enemy to to writing good code






              share|improve this answer




























                0














                Refactor out the common code/behavior to a method and invoke that method where ever necessary. In this case, just follow what @MZxFK has suggested. Redundancy is an open enemy to to writing good code






                share|improve this answer


























                  0












                  0








                  0







                  Refactor out the common code/behavior to a method and invoke that method where ever necessary. In this case, just follow what @MZxFK has suggested. Redundancy is an open enemy to to writing good code






                  share|improve this answer













                  Refactor out the common code/behavior to a method and invoke that method where ever necessary. In this case, just follow what @MZxFK has suggested. Redundancy is an open enemy to to writing good code







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 3 at 17:39









                  stack123stack123

                  124




                  124






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54026622%2fwhat-should-i-do-to-avoid-code-duplication-in-my-methods-in-service-layer%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      'app-layout' is not a known element: how to share Component with different Modules

                      android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

                      WPF add header to Image with URL pettitions [duplicate]