Skip to content
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

18p: 불변속성의 범위제한 #3

Open
yunseorim1116 opened this issue Apr 6, 2024 · 2 comments
Open

18p: 불변속성의 범위제한 #3

yunseorim1116 opened this issue Apr 6, 2024 · 2 comments
Assignees
Labels
question Further information is requested

Comments

@yunseorim1116
Copy link
Member

yunseorim1116 commented Apr 6, 2024

불변속성이란 ?

코드에서 상태(조건)를 명시적으로 확인하지 않는 속성이다.

예제내용

  • 2년전에는 과일과 야채를 판매했다.
  • 2년 후, 매장에서 전구를 판매하기 시작했다.
  • 시스템 업데이트 요청을 받았다. 바로 전구를 추가한다.
    (=> 전구에는 만료 일이 없다. 일수를 빼고 0에 도달하면 품목을 삭제하는 기능이 있지만 이렇게 하면 만료일이 없는 전구는 에러가 난다.)

범위가 제한되지 않은 불변속성은 어떻게 손상될까 ?

| 문제 되는 프로그램 코드 보기

Manage : 식료품 가게에 대한 관리 프로그램
Product : 관리 대상 프로덕트

class Product {
  name;
  daysUntilExpiry;
  value;
  urgency;

  constructor(name, daysUntilExpiry, value) {
    this.name = name;
    this.daysUntilExpiry = daysUntilExpiry;
    this.value = value;
  }

  decrementExpiry() {
    return (this.daysUntilExpiry -= 1);
  }

  getUrgency() {
    this.urgency = this.value / this.daysUntilExpiry;
    return this.urgency;
  }
}

class Manager {
  products = [];

  constructor(products) {
    this.products = products;
  }

  viewProduct() {
    this.products.forEach((product) => {
      const urgency = product.getUrgency();
      console.log(`${product.name} urgency: ${urgency}`);
    });
  }

  filterExpireProduct() {
    this.products = this.products.filter(
      (product) => product.daysUntilExpiry > 0
    );
  }

  updateProducts() {
    this.products.forEach((product) => {
      product.decrementExpiry();
    });

    this.filterExpireProduct();
  }
}

const apple = new Product("Apple", 5, 10);
const carrot = new Product("Carrot", 3, 5);
const lightBulb = new Product("Light Bulb", 0, 3);

const manager = new Manager([apple, lightBulb]);

manager.updateProducts();
manager.viewProduct();

[ 책 내용 ]

  • 변수를 명시적으로 체크해서 불변 속성을 제거함으로써 유지보수성을 향상시킬 수 있다.
  • 다만 불변속성을 더욱 쉽게 볼 수 있도록 서로 가깝게 이동시켜 유지보수성을 향상시킨다. (이를 가리켜 함께 변하는 것은 함께 있어야 한다. 는 의미의 불변속성의 범위 제한 이라고 한다)

[ 그 외 ]

  • 서로 가깝게 이동시키는것 뿐만 아닌 또 다른 방법으로 불변속성이 지켜지지 않은 코드를 개선할 수 있을까?
  • 불변속성 === 유효성 검사가 명시적으로 덜 된 코드, 라고 봐도 되는 것일까 ?
  • 예시 코드는 예시 코드일뿐, 예시 코드 자체를 변경 가능. 예시 코드를 디벨롭시켜서 더욱 적절한 예시를 만들기 :D
  • 불변속성의 범위 제한이 있지 않은 기존 코드를 개선해보기

+) 디스커션에 올릴지 이슈에 올릴지 고민이 돼서 이슈에 올렸는데 의견 주셔도 좋습니다 !

@yunseorim1116
Copy link
Member Author

2장의 호스트님이신 승희님을 태그했습니다.........^^!!! 교수님 믿습니다

@yunseorim1116 yunseorim1116 added the question Further information is requested label Apr 6, 2024
@sa02045
Copy link
Contributor

sa02045 commented Apr 13, 2024

1.daysUntilExpiry는 항상 양수인 불변속성이다.

  • 이 프로그램에서 daysUntilExpiry > 0은 항상 true이다.
  • 코드를 통해 프로그래밍적으로 양수임을 보장하는 것이 아니라 코드를 작성하는 개발자가 "양수로 다루겠다"라는 의미이다.
  1. 전구를 판매하기 시작함으로서 daysUntilExpiry는 양수가 아닌 0이 될 수 있게 되었다. 즉, 불변속성이 아니게 되었다.

    • daysUntilExpiry > 0은 항상 true로 다루었는데 그것을 위반하게 되었다.
    • 취약한 코드가 되었다
  2. 해결방법은 불변속성이 깨진 변수를 �체크하거나, 불변속성의 범위를 제한하는 것이다.

 getUrgency() {
    assert(this.daysUntilExpiry !== 0, new Error("~~")))
    this.urgency = this.value / this.daysUntilExpiry;
    return this.urgency;
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants