Skip to content

[사다리 미션] 신혜빈 미션 제출합니다. #20

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 25 commits into
base: shin378378
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
3d3d769
docs : README파일 작성
c0mpuTurtle Oct 29, 2024
b85fa13
feat : 후보자 행 객체 생성
c0mpuTurtle Oct 29, 2024
e2342f2
feat : 행 객체 생성
c0mpuTurtle Oct 29, 2024
5c01a53
refactor : 사다리 객체 다시 구성
c0mpuTurtle Oct 29, 2024
ceb91b9
feat : Controller 생성
c0mpuTurtle Oct 29, 2024
b753e93
feat : inputView 생성
c0mpuTurtle Oct 29, 2024
651f22b
2단계 사다리 생성까지 완성
c0mpuTurtle Oct 29, 2024
9f1d637
feat : 참가자, 실행결과 객체 생성 기능 추가
c0mpuTurtle Oct 29, 2024
42c7d00
feat : 사다리 결과 출력 기능 추가
c0mpuTurtle Oct 30, 2024
14b4d35
4단계까지 완성
c0mpuTurtle Oct 30, 2024
210d7f3
test : 이름 글자수 오류 발생하는지 확인
c0mpuTurtle Oct 30, 2024
9739d30
docs : README 작성
c0mpuTurtle Oct 30, 2024
6422685
refactor : all을 입력받으면 멈추는 기능 do-while문으로 구현하기
c0mpuTurtle Nov 8, 2024
cd7c8a9
refactor : 특정 참가자의 결과 찾는 기능을 OutputView가 아닌 Participants로 옮기기
c0mpuTurtle Nov 8, 2024
f2642b3
refactor : 플레이어들과 결과들 생성하고 나서 리턴값 바꾸기
c0mpuTurtle Nov 8, 2024
62ded33
refactor : ladderRows를 Ladder객체로 입력받기
c0mpuTurtle Nov 8, 2024
b24b654
feat : enum 사용하기
c0mpuTurtle Nov 8, 2024
8b4800c
refactor : 불필요한 파라미터 없애기
c0mpuTurtle Nov 8, 2024
af2eec1
fix : README 수정하기
c0mpuTurtle Nov 13, 2024
e3d3190
feat : 00rl
c0mpuTurtle Nov 14, 2024
fa8e9e0
refactor : static 변수와 일반 변수는 한 줄 띄우기
c0mpuTurtle Nov 15, 2024
b21fef9
refactor : Players의 생성 방법 바꾸기
c0mpuTurtle Nov 15, 2024
d0a5f26
feat : PlayerResultDto 생성하기
c0mpuTurtle Nov 16, 2024
8a15278
refactor : Math.random()을 ThreadLocalRandom으로 수정하기
c0mpuTurtle Nov 16, 2024
37a8e9d
refactor : randomConnectedOrDisconnected로 메소드명 수정하기
c0mpuTurtle Nov 16, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# java-ladder

Choose a reason for hiding this comment

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

헉 리드미를 작성해주셔서 한 눈에 보기가 편하네요!


# < controller >
## 1) Controller
* createParticipants() //참여자 생성기능
* createResults() //참여결과 생성기능
* createLadder() //사다리 생성기능
* createLadderResult() //사다리 결과 생성기능
* playLadderGame() //사다리 게임 실행기능

---
# < model >
## 1) DecideResult
* moveColumn() // 열부분 움직이는 기능
* moveRow() //행부분 움직이는 기능
* decideParticipantResult() //참여자 결과 결정기능
## 2) Ladder
## 3) LadderRow
* LadderRow() //사다리 열부분 생성기능
* chooseTrueOrFalse() //사다리 point 정하는 기능
## 4) Participant
* Participant() //참여자 생성, 참가자이름이 5글자 초과 시 에러발생 기능
## 5) Participants
## 6) Results
## 7) Splitter
* split() //문자열 자르는 기능

