Skip to content
This repository was archived by the owner on Aug 17, 2025. It is now read-only.

Conversation

@OmaryKoo
Copy link

@OmaryKoo OmaryKoo commented Jul 1, 2025

250701_04_구태한

📝 과제 정보

  • 교육 주제:
    제네릭(Generic), 열거형(Enum)

📋 체크리스트

  • [ x ] 코드 정리
  • Lint 체크
  • [ x ] Test 코드 작성

🔍 구현 방법

📷 실행 결과

🚨 어려웠던 점

💡 배운 점

제네릭(Generic)은 아직 정해지지 않은 타입을 나중에 지정할 수 있도록 남겨두는 문법
코드를 미리 작성해두고 싶지만, 나중에 어떤 타입이 올지는 그때 가서 정해지는 상황 이럴 때, 제네릭을 사용한다고 함.
즉, 코드를 설계하거나 구현할 때 타입이 아직 고정되지 않았지만, 일단 타입을 유연하게 열어두고 사용하고플 때.

열거형(enum)은 정해진 값 중 하나만 선택하게 하고 싶을 때 쓰는 타입
~ 금고를 여는 방식(PADLOCK, BUTTON 등)을 이름 + 사용 제한 횟수로 정리한 고정된 목록

❓ 질문 사항

📚 참고 자료

🔄 자체 평가 & 회고

전반적으로 배운 것들이 서로 잇는 듯 하면서도 모르겠음. 아직은 복습과 익숙이 필요함.

OmaryKoo and others added 27 commits June 9, 2025 10:41
self.Aid()사용시 MP 충분할 경우
self.Aid()사용시 MP 부족한 경우
chore: 테스트코드 클래스명 수정
@coderabbitai
Copy link

coderabbitai bot commented Jul 1, 2025

Summary by CodeRabbit

  • New Features

    • 다양한 자바 객체 및 상속 구조를 반영한 클래스와 인터페이스가 추가되었습니다(예: Asset, TangibleAsset, IntangibleAsset, Book, Computer, Hero, Slime, Wizard 등).
    • 마법사, 슬라임, 강력한 마법사 등 게임 캐릭터 기능 및 상호작용(치유, 공격 등)이 구현되었습니다.
    • 강력한 상자(StrongBox)와 열쇠 타입별 제한 기능이 도입되었습니다.
    • Book2 클래스에 깊은 복사, equals, hashCode, compareTo 기능이 추가되었습니다.
  • Bug Fixes

    • 없음
  • Documentation

    • 자바 기초 용어 정리 및 객체지향 개념, 클래스 다이어그램(PlantUML) 문서가 추가되었습니다.
  • Refactor

    • Person 클래스가 불변 객체로 개선되고, 나이 계산 방식이 출생 연도 기반으로 변경되었습니다.
  • Tests

    • 각 클래스별 단위 테스트가 추가되어 생성자, 필드, 메서드, 예외 처리, 게임 캐릭터 동작 등이 검증됩니다.

Summary by CodeRabbit

  • 신규 기능

    • 다양한 자바 객체 지향 프로그래밍(OOP) 개념을 설명하는 문서와 용어 정리 자료가 추가되었습니다.
    • 자산, 영웅, 마법사, 슬라임 등 여러 클래스를 포함한 게임 및 자산 관리 예제 코드가 추가되었습니다.
    • 클래스 다이어그램(PlantUML) 파일이 추가되어 구조를 시각적으로 확인할 수 있습니다.
    • 제네릭을 활용한 StrongBox 클래스와 KeyType 열거형이 추가되어 제한된 접근 제어를 구현했습니다.
    • Book2 클래스는 Comparable 인터페이스 구현, equals/hashCode 오버라이드, 깊은 복사(clone) 기능을 포함합니다.
  • 문서화

    • 자바 기초 및 OOP 관련 용어와 개념을 정리한 문서가 추가되었습니다.
  • 버그 수정

    • 없음
  • 리팩터링

    • Person 클래스가 불변 객체로 개선되고, 나이 계산 방식이 출생연도 기반으로 변경되었습니다.
  • 테스트

    • 각 클래스의 기능 및 동작을 검증하는 다양한 단위 테스트가 추가되었습니다.

Walkthrough

여러 개의 새로운 자바 클래스, 인터페이스, UML 다이어그램, 그리고 JUnit 테스트가 추가되었습니다. Java OOP 개념을 설명하는 문서가 생성되었고, Person 클래스는 불변 필드와 동적 나이 계산 방식으로 리팩터링되었습니다. Main 클래스에는 공백이 추가되었습니다. 또한 StrongBox 제네릭 클래스와 Book2 클래스가 새로 도입되었습니다.

Changes

파일/경로 요약 변경 내용 요약
TIL/topics/java_basic/README.md, TIL/topics/java_basic/용어정리.md Java 기본 개념 및 OOP 용어 설명 문서 추가
src/main/java/com/survivalcoding/Main.java main 메서드 내에 공백 2줄 추가
src/main/java/com/survivalcoding/TangibleAsset.puml, src/main/java/com/survivalcoding/game.puml 자산 및 게임 구조의 PlantUML 클래스 다이어그램 추가
src/main/java/com/survivalcoding/assignments_01_instance/exam01/Asset.java, .../TangibleAsset.java, .../IntangibleAsset.java, .../Book.java, .../Computer.java, .../Thing.java 자산, 유형/무형 자산, 인터페이스 및 상속 구조 클래스 추가
src/main/java/com/survivalcoding/assignments_01_instance/exam01/Hero.java, .../Slime.java, .../PoisonSlime.java, .../GreatWizard.java RPG 게임 캐릭터 및 몬스터 클래스, 공격/치유 로직 구현
src/main/java/com/survivalcoding/assignments_01_instance/exam01/Wizard.java, .../Wand.java 마법사, 지팡이 클래스 및 치유/마법 관련 로직 구현
src/main/java/com/survivalcoding/assignments_01_instance/exam01/Person.java age 필드를 birthYear로 변경, 불변 필드 적용, 나이 동적 계산, setter 제거
src/main/java/com/survivalcoding/assignments_01_instance/exam01/Book2.java Comparable 구현, equals/hashCode 오버라이드, 깊은 복사(clone) 기능 포함 Book2 클래스 추가
src/main/java/com/survivalcoding/assignments_01_instance/exam01/StrongBox.java 제네릭 StrongBox 클래스와 KeyType enum 추가, 제한된 접근 제어 구현
src/test/java/com/survivalcoding/assignments_01_instance/exam01/BookTest.java, .../ComputerTest.java, .../TangibleAssetTest.java, .../IntangibleAssetTest.java 자산 관련 클래스 생성자 및 필드 초기화 테스트 추가
src/test/java/com/survivalcoding/assignments_01_instance/exam01/SlimeTest.java, .../PoisonSlimeTest.java, .../GreatWizardTest.java 슬라임, 독 슬라임, 그레이트위저드 클래스의 공격/치유 로직 단위 테스트 추가
src/test/java/com/survivalcoding/assignments_01_instance/exam01/WizardTest.java 마법사, 지팡이, 히어로 클래스의 기능 및 예외 처리 단위 테스트 추가
src/test/java/com/survivalcoding/assignments_01_instance/exam01/PersonTest.java Person 클래스의 생성자, getter 테스트 추가
src/test/java/com/survivalcoding/assignments_01_instance/exam01/Book2Test.java Book2 클래스 equals 메서드 테스트 추가
src/test/java/com/survivalcoding/assignments_01_instance/exam01/StrongBoxTest.java StrongBox 클래스 접근 제한 및 해제 테스트 추가

