Refactoring the Code (If else )

前端 未结 1 622
情深已故
情深已故 2021-01-26 15:45

I was trying to refactor the code and I came across this piece of code. Can you suggest any refactoring in it and please name what refracting you used.

private v         


        
1条回答
  •  一生所求
    2021-01-26 16:03

    You are actually violating SRP (Single Responsibility Principle) therefore you need to touch this code base whenever a new language is being added.

    In order to avoid huge list of if else statements, you need a loosely coupled design in which addLetters() behaviour should be implemented in a separate LanguageImpl class (like English, etc..) as shown in the below code, which uses state pattern:

    Step (1): Define Language interface

        public interface Language {
          addLetters();
        }
    

    Step (2): Define Language Implementations

        public English implements Language {
          //implement addLetters() for English
        }
    
        //Implement other Language Classes as well in separate classes
    

    Step (3): Modify setUpBag method which takes Language object

        public void setUpBag(Language language){
            language.addLetters();
        }
    

    Each Language class follows SRP here which is key in designing OOP applications i.e., Each Language class handles only a specific behaviour.

    You can look here for more details.

    0 讨论(0)
提交回复
热议问题