---
# < view >
## 1) InputView
* inputParticipants() //참여할 사람이름 입력기능
* inputResults() //결과 입력기능
* inputLadderHeight() //최대 사다리 높이 입력기능
* inputParticipantToWantResult() //결과를 보고싶은 사람 입력기능
## 2) OutputView
* outputParticipant() //참여자 출력기능
* outputLadderRow() //사다리행 출력기능
* outputLadder() //사다리 출력기능
* outputResults() //결과 출력기능
* outputAllParticipantsResult //모든 참여자 결과 출력기능
* outputCertainParticipantResult //특정 참여자 결과 출력기능
* outputParticipantResult //참여자 결과 출력기능
8 changes: 8 additions & 0 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import controller.Controller;

public class Main {

Choose a reason for hiding this comment

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

저는 개인적으로는 Main 과 같은 클래스 네이밍을 별로 좋아하지 않는데요
비슷한 계열로 Controller 클래스도 별로 좋아하지 않아요
그 이유는 import 를 했을 때 이름이 겹칠 클래스가 엄청 많아서인데요
그래서 약간 길더라도 LadderController 같은 네이밍을 쓰는 것을 좋아하는데요 이 부분은 어떠신지 궁금합니다!

Copy link
Author

Choose a reason for hiding this comment

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

Controller는 여러개 일 수 있으니까 네이밍이 겹칠 수 있다는 건 생각 못 해본 관점인 거 같아요!
현재 LadderController로 네이밍 변경했습니다.

<질문>

Contoller가 여러개 일 수 있다는 건 이해가 갑니다.
하지만 public static void main이 들어가는 Main은 1개만 존재하는 데도 이름이 겹칠 수 있다는 게 잘 이해가 가지 않습니다.
Main이 겹치는 경우는 어떤 경우인가요?

Choose a reason for hiding this comment

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

이제 프로젝트가 커졌을 때 프로젝트를 실행시키는 main 함수를 찾기가 힘든데요
전체 검색으로 main(으로 검색해도 엄청 많이 나와요
이때 검색할 수 있는 키워드 역할을 파일명이 하는데요
LadderApplication 같은 네이밍의 파일이 있다면 그걸로 검색하고 갈 수 있어서 편한 것 같아요
프로젝트의 규모가 커졌을 때부터 큰 의미를 갖는 네이밍인 것 같아요

Copy link
Author

@c0mpuTurtle c0mpuTurtle Nov 13, 2024

Choose a reason for hiding this comment

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

Main은 무조건 하나밖에 없으니까 왜 Main이 여러개가 나온다는 건 지 몰랐는 데 하나의 어플리케이션 안에 LadderLotto 등 다양한 로직이 들어가면 main이 겹칠 수가 있군요!!

MainLadderApplication으로 변경해 주었습니다!!

public static void main(String[] args) {
Controller controller = new Controller();
controller.playLadderGame();
}
}
69 changes: 69 additions & 0 deletions src/main/java/controller/Controller.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package controller;

import model.*;

import view.InputView;
import view.OutputView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class Controller {
InputView inputView = new InputView();
Splitter splitter = new Splitter();
OutputView outputView = new OutputView();

Choose a reason for hiding this comment

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

Input VIew 쪽에 달아드린 이 클래스가 static 으로 사용하지 않는 이유를 알고 싶어요!

Copy link
Author

Choose a reason for hiding this comment

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

앗 딱히 이유는 없고 빼먹는 거 같습니다!! 짚어주셔서 감사합니다 :)


private List<Participant> createParticipants() {
String participantNamesBeforeSplit = inputView.inputParticipants();
String[] participantNames = splitter.split(participantNamesBeforeSplit);
List<Participant> participantsInventory = new ArrayList<>();
for (int i = 0; i < participantNames.length; i++) {
Participant participant = new Participant(i, participantNames[i]);
participantsInventory.add(participant);
}
Participants participants = new Participants(participantsInventory);
return participants.getParticipantInventory();
}

private List<String> createResults() {
String trialResultsBeforeSplit = inputView.inputResults();
String[] trialResults = splitter.split(trialResultsBeforeSplit);
Results results = new Results(Arrays.asList(trialResults));
return results.getTrialResults();
}

private Ladder createLadder(int columnSize) {
int rowSize = inputView.inputLadderHeight();
Ladder ladder = new Ladder();
List<LadderRow> ladderRows = new ArrayList<>();
for (int i = 0; i < rowSize; i++) {
LadderRow ladderRow = new LadderRow(columnSize);
ladderRows.add(ladderRow);
}
ladder.settingColumns(ladderRows);
return ladder;
}

private List<LadderRow> createLadderResult(List<Participant> participantInventory, List<String> trialResults){
Ladder ladder = createLadder(participantInventory.size()-1);
List<LadderRow> ladderRows = ladder.getRows();
OutputView outputView = new OutputView();
outputView.outputLadder(participantInventory, ladderRows, trialResults);
return ladder.getRows();
}

public void playLadderGame(){
List<Participant> participantInventory = createParticipants();
List<String> trialResults = createResults();
List<LadderRow> ladderRows = createLadderResult(participantInventory, trialResults);
DecideResult decideResult = new DecideResult();
decideResult.decideParticipantResult(participantInventory, ladderRows, trialResults);
while(true) {
String participantName = inputView.inputParticipantToWantResult();
outputView.outputParticipantResult(participantInventory, participantName);
if(participantName.equals("all"))break;
}

Choose a reason for hiding this comment

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

all이 나올 때까지 결과를 보여준다

이렇게 해석할 수도 있네요! 저는 그냥 한 번만 결과를 출력하는 줄 알아서 한 번만 했거든요,,ㅎㅎ

들여쓰기를 1까지 허용한다는 조건을 만족시키기 위해서 do-while문을 사용해볼 수도 있을 것 같아요!

Copy link
Author

Choose a reason for hiding this comment

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

if(participantName.equals("all"))break;

저도 모르게 단순히 이 코드를 들여쓰기가 없는 코드라고 인식하고 있었네요 ㅜㅠ 짚어주셔서 감사합니다!!
현재 아래와 같이 do while문을 수정하였습니다!!

String participantName;
        do{
            participantName = inputView.inputParticipantToWantResult();
            outputView.outputParticipantResult(participantInventory, participantName);
        }while(!participantName.equals("all"));

}
}
32 changes: 32 additions & 0 deletions src/main/java/model/DecideResult.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package model;

