Home TIL 10일차
Post
Cancel

TIL 10일차

명령형 프로그래밍(Imperative)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
const $button1 = document.createElement("button");
const $button2 = document.createElement("button");
const $button3 = document.createElement("button");

$button1.textContent = "Button1";
$button2.textContent = "Button2";
$button3.textContent = "Button3";

const $app = document.querySelector("#app");

$app.appendChild($button1);
$app.appendChild($button2);
$app.appendChild($button3);

$button1.addEventListener("click", () => {
  if ($button1.style.textDecoration === "line-through") {
    $button1.style.textDecoration = "none";
  } else {
    $button1.style.textDecoration = "line-through";
  }
});

$button2.addEventListener("click", () => {
  if ($button2.style.textDecoration === "line-through") {
    $button2.style.textDecoration = "none";
  } else {
    $button2.style.textDecoration = "line-through";
  }
});

$button3.addEventListener("click", () => {
  if ($button3.style.textDecoration === "line-through") {
    $button3.style.textDecoration = "none";
  } else {
    $button3.style.textDecoration = "line-through";
  }
});
  • 명령형 프로그램은 컴퓨터가 수행할 명령들을 순서대로 써 놓은 것이다.
  • 어떻게 구현하는 가를 디테일하게 기술하는 것에 관점이 가 있다.

선언형 프로그래밍(Declearative)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function Button({ $target, text }) {
  const $button = document.createElement("button");
  $target.appendChild($button);

  this.render = () => {
    $button.textContent = text;

    $button.addEventListener("click", () => {
      $button.style.textDecoration =
        $button.style.textDecoration === "line-throgh"
          ? "none"
          : "line-through";
    });
  };

  this.render();
}

new Button({ $target: $app, text: "선언 버튼1" });
new Button({ $target: $app, text: "선언 버튼2" });
new Button({ $target: $app, text: "선언 버튼3" });
  • 무엇을 나타내는가에 중점을 가지고 작성함
  • 코드 가독성, 확장성 증가
  • ex) HTML, query

위의 코드는 명령형 프로그래밍과 선언형 프로그래밍을 다룬 예제 코드이다. 명령형 프로그래밍은 버튼을 하나하나 직접 생성하여 작성했다. 하지만 선언형 프로그래밍은 버튼 생성을 추상화를 통해 필요할 때 생성하게 작성했다. 나는 명령형 프로그래밍은 코드를 차근차근 해석하면서 풀이하면 되지만, 선언형은 추상화를 통해 의미를 알아야 된다고 느꼈다.

선언형 프로그래밍이 추상화를 통해 일일이 작성할 필요가 없어 코드의 길이도 짧아지고 가독성이 좋지만, 코드를 작성할 때 명령형 프로그래밍 식으로 떠올라 작성이 어려운 것은 어쩔 수가 없는 거 같다. 그래서 오늘 공부할 때 명령형으로 먼저 작성하고 이후 선언형으로 짜보는 연습을 하면서 익숙해지도록 노력할 것이다.

-- Missing configuration options! --

This

3주차 회고