Sequence Diagram(s)

sequenceDiagram
    participant Wizard
    participant Hero

    Wizard->>Hero: heal(Hero hero)
    alt MP >= 10
        Wizard-->>Wizard: MP -= 10
        Wizard-->>Hero: HP += 20
        Wizard-->>Console: print("Hero HP: ...")
    else MP < 10
        Wizard-->>Console: print("마나가 부족합니다.")
    end
Loading
sequenceDiagram
    participant GreatWizard
    participant Hero

    GreatWizard->>Hero: superHeal(Hero hero)
    alt MP >= 50
        GreatWizard-->>GreatWizard: MP -= 50
        GreatWizard-->>Hero: HP = maxHp
        GreatWizard-->>Console: print("Hero HP: ...")
    else MP < 50
        GreatWizard-->>Console: print("마나가 부족합니다.")
    end
Loading
sequenceDiagram
    participant PoisonSlime
    participant Hero

    PoisonSlime->>Hero: attack(Hero hero)
    PoisonSlime-->>Hero: HP -= 10
    alt poisonCount > 0
        PoisonSlime-->>Console: print("추가로, 독 포자를 살포했다!")
        PoisonSlime-->>Hero: HP -= (HP / 5)
        PoisonSlime-->>PoisonSlime: poisonCount -= 1
    end
Loading
sequenceDiagram
    participant TangibleAsset
    participant Thing

    TangibleAsset-->>Thing: getWeight()/setWeight()
Loading
sequenceDiagram
    participant StrongBox
    participant Client

    Client->>StrongBox: put(data)
    loop 여러번 get 호출
        Client->>StrongBox: get()
        alt 접근 제한 미만
            StrongBox-->>Client: null
        else 제한 초과
            StrongBox-->>Client: data
        end
    end
Loading
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 18

🧹 Nitpick comments (15)
src/main/java/com/survivalcoding/Main.java (1)

7-8: 불필요한 공백 줄 제거 권장

의미 없는 두 줄 공백은 Diff 노이즈만 증가시키므로 제거하고 코드 포매터(예: Google Java Format)를 적용하는 편이 좋습니다.

-    
-
src/main/java/com/survivalcoding/assignments_01_instance/exam01/Thing.java (1)

3-6: 무게 값의 계약(Contract)을 명시해 주세요

setWeight가 음수를 포함한 모든 double을 허용하고 있어 구현체마다 유효성 검사가 달라질 수 있습니다. JavaDoc 주석으로 “0 이상” 범위를 명시하거나 음수 입력 시 IllegalArgumentException을 던지도록 계약을 정의하면 구현 일관성이 보장됩니다.

 public interface Thing {
+    /**
+     * 무게(kg)를 반환합니다.
+     * @return 0 이상인 무게
+     */
     double getWeight();
 
+    /**
+     * 무게를 설정합니다.
+     * @param weight 0 이상이어야 합니다
+     * @throws IllegalArgumentException weight가 0 미만인 경우
+     */
     void setWeight(double weight);
 }
TIL/topics/java_basic/README.md (1)

1-1: 헤딩 끝의 마침표 제거 권장

markdownlint MD026 규칙에 따라 헤딩 뒤 마침표를 제거하면 린트 경고를 없앨 수 있습니다.

-# 저는 구태한입니다.
+# 저는 구태한입니다
src/main/java/com/survivalcoding/assignments_01_instance/exam01/Asset.java (1)

4-7: Asset를 추상 클래스로 선언 고려

실제 인스턴스화되는 객체는 TangibleAsset/IntangibleAsset 하위 클래스입니다. Assetabstract 키워드를 붙이면 잘못된 직접 생성 방지와 설계 의도가 명확해집니다.

