처음 코딩을 공부했을때 이 개념 이해가 힘들었다.
Declartive(선언형) Imperative(명령형)의 차이는 나같은 newbie한테는 더더욱 그럴지도...
그러다 영문 아티클을 찾는도중 medium에서 이해하기 쉽게 설명해주는 아티클을 찾았는데 여기다 기록을 해서 미래에 헷갈리면 다시 방문할 리소스.
The below Ian Mundy's article on Medium was great at explainning the concepts between imperative and declarative programming styles in a nutshell.
https://codeburst.io/declarative-vs-imperative-programming-a8a7c93d9ad2
Also this article by Myung Kim
https://medium.com/@myung.kim287/declarative-vs-imperative-251ce99c6c44
Declarative programming is a programming paradigm … that expresses the logic of a computation without describing its control flow.
Imperative programming is a programming paradigm that uses statements that change a program’s state.
First off, from a very high level, declarative programming focuses on the WHAT rather than the HOW.
code examples of Imperrative below:
const container = document.getElementById(‘container’);
const btn = document.createElement(‘button’);
btn.className = ‘btn red’;
btn.onclick = function(event) {
if (this.classList.contains(‘red’)) {
this.classList.remove(‘red’);
this.classList.add(‘blue’);
} else {
this.classList.remove(‘blue’);
this.classList.add(‘red’);
}
};
container.appendChild(btn);
code examples of Declarative below:
//Functional component is also valid example within the context of demonstrating declarative programming.
class Button extends React.Component{
this.state = { color: 'red' }
handleChange = () => {
const color = this.state.color === 'red' ? 'blue' : 'red';
this.setState({ color });
}
render() {
return (<div>
<button
className=`btn ${this.state.color}`
onClick={this.handleChange}>
</button>
</div>);
}
}
The differences here may be subtle. We still have logic that says if red then blue, but there’s one huge difference. The React example never actually touches an element. it simply declares an element should be rendered given our current state. It does not actually manipulate the DOM itself.
첫번째 명령형 코드 예문과 달리 리액트 예시에선 DOM을 직접적으로 접근하지 않으면서 주어진 state 상태에 따라 엘레멘트를 렌더링 하고 있습니다. 반면, 첫번째 예문에선 직접적으로 DOM 이벤트 API안에 conditional을 쓰면서 렌더링 하고 있죠.
React TIP: When writing React, it’s often good not to think of how you want to accomplish a result, but instead what the component should look like in it’s new state. This sets us up for a good control flow where state goes through a series of predictable and replicable mutations. This doesn’t just apply to components either, but also to application state. Libraries like Redux will help enforce this method of architecting, but they aren’t necessary to achieve it.