import java.util.List;

public class DecideResult {
private int moveColumn(List<Boolean> points, int columnPosition){
if(columnPosition!=0 && points.get(columnPosition-1)==true){

Choose a reason for hiding this comment

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

오! 이 부분에 대한 책임 부여가 저랑 조금 다른 부분인 것 같아요. 저는 조건문의 내용이 List points를 인스턴스 변수로 가진 (혜빈님 클래스 이름 기준) LadderRow가 처리하도록 책임을 부여하였는데 혜빈님 생각은 어떠신가요??

Copy link
Author

Choose a reason for hiding this comment

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

생각해보니까 이 상희님 말씀처럼 DecideResult를 따로 둘 필요가 없을 거 같네요!
저는 리팩토링을 통해 Ladder를 생성하고 Ladder에서 사용자의 결과값도 구할 수 있게
결과를 저장하는 메소드를 Ladder객체에 넣어주었습니다!

return --columnPosition;
}
if(columnPosition!=points.size() && points.get(columnPosition)==true) {
return ++columnPosition;
}
return columnPosition;
}

private int moveRow(List<LadderRow> ladderRows, int columnPosition){
for (LadderRow ladderRow : ladderRows) {
List<Boolean> points = ladderRow.getPoints();
columnPosition = moveColumn(points, columnPosition);
}
return columnPosition;
}

public void decideParticipantResult(List<Participant> participantInventory, List<LadderRow> ladderRows, List<String> trialResults){
for (Participant participant : participantInventory) {
int participantPosition = participant.getPosition();
int columnPosition = moveRow(ladderRows, participantPosition);
String result = trialResults.get(columnPosition);
participant.settingResult(result);
}
}
}
15 changes: 15 additions & 0 deletions src/main/java/model/Ladder.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package model;

import java.util.List;

public class Ladder {
private List<LadderRow> ladderRows;

public void settingColumns(List<LadderRow> ladderRows) {
this.ladderRows = ladderRows;
}

Choose a reason for hiding this comment

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

생성자 이름을 Ladder이 아닌 settingColumns로 지으신 이유가 궁금합니다!

Copy link
Author

Choose a reason for hiding this comment

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

이건 제 착오인 거 같습니다 ㅜㅠㅜㅠ
생성자가 없다는 걸 몰랐네요 짚어주셔서 감사합니다!!
현재는 생성자로 수정해두었습니다!1


public List<LadderRow> getRows() {
return ladderRows;
}
}
27 changes: 27 additions & 0 deletions src/main/java/model/LadderRow.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package model;

