프론트엔드 데브코스 5기 TIL 8 - 명령/선언/상태

김영현·2023년 10월 4일
0

TIL

목록 보기
9/129

명령형 vs 선언형

  • 명령형 프로그래밍은 컴퓨터가 수행할 명령을 순서대로 써놓은 것.
    => 대부분의 프로그래밍 언어 특징이다.
const arr = [1,2,3,4,5]
let result = [];
for(let i = 0; i<arr.length; i++){
	result.push(arr[i]*2);
}
return result
  • 선언형 프로그래밍은 무엇이 나타나야 하는지를 설명
    => 추상화가 잘 된 프로그래밍(프로그래밍언어는 아니지만, html과 sql도 선언형이다)
const result = arr.map((el) => el*2);

선언형으로 프로그래밍하면, 유지보수하거나 기능을 추가할때 편하다.(짧잖아~)

class ToggleButton {
  constructor(target, text) {
    this.$target = target;
    this.text = text;
    this.button = document.createElement("button");
    this.createElement();
    this.render();
    this.addEvent();
  }
  addEvent() {
    this.button.addEventListener("click", (e) => {
      if (this.button.style.textDecoration === "line-through") {
        this.button.style.textDecoration = "";
      } else this.button.style.textDecoration = "line-through";
    });
  }
  createElement() {
    this.$target.appendChild(this.button);
  }
  render() {
    this.button.textContent = this.text;
  }
}

const $root = document.getElementById("root");
new ToggleButton($root, "button1");
new ToggleButton($root, "button2");
new ToggleButton($root, "button3");

이렇게 하면 여러개의 버튼을 제작해야하는 명령형보다 더 간단히 할수있다.
=> oop가 이래서 나왔구나.

하지만 여기에도 수정할 부분이 있다. 스타일 자체를 바꾸지 말고, 상태에 의존하도록 만들면 조작이 더 간단해진다.

class ToggleButton {
  constructor(target, text, onClick) {
    this.$target = target;
    this.text = text;
    this.button = document.createElement("button");
    this.count = 0;
    this.onClick = onClick;
    this.state = {
      clickCount: 0,
      toggled: false,
    };
    this.createElement();
    this.render();
    this.addEvent();
  }
  addEvent() {
    this.button.addEventListener("click", () => {
      this.setState({
        clickCount: this.state.clickCount + 1,
        toggled: !this.state.toggled,
      });
      if (this.onClick) this.onClick(this.state.clickCount);
      console.log(this.state);
    });
  }
  createElement() {
    this.$target.appendChild(this.button);
  }
  setState(newState) {
    this.state = { ...this.state, ...newState };
    this.render();
  }
  render() {
    this.button.textContent = this.text;
    this.button.style.textDecoration = this.state.toggled
      ? "line-through"
      : "none";
  }
}

const $root = document.getElementById("root");
new ToggleButton($root, "button1", (clickCount) => {
  if (clickCount % 2 === 0) alert("짝수");
});
new ToggleButton($root, "button2", (clickCount) => {
  if (clickCount % 3 === 0) alert("3의배수");
});
new ToggleButton($root, "button3");

강의는 생성자함수를 사용했기에 다소 다른부분이 존재한다.


상태기반 추상화

위에 진행했던 예제들이 상태를 기반으로 한 추상화다.
모두 상태에 의존해서 진행하니 개발자는 상태관리만 잘하면 된다는 장점이 있다.
상태만 추적하면 변경사항을 알기도 쉽다.

물론 단점도 존재한다.
시스템의 규모가 커질수록 상태관리의 난이도가 올라간다.
=> OOP의 단점과 비슷하다. 하지만 장점이 크기에 오늘날 수많은 프레임워크(리액트, 뷰)에서 사용하는 거겠지.

오늘은 여까지!

profile
모르는 것을 모른다고 하기

0개의 댓글