Skip to content

[2주차 과제 제출: 백성현] 레이싱카 리팩토링 - 객체지향화#65

Open
ces0135-hub wants to merge 4 commits intomainfrom
ces0135-hub/week2
Open

[2주차 과제 제출: 백성현] 레이싱카 리팩토링 - 객체지향화#65
ces0135-hub wants to merge 4 commits intomainfrom
ces0135-hub/week2

Conversation

@ces0135-hub
Copy link

@ces0135-hub ces0135-hub commented Apr 5, 2025

기존 코드의 문제점

(1) main 함수에 너무 많은 기능들이 직접 작성되어 있음
(2) Java의 네이밍 규칙이 지켜지지 않음

해결

Problem (1)

  • 각 메서드들을 각각의 파일로 분리
  • Service, ServiceImpl 코드를 통해서 main 함수에 많은 기능이 의존하는 문제 해결

Problem (2)

  • 파스칼카멜 규칙대로 변수명 정정

[기존 코드]

public class Application {
    public static void main(String[] args) {
        // TODO: 프로그램 구현

        RaceService raceService = new RaceServiceImpl();
        RaceCarService raceCarService = new RaceCarServiceImpl();


        Scanner car_scanner = new Scanner(System.in);
        System.out.println("경주할 자동차 이름을 입력하세요.(이름은 쉼표(,) 기준으로 구분)");
        String car_input = car_scanner.nextLine();  // 입력받은 자동차 이름
        String[] cars = car_input.split(",");

        System.out.print("시도할 회수는 몇회인가요? ");
        Scanner N_canner = new Scanner(System.in);
        int N = N_canner.nextInt(); // 진행 횟수 입력


        Map<String, RaceCar> carMap = new HashMap<>();

        // Map에 저장
        for (String car : cars) {
            carMap.put(car, new RaceCar(car));
        }

        System.out.println("실행결과\n");
        for (int i = 0; i < N; i++) {

            for (String car : cars) {

                RaceState currState = raceService.getState();  // GO or STAY
//                System.out.println("현재 State: " + currState);

            //  RaceCar input_car = raceCarService.saveCarInfo(car, currState);  // 이름, GO or STAY 입력
            // => for문마다 객체가 새로 생성돼서 count가 누적되지 않음

                RaceCar input_car = carMap.get(car);

                raceCarService.savaCurrentState(input_car, currState);

                if (input_car.getState().equals(RaceState.GO)) {
                    input_car.setCount(input_car.getCount() + 1);
                    input_car.getBar().append("-");  // GO이면 바로 "-" 추가 => 아래 문제 해결
                }

//                System.out.println(input_car.getCar_name() + " count : " + input_car.getCount());

                //  "-"가 중복적으로 추가되었던 이유
//              for (int j = 0; j < input_car.getCount(); j++) {
//                  input_car.getBar().append("-");
//              }


//                System.out.println(input_car.getCar_name() + "의 현재 Bar: " + input_car.getBar());
                System.out.println(input_car.getCar_name() + ": " + input_car.getBar());
            }

            System.out.println("\n------------------------------------------\n");
        }

        Map<RaceCar, Integer> winnerCar = new HashMap<>();

        int[] count_val = new int[cars.length];
        int carIdx = 0;

        // count 값을 count_val에 넣기
        for (RaceCar car : carMap.values()) {
            count_val[carIdx] = car.getCount();
            carIdx++;
        }

        // count_val에서 최대 count 찾기
        int max = Arrays.stream(count_val).max().getAsInt();

        for (RaceCar car : carMap.values()) {
            if (car.getCount() == max) {
                winnerCar.put(car, carIdx);
            }
        }

        // 우승자 출력
//        System.out.print("우승자: ");
//        for (RaceCar car : winnerCar.keySet()) {
//            System.out.print(car.getCar_name() + " ");
//        }

        // 깔끔하게 출력하기!!
        System.out.print("우승자: ");
        List<String> car_names = new ArrayList<>();
        for (RaceCar car : winnerCar.keySet()) {
            car_names.add(car.getCar_name());
        }

        System.out.println(String.join(", ", car_names));

        // stream 이용하기!!
//        System.out.print("우승자: ");
//        System.out.println(
//                winnerCar.keySet().stream()
//                        .map(RaceCar::getCar_name)
//                        .collect(Collectors.joining(", "))
//        );
    }
}

[개선된 코드]

public class Application {
    public static void main(String[] args) {
        // TODO: 프로그램 구현

        RaceCarService raceCarService = new RaceCarServiceImpl();
        getRaceCarInputService getRaceCarInputService = new getRaceCarInputServiceImpl();
        printResultService printResultService = new printResultServiceImpl();


        // 레이싱카 이름 입력받기
        String[] cars = getRaceCarInputService.getCarInput();

        // 진행 횟수 입력
        int tryCount = getRaceCarInputService.getTryCount();


        Map<String, RaceCar> carMap = new HashMap<>();

        // Map에 저장
        for (String car : cars) {
            carMap.put(car, new RaceCar(car));
        }


        // Race 현황 출력
        printResultService.printRaceProgress(carMap, cars, tryCount);


        Map<RaceCar, Integer> winnerCar = new HashMap<>();

        raceCarService.getMaxValue(winnerCar, carMap, cars);

        printResultService.printResult(winnerCar);
    }
}

Copy link
Collaborator

@pstar987 pstar987 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

기존의 책임 집중을 잘 분산해서 적용해주셨습니다! 추후에 스프링부트 과제 이전에 파스칼, 카멜 표기법에 조금더 익숙해 지실 수 있도록 수정해주시고 다시 한번 표기법 내용 확인해주세요~

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

클래스명은 파스칼 표기법에 따라 대문자로 선언해야 합니다

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

인터페이스도 마찬가지입니다

Copy link

@macqueen0987 macqueen0987 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

잘봤습니다! 여전히 enum 과 해쉬맵 사용하시는 부분이 인상적입니다.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

요구사항 중에 입력이 올바르지 않으면 예외를 발생시켜야 하는데 그부분만 추가되면 좋을것 같습니다.

Copy link

@glucosei glucosei left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

굉장히 깔끔한 객체지향적 프로그램인 것 같아요! 수고하셨어요!

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저장하기 전에 입력값 검사하는 부분이 있으면 좋을 것 같습니다!

Copy link
Member

@hyungin0505 hyungin0505 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

사소하지만 디렉토리 이름 control이 contorll로 오타가 난 것 같아요

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

camelCase에서는 언더바 안 들어가는 걸로 알고 있습니다

Copy link

@dp44rk dp44rk left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

racestate 상태를 enum class 나타내는 부분이 역시 흥미로웠어요.
좋은 객체지향 코드 보면서 많이 배우고 갑니다!

Comment on lines 30 to 46
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

생성자가 파라미터별로 많이 생긴다면 Builder 패턴 사용도 고려해보면 좋을것 같아요.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[2주차 과제 제출: 백성현] 레이싱카 리팩토링 - 객체지향화

6 participants