231027 TIL

SEULBI LEE·2023년 10월 27일
1

TIL

목록 보기
13/25

보충반
클래스는 설계도. new로 생성하는 순간 객체가 만들어진다.
모든 변수는 의미를 생각해서 Class Attribute에 표현한다.
클래스, 객체 이름은 명사, 메소드 이름은 동사로 사용한다.

오늘의 보충반 과제
주변에 보이는 하나의 물체를 정하고, 클래스로 만들어 Pull Resuquest를 날려주세요.
클래스 여러 개를 모아서 한 개의 객체가 되어도 좋고 한 개의 클래스가 한 개의 객체가 되어도 좋습니다.

객체 지향 개념을 이해하기 위한 보충반 과제로 선크림 클래스를 만들어 보았다.
선크림에는 자외선 차단이라는 메서드 외에 있을까 싶어서, 일단 증감 메서드 하나 적었다.
간단할 거라고 생각했는데 이것 저것 제약 사항을 생각하니 은근히 오래 걸린다.
그리고 클래스 안에 리스트를 만든 건 필요 없는 행동이었던 것 같다.

완성 과제

package SeulBi;

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

public class SunCream {
    private String brand; // 회사 이름
    private String productName; // 상품 이름
    private Integer sunProtectionFactor = 50; // 자외선 차단 지수
    private String formulation; // 제형
    private Double millilitre; // 용량
    private Double remainingMillilitre; // 남은 양
    private final Integer effectTimeOfSPA = sunProtectionFactor*15; // 자외선 차단 지속 시간(분)
    private Integer price; // 가격
    private static final Double recommendMl = 0.8;

    private List<SunCream> basket = new ArrayList<>();

    SunCream(String brand, String productName){
        this.brand = brand;
        this.productName = productName;
        this.formulation = "무기자차";
        this.millilitre = 50.0;
        this.remainingMillilitre = this.millilitre;
        this.price = 8000;
    }

    SunCream(String brand, String productName, String formulation, Integer spf, Double millilitre, Integer price){
        this.brand = brand;
        this.productName = productName;
        this.formulation = formulation;
        this.sunProtectionFactor = spf;
        this.millilitre = millilitre;
        this.remainingMillilitre = this.millilitre;
        this.price = price;
    }

    public void buySunCream(){
        System.out.println("구매가 완료되었습니다.");
        System.out.println();
        System.out.println(brand + " 회사의 [" + productName +"] 상품을 선택하셨습니다.");
        System.out.println("제형은 " + formulation + "이며 자외선 차단 지수는 " + sunProtectionFactor+"입니다.");
        System.out.println("용량은 " + millilitre +"ml이고, 가격은 " + price + "원입니다." );
        System.out.println("----------------------------------------------------------");

        basket.add(new SunCream(brand, productName, formulation, sunProtectionFactor, millilitre, price));
    }

    public Double useSuncream(Double usingMillilitre){
        if(Objects.equals(remainingMillilitre,0.0)){
            System.out.println("남은 선크림이 없습니다. 새로운 선크림을 구입해 보세요!");
            System.out.println("----------------------------------------------------------");
        } else if (millilitre - usingMillilitre < 0.0){
            System.out.println("남은 용량보다 많은 양을 사용하실 수 없습니다.");
            System.out.println("----------------------------------------------------------");
        } else if(millilitre - usingMillilitre >= 0.0) {
            remainingMillilitre = millilitre - usingMillilitre;
            if(usingMillilitre < recommendMl){
                System.out.println("선크림을 " + usingMillilitre + "ml 사용하셨습니다.");
                System.out.println("성인의 선크림 권장 용량은 1회당 최소 " + recommendMl + "ml이므로 자외선 차단 시간 측정이 어렵습니다.");
                System.out.println("다음 번에는 권장 용량을 지켜 사용하시는 것을 추천드립니다.");
                System.out.println("남은 선크림 용량은 "+ remainingMillilitre+"ml입니다.");
                System.out.println("즐거운 외출 되세요!");
                System.out.println("----------------------------------------------------------");
            } else {
                System.out.println("선크림을 " + usingMillilitre + "ml 사용하셨습니다.");
                System.out.println("자외선 차단 지속 시간은 " + effectTimeOfSPA + "분이며 남은 선크림 용량은 "+ remainingMillilitre+"ml입니다.");
                System.out.println("즐거운 외출 되세요!");
                System.out.println("----------------------------------------------------------");
            }
        }

        return remainingMillilitre;
    }