-public class Asset {
+public abstract class Asset {
src/test/java/com/survivalcoding/assignments_01_instance/exam01/IntangibleAssetTest.java (1)

10-17: 테스트 메서드 이름 가독성 개선 제안

JUnit 5에서는 should… 패턴 등이 의도를 더 드러냅니다.

-    void intangibleAssetAllFieldCorrectly() {
+    void shouldCreateIntangibleAssetWithGivenNameAndPrice() {
TIL/topics/java_basic/용어정리.md (3)

6-6: 마크다운 헤딩 레벨 수정 필요

헤딩 레벨이 한 번에 하나씩만 증가해야 합니다. h1 다음에 바로 h3가 오면 안 됩니다.

-### 추상클래스와 인터페이스의 차이점
+## 추상클래스와 인터페이스의 차이점

70-70: 헤딩 포맷 수정 필요

헤딩 기호(#) 뒤에 공백이 필요합니다.

-##클래스 생성자 용어 정리 (25.06.16)
+## 클래스 생성자 용어 정리 (25.06.16)

96-97: 강조 마크 내부 공백 제거 필요

강조 표시(_) 내부에 불필요한 공백이 있습니다.

-final : 변경불가 키워드(const 같은 거) _ 한번 초기화되면 이후로 값이 바뀔 수 없음.
-this : 현재 객체를 참조하는 키워드 _ 현재 객체 자기 자신을 가리킴. 
+final : 변경불가 키워드(const 같은 거) _한번 초기화되면 이후로 값이 바뀔 수 없음._
+this : 현재 객체를 참조하는 키워드 _현재 객체 자기 자신을 가리킴._
src/main/java/com/survivalcoding/assignments_01_instance/exam01/TangibleAsset.java (1)

16-19: 생성자에서 weight 필드 초기화 누락

생성자에서 weight 필드가 초기화되지 않고 있습니다. 객체 생성 시 weight를 설정할 수 있도록 매개변수를 추가하거나 기본값으로 초기화하는 것을 고려해보세요.

옵션 1: 매개변수 추가

-    public TangibleAsset(String name, int price, String color) {
+    public TangibleAsset(String name, int price, String color, double weight) {
         super(name, price);
         this.color = color;
+        this.weight = weight;
     }

옵션 2: 기본값으로 초기화

     public TangibleAsset(String name, int price, String color) {
         super(name, price);
         this.color = color;
+        this.weight = 0.0; // 기본값으로 초기화
     }
src/main/java/com/survivalcoding/game.puml (1)

6-24: 클래스 간 관계 표현 추가 고려

현재 다이어그램에는 Hero와 Cleric 클래스만 정의되어 있지만, 메소드 파라미터로 사용되는 Kinoko 클래스와의 관계가 표현되지 않았습니다. 더 완전한 설계 문서가 되도록 관련 클래스들을 추가하는 것을 고려해보세요.

src/test/java/com/survivalcoding/assignments_01_instance/exam01/SlimeTest.java (1)

10-20: 테스트 케이스 확장 고려

현재 테스트는 기본적인 공격 동작만 검증합니다. 더 포괄적인 테스트를 위해 다음과 같은 케이스들을 추가로 고려해보세요:

  • Hero의 HP가 0 이하로 떨어지는 경우
  • null Hero 파라미터 처리
  • 여러 번 공격하는 경우
src/test/java/com/survivalcoding/assignments_01_instance/exam01/GreatWizardTest.java (1)

14-23: 테스트 케이스 확장 권장

현재 테스트는 MP가 50 미만일 때의 동작만 검증합니다. GreatWizard의 superHeal 기능을 완전히 검증하기 위해 다음 테스트 케이스들을 추가하는 것을 권장합니다:

  • MP가 50 이상일 때 정상적인 힐링 동작
  • Hero의 HP가 이미 maxHP인 경우
  • MP 소모량 검증
src/main/java/com/survivalcoding/assignments_01_instance/exam01/Hero.java (1)

3-6: 생성자 추가 고려

현재 클래스는 기본 생성자만 사용하고 있습니다. Hero 객체를 생성할 때 이름을 필수로 받는 생성자를 추가하는 것을 고려해보세요.

 public class Hero {
     private String name;
     private int hp=50;
     private int maxHp=100;
+
+    public Hero() {
+        // 기본 생성자
+    }
+
+    public Hero(String name) {
+        this.name = name;
+    }
+
+    public Hero(String name, int maxHp) {
+        this.name = name;
+        setMaxHp(maxHp);
+        this.hp = maxHp; // 생성 시 HP를 maxHP로 설정
+    }
src/test/java/com/survivalcoding/assignments_01_instance/exam01/PoisonSlimeTest.java (1)

10-10: 사용되지 않는 클래스 필드 제거

클래스 레벨에서 선언된 poisonCount 필드가 테스트에서 사용되지 않습니다. 이는 코드를 혼란스럽게 만들 수 있습니다.

사용되지 않는 필드를 제거하세요:

-    int poisonCount = 5;
-
src/test/java/com/survivalcoding/assignments_01_instance/exam01/WizardTest.java (1)

76-81: 불필요한 빈 줄들을 제거하세요.

파일 끝에 과도한 빈 줄들이 있습니다. 코드 정리를 위해 제거하는 것이 좋겠습니다.

-}
-
-
-
-
-
+}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ecd6fe6 and c0280d9.

📒 Files selected for processing (27)
  • TIL/topics/java_basic/README.md (1 hunks)
  • TIL/topics/java_basic/용어정리.md (1 hunks)
  • src/main/java/com/survivalcoding/Main.java (1 hunks)
  • src/main/java/com/survivalcoding/TangibleAsset.puml (1 hunks)
  • src/main/java/com/survivalcoding/assignments_01_instance/exam01/Asset.java (1 hunks)
  • src/main/java/com/survivalcoding/assignments_01_instance/exam01/Book.java (1 hunks)
  • src/main/java/com/survivalcoding/assignments_01_instance/exam01/Computer.java (1 hunks)
  • src/main/java/com/survivalcoding/assignments_01_instance/exam01/GreatWizard.java (1 hunks)
  • src/main/java/com/survivalcoding/assignments_01_instance/exam01/Hero.java (1 hunks)
  • src/main/java/com/survivalcoding/assignments_01_instance/exam01/IntangibleAsset.java (1 hunks)
  • src/main/java/com/survivalcoding/assignments_01_instance/exam01/Person.java (1 hunks)
  • src/main/java/com/survivalcoding/assignments_01_instance/exam01/PoisonSlime.java (1 hunks)
  • src/main/java/com/survivalcoding/assignments_01_instance/exam01/Slime.java (1 hunks)
  • src/main/java/com/survivalcoding/assignments_01_instance/exam01/TangibleAsset.java (1 hunks)
  • src/main/java/com/survivalcoding/assignments_01_instance/exam01/Thing.java (1 hunks)
  • src/main/java/com/survivalcoding/assignments_01_instance/exam01/Wand.java (1 hunks)
  • src/main/java/com/survivalcoding/assignments_01_instance/exam01/Wizard.java (1 hunks)
  • src/main/java/com/survivalcoding/game.puml (1 hunks)
  • src/test/java/com/survivalcoding/assignments_01_instance/exam01/BookTest.java (1 hunks)
  • src/test/java/com/survivalcoding/assignments_01_instance/exam01/ComputerTest.java (1 hunks)
  • src/test/java/com/survivalcoding/assignments_01_instance/exam01/GreatWizardTest.java (1 hunks)
  • src/test/java/com/survivalcoding/assignments_01_instance/exam01/IntangibleAssetTest.java (1 hunks)
  • src/test/java/com/survivalcoding/assignments_01_instance/exam01/PersonTest.java (1 hunks)
  • src/test/java/com/survivalcoding/assignments_01_instance/exam01/PoisonSlimeTest.java (1 hunks)
  • src/test/java/com/survivalcoding/assignments_01_instance/exam01/SlimeTest.java (1 hunks)
  • src/test/java/com/survivalcoding/assignments_01_instance/exam01/TangibleAssetTest.java (1 hunks)
  • src/test/java/com/survivalcoding/assignments_01_instance/exam01/WizardTest.java (1 hunks)
🧰 Additional context used
🧠 Learnings (7)
📓 Common learnings
Learnt from: Hae1Won1
PR: SurvivalCodingCampus/polytech_java_study#1
File: Readme.md:1-1
Timestamp: 2025-06-09T02:30:37.051Z
Learning: The repository `SurvivalCodingCampus/polytech_java_study` is used for class practice exercises, so minimal documentation in files like README.md may be intentional and acceptable for educational purposes.
TIL/topics/java_basic/README.md (1)
Learnt from: Hae1Won1
PR: SurvivalCodingCampus/polytech_java_study#1
File: Readme.md:1-1
Timestamp: 2025-06-09T02:30:37.051Z
Learning: The repository `SurvivalCodingCampus/polytech_java_study` is used for class practice exercises, so minimal documentation in files like README.md may be intentional and acceptable for educational purposes.
src/main/java/com/survivalcoding/assignments_01_instance/exam01/Wand.java (1)
Learnt from: sezondo
PR: SurvivalCodingCampus/polytech_java_study#92
File: src/test/java/com/survivalcoding/WizardTest.java:21-33
Timestamp: 2025-06-17T07:25:21.221Z
Learning: In Java game programming, MP (Magic Points) value of 0 is a valid state representing a wizard who has used all their magic, so validation should only reject negative values, not zero.
src/main/java/com/survivalcoding/assignments_01_instance/exam01/Wizard.java (1)
Learnt from: sezondo
PR: SurvivalCodingCampus/polytech_java_study#92
File: src/test/java/com/survivalcoding/WizardTest.java:21-33
Timestamp: 2025-06-17T07:25:21.221Z
Learning: In Java game programming, MP (Magic Points) value of 0 is a valid state representing a wizard who has used all their magic, so validation should only reject negative values, not zero.
src/test/java/com/survivalcoding/assignments_01_instance/exam01/GreatWizardTest.java (1)
Learnt from: sezondo
PR: SurvivalCodingCampus/polytech_java_study#92
File: src/test/java/com/survivalcoding/WizardTest.java:21-33
Timestamp: 2025-06-17T07:25:21.221Z
Learning: In Java game programming, MP (Magic Points) value of 0 is a valid state representing a wizard who has used all their magic, so validation should only reject negative values, not zero.
src/main/java/com/survivalcoding/assignments_01_instance/exam01/GreatWizard.java (1)
Learnt from: sezondo
PR: SurvivalCodingCampus/polytech_java_study#92
File: src/test/java/com/survivalcoding/WizardTest.java:21-33
Timestamp: 2025-06-17T07:25:21.221Z
Learning: In Java game programming, MP (Magic Points) value of 0 is a valid state representing a wizard who has used all their magic, so validation should only reject negative values, not zero.
src/test/java/com/survivalcoding/assignments_01_instance/exam01/WizardTest.java (1)
Learnt from: sezondo
PR: SurvivalCodingCampus/polytech_java_study#92
File: src/test/java/com/survivalcoding/WizardTest.java:21-33
Timestamp: 2025-06-17T07:25:21.221Z
Learning: In Java game programming, MP (Magic Points) value of 0 is a valid state representing a wizard who has used all their magic, so validation should only reject negative values, not zero.
🪛 markdownlint-cli2 (0.17.2)
TIL/topics/java_basic/README.md

1-1: Trailing punctuation in heading
Punctuation: '.'

(MD026, no-trailing-punctuation)

TIL/topics/java_basic/용어정리.md

6-6: Heading levels should only increment by one level at a time
Expected: h2; Actual: h3

(MD001, heading-increment)


70-70: No space after hash on atx style heading

(MD018, no-missing-space-atx)


96-96: Spaces inside emphasis markers

(MD037, no-space-in-emphasis)


97-97: Spaces inside emphasis markers

(MD037, no-space-in-emphasis)

🔇 Additional comments (20)
src/main/java/com/survivalcoding/assignments_01_instance/exam01/IntangibleAsset.java (1)

4-8: 구현 간결 & 문제 없음

상위 생성자 위임만으로 목적을 충족하며 추가적인 불필요 코드가 없습니다.

src/test/java/com/survivalcoding/assignments_01_instance/exam01/TangibleAssetTest.java (1)

8-18: 구현이 깔끔하고 올바릅니다

TangibleAsset 클래스의 생성자 테스트가 적절하게 구현되어 있습니다. 필수 필드들의 초기화를 올바르게 검증하고 있습니다.

src/main/java/com/survivalcoding/assignments_01_instance/exam01/Computer.java (1)

3-17: 좋은 객체지향 설계를 보여줍니다

클래스가 적절한 캡슐화와 상속을 구현하고 있습니다. 생성자에서 부모 클래스 초기화를 올바르게 수행하고, 필드 접근을 위한 getter/setter 메서드를 제공합니다.

src/main/java/com/survivalcoding/assignments_01_instance/exam01/Book.java (1)

7-17: ISBN 관련 구현이 올바릅니다

ISBN 필드의 캡슐화와 생성자를 통한 초기화가 적절하게 구현되어 있습니다.

src/test/java/com/survivalcoding/assignments_01_instance/exam01/ComputerTest.java (1)

8-28: 포괄적인 테스트 커버리지를 제공합니다

Computer 클래스의 고유 기능(makerName)과 상속받은 기능(weight) 모두를 적절히 테스트하고 있습니다. 테스트 구조가 일관성 있고 명확합니다.

TIL/topics/java_basic/용어정리.md (1)

1-106: 내용이 잘 정리된 교육 자료입니다

Java OOP의 핵심 개념들이 체계적으로 정리되어 있고, 실제 코드 예시와 함께 설명되어 이해하기 쉽습니다. 특히 추상클래스의 "is-a" 관계와 인터페이스의 "can-do" 관계 구분이 명확하게 설명되어 있습니다.

src/main/java/com/survivalcoding/assignments_01_instance/exam01/TangibleAsset.java (1)

1-30: 상속과 인터페이스 구현이 올바르게 작성됨

클래스 설계가 잘 되어 있습니다:

  • Asset 추상 클래스 상속과 Thing 인터페이스 구현이 적절
  • 캡슐화 원칙이 잘 적용됨 (private 필드, public 접근자)
  • @OverRide 어노테이션 사용으로 메서드 오버라이드 명시
  • 생성자에서 super() 호출로 부모 클래스 초기화 수행
src/main/java/com/survivalcoding/TangibleAsset.puml (1)

1-31: 클래스 계층구조가 잘 설계됨

전체적인 상속 구조와 인터페이스 구현 관계가 명확하게 표현되어 있습니다. Asset을 기반으로 한 TangibleAsset과 IntangibleAsset의 분리, 그리고 구체적인 하위 클래스들의 관계가 잘 드러나 있습니다.

src/main/java/com/survivalcoding/assignments_01_instance/exam01/Person.java (3)

6-7: 불변 객체 설계가 잘 적용되었습니다.

필드를 final로 선언하여 불변 객체로 만든 설계가 우수합니다. 이는 객체의 안전성과 예측 가능성을 높입니다.


9-11: 생성자 파라미터 변경이 적절합니다.

age 대신 birthYear를 받도록 변경한 것이 논리적으로 타당합니다. 출생연도는 변하지 않는 값이므로 불변 객체 설계에 적합합니다.


18-20: 새로운 getter 메서드가 적절히 추가되었습니다.

getBirthYear() 메서드 추가로 캡슐화가 잘 유지되고 있습니다.

src/test/java/com/survivalcoding/assignments_01_instance/exam01/PersonTest.java (1)

1-6: 테스트 클래스 설정이 적절합니다.

패키지 선언과 JUnit 5 import가 올바르게 설정되어 있습니다.

src/test/java/com/survivalcoding/assignments_01_instance/exam01/PoisonSlimeTest.java (1)

25-38: 테스트 메소드 구조 양호

두 번째 테스트 메소드는 경계 조건을 잘 검증하고 있습니다. 여러 번의 공격 후에도 poisonCount가 음수가 되지 않는다는 것을 확인하는 것은 중요한 비즈니스 로직 검증입니다.

src/main/java/com/survivalcoding/assignments_01_instance/exam01/Slime.java (1)

1-28: 잘 구현된 Slime 클래스입니다.

클래스 설계가 적절하며, final 키워드를 사용한 suffix 필드와 attack 메서드의 로직이 올바르게 구현되어 있습니다.

src/main/java/com/survivalcoding/assignments_01_instance/exam01/PoisonSlime.java (1)

1-31: 상속과 메서드 오버라이딩이 올바르게 구현되었습니다.

Slime 클래스를 적절히 확장하여 독 공격 기능을 추가했습니다. 독 데미지 계산 로직과 poisonCount 관리가 잘 구현되어 있습니다.

src/main/java/com/survivalcoding/assignments_01_instance/exam01/GreatWizard.java (1)

1-40: 잘 설계된 GreatWizard 클래스입니다.

MP 관리 로직과 두 가지 치료 메서드(heal, superHeal)가 적절히 구현되어 있습니다. 각 메서드의 MP 소모량과 치료 효과가 균형잡혀 있습니다.

src/main/java/com/survivalcoding/assignments_01_instance/exam01/Wizard.java (1)

42-56: heal 메서드가 올바르게 구현되었습니다.

MP 관리와 치료 로직이 적절히 구현되어 있습니다. 주석처리된 이전 구현 코드도 참고용으로 유용합니다.

src/test/java/com/survivalcoding/assignments_01_instance/exam01/WizardTest.java (3)

8-27: 힐링 기능 테스트가 잘 구현되었습니다.

테스트 로직이 명확하고 예상 결과값(45)이 정확합니다. Hero의 HP가 30에서 15만큼 회복되는 것을 올바르게 검증하고 있습니다.


44-50: MP 0 값 테스트가 적절합니다.

검색된 학습 내용에 따르면, MP 값이 0인 것은 마법을 모두 사용한 유효한 상태이므로 이 테스트가 올바릅니다.


61-75: MP 부족 시 힐링 실패 테스트가 잘 작성되었습니다.

@DisplayName 어노테이션을 사용하여 테스트 목적을 명확히 설명했고, MP가 10 미만일 때 힐링이 작동하지 않는 것을 올바르게 검증하고 있습니다.

@Test
@DisplayName("Book클래스에서 weight 메서드가 잘 작동하는지 테스트")
void bookWeightTest() {
Book book = new Book("name", 10000, "color", "iabn");
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

오타 수정 필요

"iabn""isbn"의 오타로 보입니다. 이로 인해 테스트에서 사용하는 값이 일관되지 않습니다.

다음과 같이 수정하세요:

-        Book book = new Book("name", 10000, "color", "iabn");
+        Book book = new Book("name", 10000, "color", "isbn");
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
Book book = new Book("name", 10000, "color", "iabn");
Book book = new Book("name", 10000, "color", "isbn");
🤖 Prompt for AI Agents
In src/test/java/com/survivalcoding/assignments_01_instance/exam01/BookTest.java
at line 25, the string "iabn" is a typo and should be corrected to "isbn" to
maintain consistency in the test values. Replace "iabn" with "isbn" in the Book
constructor call.


public class Book extends TangibleAsset {
private String isbn;
private double weight;
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

중복된 weight 필드 제거 권장

TangibleAsset 클래스가 이미 Thing 인터페이스를 통해 weight 기능을 제공하는 것으로 보입니다. 여기서 weight 필드를 중복 선언하면 혼란을 야기할 수 있습니다.

중복된 weight 필드를 제거하세요:

public class Book extends TangibleAsset {
    private String isbn;
-    private double weight;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private double weight;
public class Book extends TangibleAsset {
private String isbn;
🤖 Prompt for AI Agents
In src/main/java/com/survivalcoding/assignments_01_instance/exam01/Book.java at
line 5, remove the duplicate private double weight field since the TangibleAsset
class already provides weight functionality through the Thing interface. This
will prevent confusion and redundancy in the code.

Comment on lines +13 to +15
class TangibleAsset extends Asset implements Thing {
-String color;
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

TangibleAsset 클래스에 weight 필드 누락

실제 Java 코드에서는 weight 필드가 있지만 UML 다이어그램에는 누락되어 있습니다.

 class TangibleAsset extends Asset implements Thing {
 -String color;
+-double weight;
 }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/main/java/com/survivalcoding/TangibleAsset.puml around lines 13 to 15,
the UML class diagram for TangibleAsset is missing the weight field that exists
in the actual Java code. Add a weight attribute to the TangibleAsset class in
the UML diagram to accurately reflect the class structure.

Comment on lines +4 to +6
interface Thing {
+double weight()
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Thing 인터페이스 메서드명이 실제 구현과 불일치

UML 다이어그램에서는 weight() 메서드로 정의되어 있지만, 실제 Java 코드에서는 getWeight()setWeight(double weight) 메서드로 구현되어 있습니다.

 interface Thing {
-+double weight()
++double getWeight()
++void setWeight(double weight)
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
interface Thing {
+double weight()
}
interface Thing {
+double getWeight()
+void setWeight(double weight)
}
🤖 Prompt for AI Agents
In src/main/java/com/survivalcoding/TangibleAsset.puml around lines 4 to 6, the
Thing interface method name weight() does not match the actual Java
implementation which uses getWeight() and setWeight(double weight). Update the
UML diagram to replace weight() with getWeight() and setWeight(double weight)
methods to accurately reflect the Java code.

@@ -1,27 +1,28 @@
package com.survivalcoding.assignments_01_instance.exam01;

import java.util.Date;
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

현대적인 날짜 API 사용을 권장합니다.

java.util.Date는 Java 8부터 deprecated되었습니다. java.time 패키지의 LocalDateYear를 사용하는 것이 좋습니다.

다음과 같이 수정하는 것을 권장합니다:

-import java.util.Date;
+import java.time.Year;

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/main/java/com/survivalcoding/assignments_01_instance/exam01/Person.java
at line 3, replace the import of the deprecated java.util.Date with
java.time.LocalDate or java.time.Year as appropriate. Update any usage of Date
in the code to use LocalDate or Year from the java.time package to follow modern
Java date/time API practices.

Comment on lines +19 to +26
public void setPower(double power){

if(this.power <0.5 || power>100){
throw new IllegalArgumentException("메세지");
}

this.power = power;
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

유효성 검증 로직의 심각한 오류를 수정해야 합니다.

setPower 메서드의 유효성 검증에서 this.power < 0.5를 확인하고 있는데, 이는 현재 저장된 power 값을 확인하는 것입니다. 입력 매개변수 power를 검증해야 합니다.

다음 diff를 적용하여 논리 오류를 수정하세요:

-        if(this.power <0.5 || power>100){
+        if(power < 0.5 || power > 100){
             throw new IllegalArgumentException("메세지");
         }
🤖 Prompt for AI Agents
In src/main/java/com/survivalcoding/assignments_01_instance/exam01/Wand.java
between lines 19 and 26, the validation logic in setPower incorrectly checks the
current object's power field instead of the input parameter. Change the
condition to validate the input parameter 'power' by checking if power is less
than 0.5 or greater than 100, and throw the IllegalArgumentException accordingly
before assigning it to this.power.

Comment on lines +26 to +31
public void setHp(int hp){
if(this.hp<0){
hp = 0;
}
this.hp = hp;
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

HP 유효성 검증 로직의 심각한 오류를 수정해야 합니다.

setHp 메서드에서 this.hp < 0을 확인하고 있는데, 이는 현재 저장된 hp 값을 확인하는 것입니다. 입력 매개변수 hp를 검증해야 합니다.

다음 diff를 적용하여 논리 오류를 수정하세요:

-        if(this.hp<0){
+        if(hp < 0){
             hp = 0;
         }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public void setHp(int hp){
if(this.hp<0){
hp = 0;
}
this.hp = hp;
}
public void setHp(int hp){
if (hp < 0) {
hp = 0;
}
this.hp = hp;
}
🤖 Prompt for AI Agents
In src/main/java/com/survivalcoding/assignments_01_instance/exam01/Wizard.java
lines 26 to 31, the setHp method incorrectly checks this.hp < 0 instead of
validating the input parameter hp. Fix this by changing the condition to check
if the input hp is less than 0, and if so, set hp to 0 before assigning it to
this.hp.

Comment on lines +35 to +40
public void setMp(int mp){
if(this.mp<0){
throw new IllegalArgumentException("메세지");
}
this.mp = mp;
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

MP 유효성 검증 로직의 심각한 오류를 수정해야 합니다.

setMp 메서드에서 this.mp < 0을 확인하고 있는데, 이는 현재 저장된 mp 값을 확인하는 것입니다. 입력 매개변수 mp를 검증해야 합니다.

다음 diff를 적용하여 논리 오류를 수정하세요:

-        if(this.mp<0){
+        if(mp < 0){
             throw new IllegalArgumentException("메세지");
         }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public void setMp(int mp){
if(this.mp<0){
throw new IllegalArgumentException("메세지");
}
this.mp = mp;
}
public void setMp(int mp){
if(mp < 0){
throw new IllegalArgumentException("메세지");
}
this.mp = mp;
}
🤖 Prompt for AI Agents
In src/main/java/com/survivalcoding/assignments_01_instance/exam01/Wizard.java
between lines 35 and 40, the setMp method incorrectly checks if this.mp is less
than 0 instead of validating the input parameter mp. To fix this, change the
condition to check if the input parameter mp is less than 0, and throw the
IllegalArgumentException if so, before assigning mp to this.mp.

Comment on lines +52 to +59
@Test
public void turnintominustozerotest(){
Wizard wizard = new Wizard();

wizard.setHp(-10);
assertEquals(0,wizard.getHp());

}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

음수 HP 처리 테스트에 메서드명 개선이 필요합니다.

테스트 로직은 정확하지만 메서드명이 명확하지 않습니다.

-    public void turnintominustozerotest(){
+    public void testNegativeHpConvertedToZero(){
🤖 Prompt for AI Agents
In
src/test/java/com/survivalcoding/assignments_01_instance/exam01/WizardTest.java
around lines 52 to 59, the test method name turnintominustozerotest is unclear.
Rename the method to a more descriptive name such as testSetHpWithNegativeValue
or testHpCannotBeNegative to clearly indicate that the test verifies setting HP
to a negative value results in HP being set to zero.

Comment on lines +30 to +42
@Test
public void ver3texttest(){
Wand wand = new Wand();
wand.setName("abc");
assertEquals("abc",wand.getName());
}

@Test
public void powertest(){
Wand wand = new Wand();
wand.setPower(0.5);
assertEquals(0.5,wand.getPower());
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

테스트 메서드 명명 규칙을 개선하세요.

메서드명이 Java 명명 규칙을 따르지 않고 있습니다. 더 명확하고 표준적인 이름을 사용하는 것이 좋겠습니다.

다음과 같이 개선할 수 있습니다:

-    public void ver3texttest(){
+    public void testWandGetName(){

-    public void powertest(){
+    public void testWandGetPower(){
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@Test
public void ver3texttest(){
Wand wand = new Wand();
wand.setName("abc");
assertEquals("abc",wand.getName());
}
@Test
public void powertest(){
Wand wand = new Wand();
wand.setPower(0.5);
assertEquals(0.5,wand.getPower());
}
@Test
public void testWandGetName(){
Wand wand = new Wand();
wand.setName("abc");
assertEquals("abc",wand.getName());
}
@Test
public void testWandGetPower(){
Wand wand = new Wand();
wand.setPower(0.5);
assertEquals(0.5,wand.getPower());
}
🤖 Prompt for AI Agents
In
src/test/java/com/survivalcoding/assignments_01_instance/exam01/WizardTest.java
around lines 30 to 42, the test method names ver3texttest and powertest do not
follow Java naming conventions and lack clarity. Rename these methods to use
camelCase and descriptive names, such as testWandName or testSetName for
ver3texttest, and testWandPower or testSetPower for powertest, to improve
readability and maintain standard naming practices.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 7

🧹 Nitpick comments (9)
src/main/java/com/survivalcoding/assignments_01_instance/exam01/StrongBox.java (2)

16-24: 동시성 문제 개선을 고려하세요.

현재 count 필드의 증가 연산이 thread-safe하지 않습니다. 멀티스레드 환경에서 사용될 가능성이 있다면 동기화 처리를 고려해야 합니다.

다음과 같이 개선할 수 있습니다:

+import java.util.concurrent.atomic.AtomicInteger;

public class StrongBox<E> {
    private E data;
    private KeyType keyType;
-    private int count;
+    private AtomicInteger count = new AtomicInteger(0);

    public E get() {
-        count++;
+        int currentCount = count.incrementAndGet();

-        if(count <= keyType.getLimit()) {
+        if(currentCount <= keyType.getLimit()) {
            return null;
        }

        return this.data;
    }

8-10: put 메서드에 유효성 검증을 추가하는 것을 고려하세요.

현재 put 메서드는 null 값도 허용합니다. 비즈니스 로직에 따라 null 값 저장을 허용할지 결정하고, 필요시 유효성 검증을 추가하세요.

필요시 다음과 같이 개선할 수 있습니다:

public void put(E data) {
+    if (data == null) {
+        throw new IllegalArgumentException("Data cannot be null");
+    }
    this.data = data;
}
TIL/topics/java_basic/용어정리.md (7)

3-3: 헤딩 레벨을 한 단계만 증가시키세요

# 다음에 바로 ###를 사용하면 MD001 룰 위반입니다. ##로 조정해 주세요.

-### equals() & hashCode()
+## equals() & hashCode()

5-5: 오타: “해서” → “해시”

해시 기반 컬렉션을 설명하는 문맥이므로 오타를 수정하세요.

-* hashCode(): 객체를 해서 기반 컬렉션(Set,Map 등)에 넣기 위한 해시값 생성기
+* hashCode(): 객체를 해시 기반 컬렉션(Set, Map 등)에 넣기 위한 해시값 생성기

17-17: 헤딩 레벨 불일치(제네릭)

상위 # 제네릭, … 바로 아래이므로 ### 대신 ##가 적절합니다.

-### 제네릭(Generic)
+## 제네릭(Generic)

21-21: 헤딩 레벨 불일치(열거형)

동일 섹션 내 서브헤딩도 ##로 맞춰 주세요.

-### 열거형(Enum)
+## 열거형(Enum)

44-44: 헤딩 레벨 불일치(추상클래스 vs 인터페이스)

# 추상클래스와 인터페이스의 하위 제목은 ##가 적절합니다.

-### 추상클래스와 인터페이스의 차이점
+## 추상클래스와 인터페이스의 차이점

108-108: 헤딩 앞에 공백 누락

## 뒤에 바로 텍스트가 붙어 있어 MD018 경고가 발생합니다.

-##클래스 생성자 용어 정리 (25.06.16)
+## 클래스 생성자 용어 정리 (25.06.16)

134-135: 강조 표기 내부 공백 제거

언더스코어 강조 구문 내부에 공백이 있어 MD037 위반입니다. 백틱을 사용하면 혼동을 줄일 수 있습니다.

-final : 변경불가 키워드(const 같은 거) _ 한번 초기화되면 이후로 값이 바뀔 수 없음.
-this : 현재 객체를 참조하는 키워드 _ 현재 객체 자기 자신을 가리킴. 
+final : 변경불가 키워드(const 같은 거) `한번 초기화되면 이후로 값이 바뀔 수 없음.`
+this : 현재 객체를 참조하는 키워드 `현재 객체 자기 자신을 가리킴.`
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c0280d9 and f53e54b.

📒 Files selected for processing (5)
  • TIL/topics/java_basic/용어정리.md (1 hunks)
  • src/main/java/com/survivalcoding/assignments_01_instance/exam01/Book2.java (1 hunks)
  • src/main/java/com/survivalcoding/assignments_01_instance/exam01/StrongBox.java (1 hunks)
  • src/test/java/com/survivalcoding/assignments_01_instance/exam01/Book2Test.java (1 hunks)
  • src/test/java/com/survivalcoding/assignments_01_instance/exam01/StrongBoxTest.java (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: Hae1Won1
PR: SurvivalCodingCampus/polytech_java_study#1
File: Readme.md:1-1
Timestamp: 2025-06-09T02:30:37.051Z
Learning: The repository `SurvivalCodingCampus/polytech_java_study` is used for class practice exercises, so minimal documentation in files like README.md may be intentional and acceptable for educational purposes.
src/main/java/com/survivalcoding/assignments_01_instance/exam01/Book2.java (1)
Learnt from: Yuny2036
PR: SurvivalCodingCampus/polytech_java_study#170
File: src/main/java/com/survivalcoding/asset/Book.java:69-78
Timestamp: 2025-07-07T08:33:32.454Z
Learning: In the `SurvivalCodingCampus/polytech_java_study` repository, students may be explicitly instructed to use deprecated methods like `Date.getYear()`, `Date.getMonth()`, and `Date.getDay()` for educational purposes, even though these methods are deprecated. This is intentional for learning objectives and should not be flagged as issues requiring modernization.
🧬 Code Graph Analysis (1)
src/test/java/com/survivalcoding/assignments_01_instance/exam01/StrongBoxTest.java (1)
src/main/java/com/survivalcoding/assignments_01_instance/exam01/StrongBox.java (1)
  • StrongBox (3-39)
🪛 markdownlint-cli2 (0.17.2)
TIL/topics/java_basic/용어정리.md

3-3: Heading levels should only increment by one level at a time
Expected: h2; Actual: h3

(MD001, heading-increment)


17-17: Heading levels should only increment by one level at a time
Expected: h2; Actual: h3

(MD001, heading-increment)


44-44: Heading levels should only increment by one level at a time
Expected: h2; Actual: h3

(MD001, heading-increment)


108-108: No space after hash on atx style heading

(MD018, no-missing-space-atx)


134-134: Spaces inside emphasis markers

(MD037, no-space-in-emphasis)


135-135: Spaces inside emphasis markers

(MD037, no-space-in-emphasis)

🔇 Additional comments (5)
src/test/java/com/survivalcoding/assignments_01_instance/exam01/StrongBoxTest.java (1)

10-22: 테스트 로직이 올바르게 구현되었습니다.

PADLOCK 키 타입의 제한 횟수(1024회)를 정확히 검증하고, 1025번째 호출에서 데이터가 반환되는지 확인하는 테스트 로직이 올바르게 작성되었습니다.

src/main/java/com/survivalcoding/assignments_01_instance/exam01/StrongBox.java (2)

3-6: 제네릭 클래스 구조가 잘 설계되었습니다.

StrongBox<E> 클래스는 제네릭을 활용하여 타입 안전성을 보장하면서도 재사용 가능한 코드를 작성했습니다. 필드 구성도 적절합니다.


26-38: Enum 활용이 효과적입니다.

KeyType enum은 각 키 타입별로 고정된 제한 횟수를 정의하여 상수와 관련 데이터를 함께 관리하는 좋은 예시입니다. 불변 필드와 getter 메서드 구현이 적절합니다.

src/test/java/com/survivalcoding/assignments_01_instance/exam01/Book2Test.java (1)

10-18: 테스트 로직이 올바르게 구현되었습니다.

equals 메서드의 동작을 정확히 검증하고 있습니다. 동일한 제목과 출간일을 가진 두 Book2 객체가 다른 코멘트를 가져도 equals에서 true를 반환하는지 확인하고 있습니다.

src/main/java/com/survivalcoding/assignments_01_instance/exam01/Book2.java (1)

5-8: 클래스 설계가 잘 구성되어 있습니다.

Comparable 인터페이스 구현과 필드 구성이 적절하며, 교육 목적에 맞게 잘 설계되었습니다.

@DisplayName("제한 횟수 초과되면 열림")

void testUnlock() {
StrongBox box = new StrongBox(StrongBox.KeyType.PADLOCK);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

제네릭 타입 매개변수를 명시하세요.

StrongBox를 생성할 때 제네릭 타입을 명시하지 않아 raw type 경고가 발생합니다. 타입 안전성을 위해 제네릭 매개변수를 지정해야 합니다.

다음과 같이 수정하세요:

-        StrongBox box = new StrongBox(StrongBox.KeyType.PADLOCK);
+        StrongBox<String> box = new StrongBox<>(StrongBox.KeyType.PADLOCK);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
StrongBox box = new StrongBox(StrongBox.KeyType.PADLOCK);
StrongBox<String> box = new StrongBox<>(StrongBox.KeyType.PADLOCK);
🤖 Prompt for AI Agents
In
src/test/java/com/survivalcoding/assignments_01_instance/exam01/StrongBoxTest.java
at line 14, the StrongBox instance is created without specifying the generic
type parameter, causing a raw type warning. To fix this, explicitly provide the
appropriate generic type argument when instantiating StrongBox to ensure type
safety and eliminate the warning.

Comment on lines +59 to +64
public Book2 clone() {
return new Book2(
this.title, (Date) this.publishDate.clone(), this.comment
);

}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

clone 메서드에서 null 포인터 예외 위험이 있습니다.

publishDate가 null인 경우 61번 라인에서 NullPointerException이 발생할 수 있습니다.

다음과 같이 수정하여 null 안전성을 보장하세요:

public Book2 clone() {
    return new Book2(
-           this.title, (Date) this.publishDate.clone(), this.comment
+           this.title, this.publishDate != null ? (Date) this.publishDate.clone() : null, this.comment
    );
}
🤖 Prompt for AI Agents
In src/main/java/com/survivalcoding/assignments_01_instance/exam01/Book2.java
around lines 59 to 64, the clone method risks a NullPointerException if
publishDate is null. To fix this, add a null check before cloning publishDate;
if publishDate is null, pass null instead of calling clone on it. This ensures
null safety when creating the new Book2 instance.

Comment on lines +28 to +30
public void setPublishDate(Date publishDate) {
this.publishDate = publishDate;
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Date 객체의 가변성으로 인한 캡슐화 위반 가능성

외부에서 전달된 Date 객체를 직접 할당하면 외부에서 내부 상태를 변경할 수 있습니다.

방어적 복사를 통해 캡슐화를 보장하세요:

public void setPublishDate(Date publishDate) {
-   this.publishDate = publishDate;
+   this.publishDate = publishDate != null ? (Date) publishDate.clone() : null;
}
🤖 Prompt for AI Agents
In src/main/java/com/survivalcoding/assignments_01_instance/exam01/Book2.java
around lines 28 to 30, the setter method for publishDate directly assigns the
passed Date object, which can lead to encapsulation violation due to Date's
mutability. Fix this by creating a defensive copy of the passed Date object
before assigning it to the field, ensuring internal state cannot be altered
externally.

Comment on lines +24 to +26
public Date getPublishDate() {
return publishDate;
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Date 객체의 가변성으로 인한 캡슐화 위반 가능성

Date 객체는 가변 객체이므로 getter에서 직접 반환하면 외부에서 내부 상태를 변경할 수 있습니다.

방어적 복사를 통해 캡슐화를 보장하세요:

public Date getPublishDate() {
-   return publishDate;
+   return publishDate != null ? (Date) publishDate.clone() : null;
}
🤖 Prompt for AI Agents
In src/main/java/com/survivalcoding/assignments_01_instance/exam01/Book2.java
around lines 24 to 26, the getPublishDate method returns the mutable Date object
directly, which can lead to encapsulation violation by allowing external
modification of the internal state. To fix this, modify the getter to return a
defensive copy of the publishDate by creating and returning a new Date object
initialized with the value of publishDate, thus preserving encapsulation.

Comment on lines +54 to +57
@Override
public int compareTo(Book2 other) {
return this.publishDate.compareTo(other.publishDate);
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

compareTo 메서드에서 null 포인터 예외 위험이 있습니다.

this.publishDate가 null인 경우 NullPointerException이 발생할 수 있습니다.

다음과 같이 수정하여 null 안전성을 보장하세요:

@Override
public int compareTo(Book2 other) {
-   return this.publishDate.compareTo(other.publishDate);
+   if (this.publishDate == null && other.publishDate == null) return 0;
+   if (this.publishDate == null) return -1;
+   if (other.publishDate == null) return 1;
+   return this.publishDate.compareTo(other.publishDate);
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@Override
public int compareTo(Book2 other) {
return this.publishDate.compareTo(other.publishDate);
}
@Override
public int compareTo(Book2 other) {
if (this.publishDate == null && other.publishDate == null) return 0;
if (this.publishDate == null) return -1;
if (other.publishDate == null) return 1;
return this.publishDate.compareTo(other.publishDate);
}
🤖 Prompt for AI Agents
In src/main/java/com/survivalcoding/assignments_01_instance/exam01/Book2.java
around lines 54 to 57, the compareTo method risks throwing a
NullPointerException if this.publishDate is null. To fix this, add null checks
before calling compareTo on publishDate. Implement logic to handle cases where
either this.publishDate or other.publishDate is null, ensuring the method
returns a consistent ordering without throwing exceptions.

Comment on lines +49 to +52
@Override
public int hashCode() {
return title.hashCode() + publishDate.hashCode();
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

hashCode 메서드에서 null 포인터 예외 위험이 있습니다.

title이나 publishDate가 null인 경우 NullPointerException이 발생할 수 있습니다. 또한 현재 구현은 hashCode 계산에서 충돌 가능성이 높습니다.

다음과 같이 수정하여 null 안전성과 더 나은 해시 분산을 보장하세요:

@Override
public int hashCode() {
-   return title.hashCode() + publishDate.hashCode();
+   return Objects.hash(title, publishDate);
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@Override
public int hashCode() {
return title.hashCode() + publishDate.hashCode();
}
@Override
public int hashCode() {
return Objects.hash(title, publishDate);
}
🤖 Prompt for AI Agents
In src/main/java/com/survivalcoding/assignments_01_instance/exam01/Book2.java
around lines 49 to 52, the hashCode method risks NullPointerException if title
or publishDate is null and has a high collision probability. To fix this, modify
the method to check for null values before calling hashCode on these fields and
use a standard formula like multiplying one hash by a prime number before adding
the other to improve hash distribution and reduce collisions.

Comment on lines +41 to +47
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;

Book2 other = (Book2) obj;
return this.title.equals(other.title) && this.publishDate.equals(other.publishDate);
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

equals 메서드에서 null 포인터 예외 위험이 있습니다.

title이 null인 경우 46번 라인에서 NullPointerException이 발생할 수 있습니다. 방어적 프로그래밍을 위해 null 체크를 추가해야 합니다.

다음과 같이 수정하여 null 안전성을 보장하세요:

@Override
public boolean equals(Object obj) {
    if (this == obj) return true;
    if (obj == null || getClass() != obj.getClass()) return false;
    
    Book2 other = (Book2) obj;
-   return this.title.equals(other.title) && this.publishDate.equals(other.publishDate);
+   return Objects.equals(this.title, other.title) && Objects.equals(this.publishDate, other.publishDate);
}

Objects.equals 사용을 위해 import문도 추가해야 합니다:

+import java.util.Objects;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Book2 other = (Book2) obj;
return this.title.equals(other.title) && this.publishDate.equals(other.publishDate);
}
// add this among your other imports
import java.util.Objects;
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Book2 other = (Book2) obj;
return Objects.equals(this.title, other.title)
&& Objects.equals(this.publishDate, other.publishDate);
}
🤖 Prompt for AI Agents
In src/main/java/com/survivalcoding/assignments_01_instance/exam01/Book2.java
around lines 41 to 47, the equals method risks a NullPointerException if title
or publishDate is null. To fix this, add null-safe checks by replacing direct
equals calls with Objects.equals for both title and publishDate comparisons.
Also, add the necessary import for java.util.Objects at the top of the file.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant