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