import java.util.ArrayList;
import java.util.List;

public class LadderRow {
private List<Boolean> points = new ArrayList<>();

public LadderRow(int columnSize) {
for (int columnPosition = 0; columnPosition < columnSize; columnPosition++) {
boolean randomBoolean = chooseTrueOrFalse(this.points, columnPosition);
this.points.add(columnPosition, randomBoolean);
}
}

private boolean chooseTrueOrFalse(List<Boolean> points, int columnPosition) {
if (columnPosition == 0) {
return Math.random() < 0.5;
}
if (points.get(columnPosition - 1) == true) return false;
return Math.random() < 0.5;
}

public List<Boolean> getPoints() {
return points;
}
}
32 changes: 32 additions & 0 deletions src/main/java/model/Participant.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package model;

public class Participant {
private static final int NAME_LENGTH_LIMIT=5;
private int position;
private String name;
private String result;
Copy link

@SANGHEEJEONG SANGHEEJEONG Oct 31, 2024

Choose a reason for hiding this comment

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

3개 이상의 인스턴스 변수를 가진 클래스를 쓰지 않는다.

오 저도 이거 result를 넣고 싶었는데 조건 때문에 못 넣었어요 ㅠ

저는 세 개 중에 두 개만 넣어야 한다면 Participantposition이랑 name을 가지는 것이 나을 것 같아서 이 두 개로 클래스를 작성했습니다. 제 경우 position을 움직이는 메서드를 따로 Participant 클래스에 만들고 이를 이용해서 마지막 result의 인덱스만 저장을 하도록 했습니다. 결국 사용자가 입력받은 결과들은 사용자 입력을 유지한 채로 있을테니까 결과 리스트를 resultList라고 한다면 resultList.get(participant.getPosition()) 이렇게 결과를 출력하도록 했습니다.

혜빈님은 어떻게 생각하시나요??

Copy link
Author

@c0mpuTurtle c0mpuTurtle Nov 8, 2024

Choose a reason for hiding this comment

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

이번 기회에 저도 곰곰히 어떤 변수를 빼면 좋을까 고민을 했는 데요. 저도 상희님처럼 result결과를 빼기로 결정했습니다!!

차이점이 있다면 값을 Map<사용자이름, 사용자의 결과>의 형태로 저장해주었어요.
resultList.get(participant.getPosition()) 이렇게 리스트로 저장해서 특정 위치에 있는 결과값을 들고오는 것도 좋지만 조금 더 직관적일 순 없을까 고민하다 Map을 사용했는 데요.
특정 위치 대신 사용자이름을 키 값으로 사용해서 사용자의 결과를 뽑아내니까 직관적이라 좋은 거 같아요 :)

result값을 따로 빼라고 피드백해주셔서 감사합니다! 덕분에 조금 더 깔끔한 리팩토링에 많은 도움이 된 거 같아요!


public Participant(int position, String name) {
if(name.length()> NAME_LENGTH_LIMIT) {
throw new IllegalArgumentException("참가자 이름이 "+NAME_LENGTH_LIMIT+"자 초과입니다.");
}
this.position = position;
this.name = name;
}

public void settingResult(String result){
this.result = result;
}

public int getPosition() {
return position;
}

public String getName() {
return name;
}

public String getResult() {
return result;
}
}
15 changes: 15 additions & 0 deletions src/main/java/model/Participants.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package model;

import java.util.List;

public class Participants {
private List<Participant> participantInventory;

public Participants(List<Participant> participantInventory) {
this.participantInventory = participantInventory;
}

public List<Participant> getParticipantInventory() {
return participantInventory;
}
}
15 changes: 15 additions & 0 deletions src/main/java/model/Results.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package model;

import java.util.List;

public class Results {
private List<String> trialResults;

public Results(List<String> trialResults) {
this.trialResults = trialResults;
}

public List<String> getTrialResults() {
return trialResults;
}
}
13 changes: 13 additions & 0 deletions src/main/java/model/Splitter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package model;

public class Splitter {
final static private String SPLIT_SIGN = ",";

public String[] split(String beforeSplit) {
String[] afterSplit = beforeSplit.split(SPLIT_SIGN);
for (int i = 0; i < afterSplit.length; i++) {
afterSplit[i] = afterSplit[i].trim();
}
return afterSplit;
}

Choose a reason for hiding this comment

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

우와 저는 공백 제거하여 분리하는 방법은 몰랐는데 알아가네요!
","을 따로 정의해주신 것도 좋은 방법 같네요 배워갑니당 ㅎㅎ

}
26 changes: 26 additions & 0 deletions src/main/java/view/InputView.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package view;

import java.util.Scanner;

public class InputView {
Scanner scanner = new Scanner(System.in);

Choose a reason for hiding this comment

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

다른 부분의 구현을 정말 잘 해주신 것 같아서
조금 디테일하게 챙길 수 있을 것 같을 부분을 말씀드리려고 하는데요
혹시 이 클래스가 Static method 로 이루어지지 않은 이유가 있을까요?
private static final Scanner scanner = new Scanner(System.in); 으로 바꾸면 현재 있는 것들을 전부 static 으로 바꿀 수 있을테니까요

Copy link
Author

@c0mpuTurtle c0mpuTurtle Nov 12, 2024

Choose a reason for hiding this comment

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

딱히 이유는 없습니다 ㅜㅠ
Controller 안에서 inputViewoutputViewstatic을 붙여야 한다는 개념은 생각해봤는 데 그 안의 Scanner에도 static을 붙여줄 수 있다는 개념은 생각 못 해본 거 같아요! 짚어주셔서 감사합니다!!

현재 스캐너와 InputView OutputView의 모든 메서드에 static 을 붙여주었습니다!

<질문>

static을 붙이는 이유가 "이 값은 객체마다의 특징을 나타내는 값이 아니다"라는 특징을 명시해주기 위해서 인가요?
아니면 또 다른 이유가 있는 건가요?
미리 값들을 한 번에 불러온다는 게 좋은 건지 잘 모르겠습니다 ㅜㅠ
미리 불러오더라도 그 값을 안 쓰게 되면 괜한 메모리 낭비가 아닌가 하는 생각이 있기 때문입니다.

Choose a reason for hiding this comment

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

보통 스태틱으로 할당되는 메모리는 신경쓸 필요가 없어요 (map 에 10만개쯤 넣는 순간부터 고민해도 충분합니다)
그래서 그 이유는 아니고요

스태틱을 쓰면 가장 간단하게는 생성자가 간단해지잖아요?
테스트에서 그 객체를 다룰 필요가 없을 때는 생성자가 간단해져서 테스트가 오히려 쉬워지기도 합니다
물론 수기 구현으로 테스트에서 모킹된 객체를 넣는다면 그때부터는 static이 아닌 쪽이 편합니다
모든 것에는 장단이 있어요!

Copy link
Author

@c0mpuTurtle c0mpuTurtle Nov 13, 2024

Choose a reason for hiding this comment

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

staic이라는 게 생각보다 메모리를 많이 잡아먹진 않군요 :) 몰랐던 지식인 데 알려주셔서 감사합니다!

생성자가 간단해진다는 생각은 못 해봤어요!! 생각해보지 못 한 관점이네요.
그런데 꼭 static이 아니여도 아래와 같이 선언해두면 생성자가 간단해지지 않나요?
static으로 변수를 미리 선언해주는 것과 아래와 같이 변수를 설정해주는 것의 차이가 모호하게 느껴져요...

private String name = "아무개";

Choose a reason for hiding this comment

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

만약 그렇게 된다면 큰 차이는 없을 것 같아요!
Java 기준에서는 Lombok 으로 생성자를 만드는 경우가 많은데, 이때 기준으로 봤을 때 @RequiredArgsConstructor 를 쓰지 못한다는 것이 약간 아쉬울 수 있는데, 이 부분만 알고서 쓰신다면 문제는 없을 것 같아요

Copy link
Author

Choose a reason for hiding this comment

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

@RequiredArgsConstructor는 처음 들어 봤는 데 생성자를 초기화 해주는 기능이군요:)
static 변수는 생성자와 관련이 없어서 @RequiredArgsConstructor로 처리할 수 없다는 점은 이번 기회로 잘 인지하고 있겠습니다!! 감사합니다!!

public String inputParticipants(){
System.out.println("참여할 사람 이름을 입력하세요. (이름은 쉼표(,)로 구분하세요)");
return scanner.nextLine();
}

public String inputResults(){
System.out.println("\n"+"실행 결과를 입력하세요. (결과는 쉼표(,)로 구분하세요)");
return scanner.nextLine();
}

public Integer inputLadderHeight(){
System.out.println("\n"+"최대 사다리 높이는 몇 개인가요?");
return Integer.parseInt(scanner.nextLine());
}

public String inputParticipantToWantResult(){
System.out.println("\n"+"결과를 보고 싶은 사람은?");
return scanner.nextLine();
}
}
72 changes: 72 additions & 0 deletions src/main/java/view/OutputView.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package view;

import model.Participant;
import model.LadderRow;

import java.util.List;

public class OutputView {
private static final int COLUMN_LENGTH = 5;

private void outputParticipant(List<Participant> participantInventory) {
for (Participant participant : participantInventory) {
String participantName = participant.getName();
System.out.printf("%" + COLUMN_LENGTH + "s", participantName);
System.out.printf(" ");
}
}

private void outputLadderRow(List<Boolean> points) {
System.out.println();
System.out.print(" |");
for (int i = 0; i < points.size(); i++) {
if (points.get(i) == true) System.out.print("-----|");
else if (points.get(i) == false) System.out.print(" |");
}

Choose a reason for hiding this comment

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

for문 안에 있는 내용을 따로 메서드로 분리하면 else를 안 써도 될 것 같은데 어떠신가용

Copy link
Author

Choose a reason for hiding this comment

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

private void outputLadderColumn(Boolean bool) {
        if (bool == true) System.out.print("-----|");
        if (bool == false) System.out.print("     |");
    }

지금은 현재 for문 안의 내용을 이렇게 따로 메소드를 만들어 빼주었습니다!!
들여쓰기를 줄이는 데에 좋은 방법인 거 같아요 감사합니다 :)

<질문>

제가 이해를 잘 못 한 거 같은 데 else를 안 써도 될 거 같다는 말이 else if를 if로 바꾸는 게 좋을 거 같다는 말인가요?
아니면 다른 의미가 또 있는 건가요??

Copy link

@SANGHEEJEONG SANGHEEJEONG Nov 9, 2024

Choose a reason for hiding this comment

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

else 예약어를 쓰지 않는다.

엇 다른 의미는 없고 이 규칙을 지키는 방향으로 수정했으면 좋겠다는 뜻이었습니다!

}

public void outputLadder(List<Participant> participantInventory, List<LadderRow> ladderRows, List<String> trialResults) {
System.out.println("\n"+"사다리 결과"+"\n");
outputParticipant(participantInventory);
for (int i = 0; i < ladderRows.size(); i++) {
List<Boolean> points = ladderRows.get(i).getPoints();
outputLadderRow(points);
}
outputResults(trialResults);
System.out.println();
}

private void outputResults(List<String> trialResults) {
System.out.println();
for (String trialResult : trialResults) {
System.out.printf("%" + COLUMN_LENGTH + "s", trialResult);

Choose a reason for hiding this comment

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

와... 이렇게 쓸 수 있다는 것을 저도 처음봤어요 신기하네요!

java 쪽에서는 printf 를 활용한 코드를 일반적으로는 많이 사용하지 않는 것 같은데요
제가 본 방법들은 보통 StringBuilder 를 통해서

StringBuilder result=new StrintBuilder();
for(int i=0;i<COLUMN_LENGTH;i++){
    result.append("-")
}

약간 이런 느낌으로 해도 좋을 것 같은데 어떠신가요?
일반적으로 많이 쓰는 형태가 아니라서 신선했으면서도 살짝 어색하게 느껴져서 달아봅니다!

Copy link
Author

Choose a reason for hiding this comment

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

<질문>

혹시.. 이런식으로 활용하라는 말씀이 맞을까용?
더 효율적인 방법이 있는 건지, 말씀하신 방법이 이런 느낌이 맞는 건지 확인 부탁드립니다!!

for (String trialResult : trialResults) {
            StringBuilder result=new StringBuilder();
            for(int i=0;i<COLUMN_LENGTH-trialResult.length();i++){
                result.append(" ");
            }
            result.append(trialResult+" ");
            System.out.print(result);
        }

Choose a reason for hiding this comment

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

오 좋아요 딱 이런 느낌이었어요
이런 코드는 약간 더 직관적으로 읽혀왔던 것 같아서요

System.out.printf(" ");
}
}

Choose a reason for hiding this comment

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

헉 제가 출력할 때 폭을 어떻게 지정해야 하는지 몰라서 그냥 지정하지 않은 채로 냅뒀었는데 이런 방법이 있었네요!


private void outputAllParticipantsResult(List<Participant> participantInventory) {
for (Participant participant : participantInventory) {
String participantName = participant.getName();
String participantResult = participant.getResult();
System.out.println(participantName + " : " + participantResult);
}
}

private void outputCertainParticipantResult(List<Participant> participantInventory, String participantName) {
for (Participant participant : participantInventory) {
if (participantName.equals(participant.getName())) {
String participantResult = participant.getResult();
System.out.println(participantName + " : " + participantResult);
}

Choose a reason for hiding this comment

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

indent(인덴트, 들여쓰기) depth를 2를 넘지 않도록 구현한다. 1까지만 허용한다.

이 조건을 충족시키기 위해서 스트림을 사용해보는 건 어떨까요?
저도 처음에 while문 안에 if로 이름 찾는 방법만 생각이 나서 고민했었는데 학습테스트를 통해 filter 사용법을 알게 돼서 고쳤어요!!

그리고 이름을 찾는 행위가 Participants의 책임이라고 생각해서 저는 해당 메서드를 플레이어 모아놓은 클래스에 작성했는데 혜빈님은 어떻게 생각하시나요?

Copy link
Author

@c0mpuTurtle c0mpuTurtle Nov 8, 2024

Choose a reason for hiding this comment

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

제가 지금 우아한테크코스 프리코스를 진행 중인데요. 공동 피드백을 보면 "객체는 객체답게 사용한다."라는 부분이 있거든요?

객체는 객체답게 사용한다는 말이 getter setter만 있고 로직은 없는 객체가 있다면,
데이터를 꺼내(get) 사용하기보다는, 데이터가 가지고 있는 객체가 스스로 처리할 수 있도록 구조를 변경할 수는 없는 지를 한 번 생각해보라는 내용의 피드백이였는 데요.

상희님의 조언을 듣고 이 말이 갑자기 떠올랐어요. 사실 객체는 객체답게 쓰라는 말이 잘 이해가 안 갔는 데 이렇게 예시를 보고 나니까 get해서 쓰지말고 객체가 스스로 처리 하도록 해야한다는 게 무슨 말인지 알겠네요 :)
좋은 조언 진짜 너무 감사합니다!!

Copy link
Author

@c0mpuTurtle c0mpuTurtle Nov 8, 2024

Choose a reason for hiding this comment

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

그리고 stream의 filter기능을 사용하면 들여쓰기를 줄일 수 있다는 점은 또 몰랐네요!!
상희님의 조언대로 1) filter기능을 사용해 들여쓰기를 줄이고 2) 이름을 찾는 행위를 부여하는 아래와 같은 코드를 Participants에 넣어주었습니다!

public String getCertainParticipantResult(String participantName){
        return participantInventory.stream()
                .filter(participant -> participantName.equals(participant.getName()))
                .map(Participant::getResult)
                .findFirst()
                .orElse(null);
    }

Copy link
Author

Choose a reason for hiding this comment

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

----- 제가 결과값을 Map으로 저장하면서 지금은 사용자이름을 키값으로 사용자의 결과를 불러오는 코드로 변경되었습니다.

}
}

public void outputParticipantResult(List<Participant> participantInventory, String participantName) {
System.out.println("\n" + "실행결과");
if (participantName.equals("all")) {
outputAllParticipantsResult(participantInventory);
return;
}
outputCertainParticipantResult(participantInventory, participantName);
}
}
Loading