命令的と宣言的を理解するためのシンプルな例
命令的
code:py
d = {}
print(d)
# => {'orange': 45, 'apple': 100}
dを空で作ってその後に、d['apple'] = 100のように操作して値を増やしていく。
宣言的
code:py
d = {
'apple': 100,
'orange': 45,
}
print(d)
# => {'ornage': 45, 'apple': 100}
dはapple: 100でorange: 45と定義する。
命令的なUIの構築
code:js
const body = document.body;
const h1 = document.createElement('h1');
h1.innerText = 'hello!';
body.appendChild(h1);
宣言的なUIの構築
code:html
<body>
<h1>hello!</h1>
</body>
おまけ
ちょっとおまけ。
JavaScriptで宣言的なUIを作るシンプルな例
code:js
function e(tag, attrs={}, children=[]){
const el = document.createElement(tag);
el.setAttribute(name, value);
}
for (c of children) {
if (typeof c === 'string') c = document.createTextNode(c);
el.appendChild(c);
}
return el;
}
以下のように宣言的にUIを簡単に構築できる。
code:js
document.body.appendChild(
e('div', {}, [
e('ul', {style: 'list-style-type: circle'}, [
]),
])
);
デモ:
https://gyazo.com/342fda46d55c9c77781523379eb7d1ba
const text = document.createTextNode.bind(document)としてtext('hello!')のようにして要素を作るようすれば一貫性があってifを消せるけど使い勝手的にこれを選んだ。
これを命令的に書くと、DOMの入れ子構造が読み取りづらく保守しづらいことが容易に想像がつく。 Javaで頑張って宣言的にHashMapを定義する
以下の書き方も命令的なのだけど頑張って標準にあるものだけで宣言的に書こうとする例だと思っている。 宣言的に各用のラッパーを作っていないところがポイント。
{{になっているところもポイント。
最初の{は匿名クラスで、次の{は確かイニシャライザと読んだはず。
code:java
HashMap<String, Integer> myMap = new HashMap<String, Integer>() {{
put("apple", 100);
put("orange", 45);
}};
new HashMap()して後に空に向かってmyMap.put()するより、こういう書き方の方が好きなタイプ。