    public void checkSuncream(){
        System.out.println(productName + "의 자외선 차단 지수는 " + sunProtectionFactor + "이며 남은 용량은 " + remainingMillilitre + "ml입니다." );
        System.out.println("----------------------------------------------------------");
    }

    public static void main(String[] args) {
        // 메서드 확인용 객체 생성
        SunCream mySunCream1 = new SunCream("에뛰드","순정 선크림");
        SunCream mySunCream2 = new SunCream("라운드랩","자작나무 수분 선크림","무기자차",50,50.0,12000);

        mySunCream1.buySunCream();
        mySunCream2.buySunCream();

        mySunCream1.useSuncream(0.5);
        mySunCream2.useSuncream(50.0);

        mySunCream1.useSuncream(0.8);
        mySunCream2.useSuncream(1.0);

        mySunCream1.checkSuncream();


    }
}

모던 자바

프로그래밍 언어는 시장의 상황에 따라 새로운 대안으로 등장하거나 도태되거나 다양한 변화를 겪습니다.
자바가 대면한 새 시대의 요구사항...
1. 병렬 처리
2. 함수형 프로그래밍
수학의 함수처럼, 특정한 데이터에 의존하지 않고, 관련 없는 데이터를 변경하지도 않으며, 결과값이 오직 입력 값에만 영향을 받는 함수를 순수함수라고 한다.
검증이 쉽고, 성능 최적화가 쉽고, 동시성 문제를 해결하기 쉽다.

코드의 재사용성. 유지보수. 확장. 신뢰성.을 달성해야 합니다.

자바 함수의 변화
함수를 일급 값으로 받기로 했다.
함수를 변수처럼 쓸 수 있다.
메서드는 변수처럼 쓸 수 없어 이급 값이다.

람다(익명 함수)를 받아들이기로 했다.
이것이 바로 일급 객체.
함수를 값으로 사용할 수도 있으며 파라미터에 전달할 수 있다.

스트림은 데이터 처리 연산을 지원하도록 소스에서 추출된 연속된 요소.
컬렉션 : 데이터 저장, 접근
스트림 : 데이터 처리(인터페이스입니다.)

함수형 인터페이스

인터페이스는 타입 역할을 할 수 있다.
함수를 인자로 사용할 때는 타입을 알려주기 위해 함수형 인터페이스를 사용한다.
함수형 인터페이스는 추상 메소드를 딱 하나만 가지고 있다.

람다 함수
(인자로 들어갈 매개 변수) -화살표-> {로직. 간단하면 중괄호도 생략 가능}

스트림

자료구조의 흐름을 객체로 제공하는 것.
메서드를 api 형태로 제공함.

  1. 원본의 데이터를 변경하지 않습니다.
  2. 일회용입니다.

filter vs map?
filter : 조건에 맞는 것만 반환
map : 모든 요소를 가공해서 반환

forEach : 원소에 넘겨받은 함수를 실행함.

복습 키워드 뽑기

  • 객체 지향 프로그래밍
  • 예외처리
  • 컬렉션 프레임웍
  • 지네릭스, 열거형, 애너테이션
  • 람다와 스트림
  • 배열

하루를 마무리하며

오늘은 좋은 개발자의 비밀이라는 특강을 오후에 들었는데, 나에게 가장 부족한 미덕이 무엇인지 계속해서 상기할 수 있는 시간이었다. 나는... 질문을 너무 못한다!
상대방이 어떻게 하면 내 말을 들어줄까?
를 생각해보라고 하셨는데...
지금까지 짧은 팀프 경험을 돌아보면... 내가 전에 경험했던 회사 문화와는 다른 느낌이 있다.
대답을 인내심있게 기다려야 한다는 거? 다들 원하는 로직이 마음 깊이 있으니 충분히 말할 수 있을 때까지 기다려야 한다는 거. 그리고 짧게 말하는 걸 좋아한다는 거.
뭘 모르는지 명확히 파악할 수 있게 꼭 복습 키워드는 주말에 다시 보자.
이번 주도 고생 많았다.

0개의 댓글