Improve duplicate code

Asked 1 years ago, Updated 1 years ago, 321 views

package sec01.exam01;

public class TelevisionExam {

public static void main(String[] args) {
    Television tv;
    tv = new Television();

    tv.setModel("SAMSUNG Neo OLED");
    tv.setSize("100-inch");
    System.out.println(tv.infoTv());

    tv.setPower();
    if(tv.getPower()) {
        System.out.println("TV power: ON");
    }
    else {
        System.out.println("TV poser: OFF");
    }

    tv.setChannel(24);
    System.out.println ("channel is " + tv.getChannel() + ");

    tv.channelDown();
    System.out.println ("The current channel is " + tv.getChannel() + ");

    tv.setPower();
    if(tv.getPower()){
        System.out.println("TV pwoer: ON");
    } } else {
        System.out.println("TV power: OFF");
    }

    System.out.println("=================="); }

Currently, there are two if statements that check the power field in the TelevisionExam class to output on/off of TV power. I want to write an if statement in one method to get rid of duplicate code, what should I do?

java

2022-10-01 01:00

1 Answers

Subtract by method.

If you can modify the setPower() of the Television class, it is recommended that you run a branch statement there.

Example:

public class Television {
  public void setPower() {

    // There's probably a lot of code here that the setPower() originally does, right?

    if (this.getPower()) {
      System.out.println("TV power: ON");
    } } else {
      System.out.println("TV poser: OFF");
    }
  }
}
  public static void main(String[] args) {
    Television tv;
    tv = new Television();

    tv.setModel("SAMSUNG Neo OLED");
    tv.setSize("100-inch");
    System.out.println(tv.infoTv());

    tv.setPower();

    tv.setChannel(24);
    System.out.println ("channel is " + tv.getChannel() + ");

    tv.channelDown();
    System.out.println ("The current channel is " + tv.getChannel() + ");

    tv.setPower();

    System.out.println("=================="); 
  }


2022-10-01 01:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.