0

In one recent exam, I was asked 2 questions regarding the code snippet below... The questions are as follows

  1. Identify the design principle violated by the code snippet

  2. Describe the design pattern that solves the design principle violated.

  3. Provide the UML class diagram of the design pattern described in (2) above (Optional)

  public class AI{
     public static void main(String args[]){
        Scanner input = new Scanner(System.in);
        String choice = input.nextLine();
        
        if(choice.equals("some text"){
           // do something
        }
        else if(choice.equals("another text"){
           // do something
        }
        else if(choice.equals("extra text"){
           // do something
        }
        ...
        else{
           // do default
        }

     }
  }
Ebenezer Mathebula
  • 271
  • 1
  • 5
  • 19
  • 1
    SOLID refers to object-oriented programs, and this contains no objects except the scanner. It is procedural. So the correct answer is "N/A". Possibly they are alluding to SRP, because of the 4 conditional branches. Don't know. – Michael Aug 26 '20 at 15:55
  • 1
    You are right saying SOLID refers to object-oriented programs. But i think in this particular question, the design principle being violated is the Open/Closed Principle, since we would have to Modify the code inorder to add another condition. If i am right, I still dont know which pattern can fix this – Ebenezer Mathebula Aug 26 '20 at 16:05
  • 1
    In OOP, branching logic is often refactored to polymorphism. I don't know whether this exam considers polymorphism to be a design pattern. – jaco0646 Aug 26 '20 at 20:34
  • 2
    It violates the open-close principle, because you must change the main method when another line handling should be added.. You must add another else if branch. – René Link Aug 27 '20 at 04:26
  • Just as I thought, it violates the open/closed principle. Is there a design pattern amongst the 23 GOF design patterns that can fix this? – Ebenezer Mathebula Aug 27 '20 at 09:37
  • 1
    All of the GoF design patterns make use of polymorphism to some degree. From that perspective you could make a case for almost any of them. I expect the answer here is specific to the material taught in this course. – jaco0646 Aug 27 '20 at 14:28

1 Answers1

0
Your code violates -  the Single Responsibility Principle (SRR)- design principle.
SRP make sure every class, module, or function in a program should have one responsibility/purpose in a program.
The strategy pattern (also known as the policy pattern) is a behavioral software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use.

enter image description here

The above is UML diagram for strategy diagram.

D.S.
  • 137
  • 5