중복된 코드 개선하기

조회수 264회

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인치");
    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("채널은 " + tv.getChannel() + "입니다.");

    tv.channelDown();
    System.out.println("현재 채널은 " + tv.getChannel() + "입니다.");

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

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

현재 TelevisionExam 클래스에서 power 필드를 체크해 tv power의 on/off를 출력하는 if문이 2개가 있습니다. if문을 하나의 메서드로 작성하여 중복된 코드를 없애고 싶은데 어떻게 해야될까요??

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    메서드로 빼면 됩니다.

    Televesion 클래스의 setPower()를 수정할 수 있다면, 거기서 분기문을 실행하도록 하는 게 좋습니다.

    예시:

    public class Television {
      public void setPower() {
    
        // 여기엔 원래 setPower()가 수행하는 코드들이 잔뜩 있겠죠?
    
        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인치");
        System.out.println(tv.infoTv());
    
        tv.setPower();
    
        tv.setChannel(24);
        System.out.println("채널은 " + tv.getChannel() + "입니다.");
    
        tv.channelDown();
        System.out.println("현재 채널은 " + tv.getChannel() + "입니다.");
    
        tv.setPower();
    
        System.out.println("=================="); 
      }
    
    • 아 딱 알겠네요! 감사합니다! 김호준 2022.9.30 21:43

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)