<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[codewey - Medium]]></title>
        <description><![CDATA[Programming Articles in Indonesian - Medium]]></description>
        <link>https://medium.com/codewey?source=rss----c57339f9150d---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>codewey - Medium</title>
            <link>https://medium.com/codewey?source=rss----c57339f9150d---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 11:21:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/codewey" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Reducer dengan Side Effects. Emang Bisa?]]></title>
            <link>https://medium.com/codewey/reducer-dengan-side-effects-emang-bisa-36c751050202?source=rss----c57339f9150d---4</link>
            <guid isPermaLink="false">https://medium.com/p/36c751050202</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[bahasa-indonesia]]></category>
            <dc:creator><![CDATA[Jihad Dzikri Waspada]]></dc:creator>
            <pubDate>Sat, 18 May 2019 00:07:11 GMT</pubDate>
            <atom:updated>2019-05-18T00:16:10.272Z</atom:updated>
            <content:encoded><![CDATA[<h4>Dibisain aja lah!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EDTJ6JiLIyut1QkxtpMphw.jpeg" /><figcaption>Launch rocket as a side-effect (<a href="https://wallpapertag.com/rocket-wallpaper">source</a>)</figcaption></figure><p>Temen-temen di sini pasti sudah paham lah ya konsep reducer: sebuah <em>pure function</em> untuk mengolah state atau sebagian state aplikasi kita. Saya pribadi sangat menyukai konsep reducer ini karena komputasi state aplikasi kita dilakukan di satu tempat saja. Pun sifatnya yang <em>pure</em>, tidak ada <em>side-effects </em>(i.e HTTP request, logging, IO, dll), agar menjamin state kita tetap <em>predictable</em> dan <em>deterministic</em>. Apalagi beberapa saat yang lalu React meluncurkan fitur React Hooks, dimana salah satu diantaranya adalah useReducer yang memungkinkan penggunaan reducer di scope component saja.</p><p>Nah karena sifat reducer yang <em>pure</em>, kita “harus” menggunakan beberapa library tambahan untuk melakukan <em>side-effects</em> seperti <a href="https://github.com/reduxjs/redux-thunk">redux-thunk</a>, <a href="https://github.com/redux-saga/redux-saga">redux-saga</a>, <a href="https://redux-observable.js.org/">redux-observable</a>, dll. Tapi jujur aja, selama kurang lebih 3 taun saya makek konsep reducer ini, gak jarang juga saya ngedumel dan berharap bisa melakukan <em>side-effects</em> langsung di dalam reducer. Biar gampang aja gitu. Soalnya kadang-kadang agak males dengan ceremony-nya redux: musti bikin action creator, reducer, mapStateToProps, mapDispatchToProps, dll 🤯</p><p>Ditambah lagi kalo mau make hooks useReducer yang memang mainannya di level component, sedangkan library-library yang disebutkan tadi biasanya main di level global. Terus kalo effect yang mau dijalanin itu receh, ngelakuin ceremony redux berasa <em>overkill</em> dan berdosa aja gitu.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FSDogLD4FOZMM8%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FSDogLD4FOZMM8%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FSDogLD4FOZMM8%2F200.gif&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/40aadcaeaf5af56bb411677826bd89c3/href">https://medium.com/media/40aadcaeaf5af56bb411677826bd89c3/href</a></iframe><blockquote>Pertanyaannya: ada cara yang simple gak sih?</blockquote><h3>📖 Case Study</h3><p>Yang gampang aja ya case study-nya: kita mau buat aplikasi counter biasa, yang bisa <em>increment</em> ama <em>decrement</em> gitu. Tapi dengan syarat, nilai counter-nya gak boleh dibawah 0. Jika tetep di-<em>decrement</em>, maka kita mau ngelakuin <em>side-effect</em> berupa tampilan alert dengan message: “GAK BOLEH DI BAWAH 0 BGSD!” Ups maap ngegas 🤭</p><p>Untuk increment sama decrement-nya pasti gampang lah ya, udah banyak contohnya jugak:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56517665eea67a5fa1c75f5fa6c4a59b/href">https://medium.com/media/56517665eea67a5fa1c75f5fa6c4a59b/href</a></iframe><p><em>All is well</em>. Sekarang tinggal kita handle <em>side-effect</em>-nya deh di component. React Hooks menyediakan fungsi useEffect untuk melakukan, ummm, <em>side-effects</em> di component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee385da43ddb9673fc6a47953537642d/href">https://medium.com/media/ee385da43ddb9673fc6a47953537642d/href</a></iframe><h3>⚠️ Problem is..</h3><p>Masalah-nya pada pendekatan di atas adalah state kita <em>leak</em>. “Bocor bocor bocor!” Kata salah satu tokoh besar di negeri kita. <em>Leak</em>-nya adalah ketika kita membiarkan counter bernilai -1 dan komponen mengetahui-nya terus buru-buru “mengkoreksi” dengan dispatch(‘INCREMENT’). <em>Not good at all</em>.</p><p>Pendekatan yang benar adalah kita harus <strong>meng-en-kap-su-la-si</strong> state kita di dalam reducer itu sendiri <strong>sehingga state yang keluar dari reducer itu hanyalah state yang valid saja</strong>. Kita harus mencegah invalid state. <em>Invalidate the invalids</em>. Kayak di salah satu artikel saya ini 👇🏻</p><p><a href="https://medium.com/codewey/tentang-loading-state-886dbb1cfe8d">Tentang Loading State…</a></p><p>Jadi solusinya? Kita ubah sedikit reducernya menjadi</p><pre>...</pre><pre>if (action.type === &#39;DECREMENT&#39;) {<br>  <strong>if (state === 0) return state;</strong><br>  return state - 1;<br>}</pre><pre>...</pre><p>Dengan begini counter kita gak akan pernah bisa di bawah 0. Udah gak bocor lagi 😉.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FJGunlb6LbQlz2%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FJGunlb6LbQlz2%2Fgiphy-downsized.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FJGunlb6LbQlz2%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/064047d318f1a2a712eff7829ca12773/href">https://medium.com/media/064047d318f1a2a712eff7829ca12773/href</a></iframe><p>Terus component-nya?</p><pre>...</pre><pre>React.useEffect(() =&gt; {<br>  <strong>if (??????) {<br>    alert(&#39;...&#39;)<br>  }</strong><br>}, [state]);</pre><pre>...</pre><p>Dhuaar! Bingung dah lu. Gimaana caranya kita nge-detect user lagi mencet tombol DECREMENT sedangkan state kita 0? Kita cuman punya dispatch(‘DECREMENT’) yang dikirim dari component ke reducer. Andaikata aja action ini bisa ditangkep di dalam useEffect macam</p><pre>if (action === &#39;DECREMENT&#39;) ...</pre><p>mungkin bakalan lebih gampang 🤔.</p><p>Atau mungkin kalo dipikir-pikir, kita bisa aja bikin <em>work-around</em> dan gak make useEffect:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3290fb6b14a3350862d30efe3fbc2ecf/href">https://medium.com/media/3290fb6b14a3350862d30efe3fbc2ecf/href</a></iframe><p>Cuman ya gitu, masak di component kita musti cek logic lagi if (state === 0) .. sedangkan logic yang sama baru aja kita implementasikan di reducer. Solusi ini pun berpotensi terjadinya state leak juga. <em>Duplicated logic. Smelly code</em>.</p><p>Mungkin yang kita butuhkan adalah: <strong>“sesuatu” yang dikirim dari reducer ke component sehingga component tau kapan harus melakukan side-effect</strong>.</p><h3>🌟 Solution</h3><p>Entah ini beneran solusi atau <em>another work-around</em>, tapi cara ini cukup efektif dan simple menurut saya pribadi: kita ubah “<strong>state</strong>” di reducer menjadi “<strong>state dan effect</strong>”.</p><p>Maksudnya? Kita akan pake struktur data Tuple yang berisi state dan effect. Di Javascript, tuple ini bisa direpresentasikan dengan array [state, effect]. Kemudian dengan menggunakan teknik <em>array destructuring</em>, reducer kita kurang lebih akan berubah menjadi</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/551fc0b682b8b410a5fe405efc838c90/href">https://medium.com/media/551fc0b682b8b410a5fe405efc838c90/href</a></iframe><p>Dan di component pun bisa dengan mudah mendeteksi perubahan state dan sinyal untuk melakukan <em>side-effect</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc755a9fb7b43394a6f420da29c82d31/href">https://medium.com/media/fc755a9fb7b43394a6f420da29c82d31/href</a></iframe><p>Dengan pendekatan seperti ini, reducer kita bisa menkontrol baik state maupun effect sekaligus. Dengan catatan effect yang dihasilkan dari reducer ini tetap bersifat pure: <strong>ia hanya berupa deskripsi side-effect, mirip-mirip kayak action creator</strong>. Kalau action creator itu dikirim dari component ke reducer, effect yang ini dikirim dari reducer ke component. Dan yang paling penting: state kita gak bocor ke component! Yeaa 🎉</p><p>Singkat kata, <em>type signature</em> reducer yang awalnya (state, actions) =&gt; state sedikit berubah menjadi ([state, effect], action) =&gt; [state, effect]. <em>In fact</em>, filosofi <em>side-effect</em> sebagai deskripsi/<em>messages</em> ini ternyata menjadi ide utama dari library <a href="https://redux-loop.js.org/">redux-loop</a>. Sebagaimana dinyatakan di dokumentasinya:</p><blockquote>The values returned from the reducer when scheduling an effect with redux-loop only “describe”<em> </em>the effect</blockquote><p>Kalau mau contoh yang agak real world, saya sudah siapkan repo yang simple:</p><p><a href="https://github.com/dewey92/playlist">dewey92/playlist</a></p><p>beserta “effectful reducer”-nya <a href="https://github.com/dewey92/playlist/blob/master/src/usePlaylistReducer.ts">dimari</a>.</p><p><em>If you find this article useful, don’t hesitate to hit the clap button so that your friends could know this story.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F14cilFdQzr8hG0%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F14cilFdQzr8hG0%2Fgiphy.mp4&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F14cilFdQzr8hG0%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/21015ef08c5d5eb0780efa247c993030/href">https://medium.com/media/21015ef08c5d5eb0780efa247c993030/href</a></iframe><p>Semoga bermanfaat 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36c751050202" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codewey/reducer-dengan-side-effects-emang-bisa-36c751050202">Reducer dengan Side Effects. Emang Bisa?</a> was originally published in <a href="https://medium.com/codewey">codewey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kuy Ngobrol Dikit Soal Generics]]></title>
            <link>https://medium.com/codewey/kuy-ngobrol-dikit-soal-generics-4a05f60d5be1?source=rss----c57339f9150d---4</link>
            <guid isPermaLink="false">https://medium.com/p/4a05f60d5be1</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[bahasa-indonesia]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Jihad Dzikri Waspada]]></dc:creator>
            <pubDate>Wed, 08 May 2019 21:33:01 GMT</pubDate>
            <atom:updated>2019-07-21T22:57:26.999Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using Typescript for simplicity</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WaWswm_G9NXmy1d-H1fmIA.jpeg" /><figcaption>A hole to fill in (<a href="https://www.pixelstalk.net/wp-content/uploads/2016/08/Black-Hole-Picture-Download-Free.jpg">source</a>)</figcaption></figure><p><em>Reusability</em> adalah komponen yang sangat penting dalam membangun sebuah software. Dengan <em>code reuse</em>, LoC (<em>lines of code</em>) dapat dikurangi sehingga maintainance aplikasi jadi relatif lebih gampang.</p><blockquote>Less code == Less bugs</blockquote><p>Salah satu cara untuk mencapai <em>reusability</em> adalah dengan menggunakan konsep Generics. Beberapa bahasa pemrograman seperti Typescript, Java, C++, OCaml, ReasonML, Purescript, dan Haskell, memeliki konsep Generics. Generics memungkinkan kita untuk membuat function atau <em>data structure</em> yang gak kaku sama satu tipe data aja, melainkan dengan tipe data apapun dia ayok-ayok aja: a.k.a terserah yang manggil. Tentunya bisa dibatasi dengan <strong>constraints</strong> (akan dibahas nanti).</p><p>Oh iya, konsep Generics ini hanya berguna jika kita menggunakan <em>statically-typed language</em>. Oleh karenanya membahas Generics dengan Javascript tidaklah relevan karena Javascript tidak memiliki <em>type system</em>.</p><h3>✈️ Let’s Start with Function</h3><p>Ketika bicara Generics, contoh yang paling gampang adalah dengan menggunakan <em>identity function</em>: sebuah unary function (memiliki 1 argument) yang langsung mengembalikan argument-nya:</p><pre><strong>const</strong> id = x =&gt; x</pre><pre>id(1)       === 1<br>id(&#39;jihad&#39;) === &#39;jihad&#39;<br>id([1,2])   === [1,2]<br>// etc</pre><p>Tanpa Generics, kita musti overload atau bahkan redefine function ini dengan semua macam tipe yang ada di muka bumi.</p><pre><strong>const</strong> idNumber = (x: <strong>number</strong>): <strong>number</strong> =&gt; x<br><strong>const</strong> idString = (x: <strong>string</strong>): <strong>string</strong> =&gt; x<br>...</pre><p>ini belum termasuk overloading untuk array, object, function, atau bahkan <em>data structure</em> kita sendiri.</p><p>Dengan Generics, semua jadi jauh lebih mudah:</p><pre><strong>const</strong> id = &lt;<strong>T</strong>&gt;(x: <strong>T</strong>): <strong>T</strong> =&gt; x</pre><p>Maksudnya: <strong>id menerima variable </strong><strong>x yang memiliki tipe </strong><strong>T, dan mengembalikan tipe </strong><strong>T</strong>. Ketika T disubstitusi dengan number, maka bunyinya jadi: <strong>id menerima variable </strong><strong>x yang memiliki tipe </strong><strong>number, dan mengembalikan tipe </strong><strong>number</strong>. Begitupun seterusnya dengan string, array, dll.</p><pre>id&lt;<strong>number</strong>&gt;(1)       === 1<br>id&lt;<strong>string</strong>&gt;(&#39;jihad&#39;) === &#39;jihad&#39;</pre><pre>id&lt;<strong>number</strong>&gt;(&#39;jihad&#39;) // error</pre><p>Typecheck! Oh iya, satu lagi, jika diperhatikan, tipe T muncul di 3 tempat pada definisi identity function yang kita buat:</p><pre><strong>const</strong> id = &lt;<strong>T</strong>&gt;(x: <strong>T</strong>): <strong>T</strong> =&gt; x<br>            ^     ^   ^<br>            1     2   3</pre><p>Ketika menjalankan id(‘jihad’), <em>type inference</em> bilang bahwa ‘jihad’ bertipe string. Dengan kata lain, T pada posisi kedua sekarang bisa diisi dengan string. Karena salah satu T sudah diketahui bernilai string, maka semua T bisa disubstitusi dengan string sehinnga kita gak perlu lagi menggunakan &lt;&gt; untuk <em>type assertion</em>. <em>Type can be inferred from anywhere</em>.</p><pre><strong>typeof</strong> id(&#39;string&#39;) === &#39;string&#39;<br><strong>typeof</strong> id(1)        === &#39;number&#39;</pre><h3>🔗 Generic Data Structure</h3><p>Sampai di sini kita udah tau gimana caranya buat function yang <em>polymorphic</em> pakek konsep Generics. Sebenernya gak cuman function, kita juga bisa buat <em>data structure</em> kita sendiri generics juga: misal pas kita mau bikin sebuah “template” data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbdbb17ee54bb80189566831e477d0c5/href">https://medium.com/media/fbdbb17ee54bb80189566831e477d0c5/href</a></iframe><p>Baik createRemoteData maupun RemoteData, keduanya generic. Gak usah jauh-jauh, <em>data structure</em> dasar kayak Array di TS juga syudah generic. Kita bisa buat array of integers, array of string, array of arrays, array of objects, dll</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1dd41ef79d04f0c8ac21f227b7889822/href">https://medium.com/media/1dd41ef79d04f0c8ac21f227b7889822/href</a></iframe><p>Pun yang agak kompleks kayak struktur data Tree:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10dab102a4fa2688649bc83a0b32a1fe/href">https://medium.com/media/10dab102a4fa2688649bc83a0b32a1fe/href</a></iframe><h3>🚧 Constraints</h3><p><em>Generics is cool</em>. Sampai suatu saat, kita sadar bahwa dalam beberapa kasus kita juga ingin <strong>membatasi</strong> tipe data apa saja yang boleh digunakan. Misal seperti sebuah function generics yang mengembalikan semua key dari suatu object.</p><pre><strong>const</strong> keys = &lt;T&gt;(obj: T) =&gt; Object.keys(obj)</pre><p>Ada satu masalah di sini: T tidak boleh bernilai null atau undefined. Malah kalau dipikir-pikir, kita hanya ingin T ini bertipe object.</p><pre>Object.keys(null)<br>// Uncaught TypeError: Cannot convert undefined or null to object</pre><p>Gimana solusinya? Di Typescript, kita harus menggunakan keyword extends.</p><pre>const keys = &lt;T <strong>extends {}</strong>&gt;(obj: T) =&gt; Object.keys(obj)</pre><p>Di sini compiler akan bilang: <strong>saya gak mau tau apa itu </strong><strong>T, asalkan dia bentuknya object, saya terima</strong>. Saya juga gak peduli apapun <em>key </em>dan <em>value</em>-nya. Seng penting object.</p><pre>keys({}) === []<br>keys({ id: 1 }) === [&#39;id&#39;]</pre><pre>keys(1) // error</pre><p><em>Easy peasy</em> 🎉</p><h3>Kesimpulan</h3><p>Konsep Generics dalam bahasa pemrograman sangat sangat membantu kita untuk <em>achieve reusability</em>. Dengan Generics pula, kita bisa dengan mudah membuat <em>function</em> dan <em>data structure</em> yang <em>polymorphic</em>: bisa nerima berbagai macam tipe data.</p><p>Namun ada pertanyaan besar: <strong>“Kan katanya <em>generics</em> bisa nerima tipe data apa aja, bisa gak <em>generics</em> nerima <em>generics</em> lain?”</strong>.<strong> </strong>Semacam <em>Higher-Order Generics</em> gitu 🤔</p><p>Maksudnya kek gimana Pak Jihad? Kek gini:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/571315e56b68a5ca864ef4bf571cfc47/href">https://medium.com/media/571315e56b68a5ca864ef4bf571cfc47/href</a></iframe><p>Fungsi map punya 3 buah <em>type variable</em>: F, A, dan B. Di argument kedua, thing memiliki tipe F&lt;A&gt;, dan fungsi map ini mengembalikan tipe F&lt;B&gt;. Di sini F seolah-olah berperan sebagai suatu struktur data yang menerima <em>type variable</em>, mirip Array dan Tree di atas. Harapannya sih dengan fungsi ini saya bener-bener bisa substitusi F dengan Array maupun Tree, dan A atau B dengan <em>primitive types</em> seperti number dan string.</p><p>Kira-kira bisa gak ya? Kalau iya apa keuntungannya? Simak artikel berikut kalau mau tau lebih lanjut 😉</p><p><a href="https://www.jihadwaspada.com/post/generic-di-atas-generic-higher-kinded-type/">https://www.jihadwaspada.com/post/generic-di-atas-generic-higher-kinded-type/</a></p><p>Terima kasih semoga bermanfaat 🙂</p><p><em>If you find this article useful, don’t hesitate to hit the clap button so that your friends could know this story.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F14cilFdQzr8hG0%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F14cilFdQzr8hG0%2Fgiphy.mp4&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F14cilFdQzr8hG0%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/21015ef08c5d5eb0780efa247c993030/href">https://medium.com/media/21015ef08c5d5eb0780efa247c993030/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a05f60d5be1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codewey/kuy-ngobrol-dikit-soal-generics-4a05f60d5be1">Kuy Ngobrol Dikit Soal Generics</a> was originally published in <a href="https://medium.com/codewey">codewey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Subtype Polymorphism vs Algebraic Data Types (ADT)]]></title>
            <link>https://medium.com/codewey/subtype-polymorphism-vs-algebraic-data-types-adt-94a0f186b8d1?source=rss----c57339f9150d---4</link>
            <guid isPermaLink="false">https://medium.com/p/94a0f186b8d1</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[bahasa-indonesia]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Jihad Dzikri Waspada]]></dc:creator>
            <pubDate>Thu, 02 May 2019 19:08:46 GMT</pubDate>
            <atom:updated>2019-05-03T00:25:16.395Z</atom:updated>
            <content:encoded><![CDATA[<h4>Pendekatan Polymorphism dalam Object-Oriented Programming dan Functional Programming</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l0mEHXvJU6KLZBH9mMrSJg.jpeg" /><figcaption>Many variants (<a href="http://ognature.com/park-tulip-flowers-garden-tulips-bed-wallpaper-flower-hd/tulip-bed-park-garden-tulips-flowers-rose-flower-hd-live-wallpaper/">source</a>)</figcaption></figure><p>Inspirasi artikel ini saya dapatkan dari tulisan ringkas Reid Evans. Bisa dibaca <a href="https://medium.com/@reidev275/expression-problem-related-to-oo-and-fp-aef063bb96f6">di sini</a>. Artikel saya ini bisa dibilang terjemahan dari artikel tersebut dengan beberapa poin tambahan (di bawah section “Kesimpulan”) 😆🙏🏻</p><p>Kita mulai dari <em>Polymorphism </em>dulu.</p><h3>🌈 Polymorphism</h3><p>Dalam dunia OOP, <em>polymorphism</em> lumrahnya me-<em>refer</em> ke istilah <strong>Subtype Polymorphism</strong> dimana suatu data (bisa <em>interface</em> atau <em>parent class</em>) mempunyai beberapa “variant” (yang umum disebut <em>child classes</em>).</p><p>Ketika kita bicara tentang “Shape”, beberapa <em>variant </em>di antaranya bisa berupa “Rectangle” atau “Triangle”. Di Typescript, kita bisa menuliskannya dengan gaya OOP seperti ini:</p><pre><strong>interface</strong> Shape {}</pre><pre><strong>class</strong> Rectangle <strong>implements</strong> Shape {}<br><strong>class</strong> Triangle <strong>implements</strong> Shape {}</pre><p>Simpel. Namun dalam paradigma Functional Programming, alih-alih mengandalkan teknik <em>subtyping</em> seperti ini, kita bisa mengekspresikannya dengan suatu konsep yang bernama Algebraic Data Types (ADT). Kayak gimana tuh?</p><p>Kek gini (dalam Haskell):</p><pre><strong>data</strong> Shape = Rectangle | Triangle</pre><p>Terlihat lebih singkat dan <em>straightforward</em>. Namun kita coba telusuri dulu lebih lanjut perbandingan dari kedua pendekatan di atas dari beberapa sisi.</p><p>Code di atas kayak gak ada gunanya karena kita cuma men-<em>define</em> datanya saja: masih kopong, belum ada <em>behaviour</em>-nya. Kita coba kasih dua buah <em>behaviour</em>: display, dan getSides.</p><h4>OOP</h4><pre><strong>interface</strong> Shape {<br>  display: () =&gt; string;<br>  getSides: () =&gt; number;<br>}</pre><pre><strong>class</strong> Rectangle <strong>implements</strong> Shape {<br>  display = () =&gt; &quot;I&#39;m a Rectangle&quot;<br>  getSides = () =&gt; 4<br>}</pre><pre><strong>class</strong> Triangle <strong>implements</strong> Shape {<br>  display = () =&gt; &quot;I&#39;m a Triangle&quot;<br>  getSides = () =&gt; 3<br>}</pre><p>Bagaimana kalau di FP?</p><h4>FP</h4><p>Kalau pake cara FP (<em>at least</em> di Haskell), kita bisa menggunakan teknik <em>pattern-matching</em> di function-nya. Semua <em>inhabitants</em> (dalam hal ini Rectangle dan Triangle) harus muncul.</p><pre><strong>data</strong> Shape = Rectangle | Triangle</pre><pre>display :: Shape -&gt; String<br>display Rectangle = &quot;I&#39;m a Rectangle&quot;<br>display Triangle = &quot;I&#39;m a Triangle&quot;</pre><pre>getSides :: Shape -&gt; Number<br>getSides Rectangle = 4<br>getSides Triangle = 3</pre><h3>Adding Variants 🎨</h3><p>Bagaimana kalau sekarang kita tambah <em>variant</em> Shape-nya? Misal kita tambah Circle. Di OOP, kita hanya perlu membuat class baru tanpa mengubah code baik di Shape, Rectangle, atau Triangle.</p><pre>...</pre><pre><strong>class</strong> Circle <strong>implements</strong> Shape {<br>  display = () =&gt; &quot;I&#39;m a Circle&quot;<br>  getSides = () =&gt; 1<br>}</pre><p>Sebaliknya, di dunia FP kita perlu sedikit refactor, karena semua <em>inhabitants</em> harus muncul di fungsi-fungsi tersebut agar pattern-matching nya bersifat <em>exhaustive</em>.</p><pre><strong>data</strong> Shape = Rectangle | Triangle | <strong>Circle</strong></pre><pre>display :: Shape -&gt; String<br>display Rectangle = &quot;I&#39;m a Rectangle&quot;<br>display Triangle = &quot;I&#39;m a Triangle&quot;<br><strong>display Circle = &quot;I&#39;m a Circle&quot;</strong></pre><pre>getSides :: Shape -&gt; Number<br>getSides Rectangle = 4<br>getSides Triangle = 3<br><strong>getSides Circle = 1</strong></pre><p>Nah dalam hal ini, pendekatan OOP terlihat lebih mudah karena kita tidak perlu melakukan refactor dan bisa membuat “variant” sebanyak yang kita mau.</p><h3>Adding Behaviours 🚶🏻‍♂️</h3><p>Sekarang kita coba lihat dari sisi lain: gimana kalau kita tambah <em>behaviour</em>-nya lagi? Misal kita juga ingin tahu luas dari masing-masing Shape tersebut.</p><pre><strong>interface</strong> Shape {<br>  display: () =&gt; string;<br>  getSides: () =&gt; number;<br>  <strong>area: (length: number, height: number) =&gt; number;</strong><br>}</pre><pre><strong>class</strong> Rectangle <strong>implements</strong> Shape {<br>  display = () =&gt; &quot;I&#39;m a Rectangle&quot;<br>  getSides = () =&gt; 4<br>  <strong>area = (length, height) =&gt; length * height</strong><br>}</pre><pre><strong>class</strong> Triangle <strong>implements</strong> Shape {<br>  display = () =&gt; &quot;I&#39;m a Triangle&quot;<br>  getSides = () =&gt; 3<br>  <strong>area = (base, height) =&gt; base * height / 2</strong><br>}</pre><p>Nah sekarang gantian OOP yang perlu banyak refactor jika ada penambahan/perubahan <em>behaviour</em>. Emang sih, ada beberapa prinsip supaya meminimalisir perubahan pada <em>interface</em> kita, <a href="https://en.wikipedia.org/wiki/SOLID">SOLID principles</a> salah satunya. Tapi kita gak akan bahas itu karena <em>out of topic</em> 🙃</p><p>Sebaliknya, pendekatan FP tidak perlu mengubah ADT dan <em>function</em> yang sudah de-define: kita hanya perlu menambah function area.</p><pre>...</pre><pre>area :: Shape -&gt; Number -&gt; Number -&gt; Number<br>area Rectangle length height = length * height<br>area Triangle base height = base * height / 2</pre><h3>Kesimpulan</h3><p>Pendekatan OOP bisa lebih unggul jika kita sudah tau lebih dulu spesifikasinya (<em>interface</em>), tinggal buat aja <em>variant</em>-nya (<em>child classes</em>) sebanyak yang kita mau. Sedangkan FP lebih suka menggunakan Algebraic Data Types dimana jumlah <em>variant</em>-nya (<em>inhabitant</em>) sudah fix, tinggal menambahkan <em>behaviour</em>-nya (<em>function</em>) saja untuk masing-masing <em>inhabitant</em> tersebut. Dan kita bisa menambahkan <em>behaviour</em> sebanyak yang kita mau.</p><p>Pola ADT dalam FP ini bisa dengan mudah ditemukan pada beberapa <em>data structure</em> dasar:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1ed0e3686ba6a23634116887e341e1e/href">https://medium.com/media/b1ed0e3686ba6a23634116887e341e1e/href</a></iframe><h3>More on ADT</h3><p>Lho kan sudah kesimpulan? Hehe iya, namun masih ada beberapa hal yang ingin saya tambahkan terkait dengan ADT ini.</p><h4>Separation of Concern</h4><p>Kalau dilihat lebih dalam lagi, OOP dengan konsep <em>class</em>-nya menggabungkan dua konsep sekaligus: Data dan Behaviour.</p><pre><strong>class</strong> Rectangle <strong>implements</strong> Shape {<br>  display = () =&gt; &quot;I&#39;m a Rectangle&quot;<br>  getSides = () =&gt; 4<br>}</pre><p>Data-nya adalah Rectangle, <em>behaviour</em>-nya adalah display dan getSides. Keduanya digabungkan ke dalam satu <em>value</em> yang biasa kita kenal dengan istilah <strong>class</strong>.</p><p>Sedangkan dalam pendekatan FP, kedua konsep ini dipisah: data sendiri, behaviour sendiri.</p><pre>-- Data<br><strong>data</strong> Shape = Rectangle | Triangle</pre><pre>-- Behaviour<br>display :: Shape -&gt; String<br>display Rectangle = &quot;I&#39;m a Rectangle&quot;<br>display Triangle = &quot;I&#39;m a Triangle&quot;</pre><pre>getSides :: Shape -&gt; Number<br>getSides Rectangle = 4<br>getSides Triangle = 3</pre><h4>Autonomous</h4><p>Di contoh yang saya tulis pada <em>section</em> “Adding Behaviours”, saya tidak menyinggung penambahan <em>behaviour</em> area pada Circle. Kalaupun iya, saya sendiri pun bingung bagaimana harus mengimplementasikannya.</p><pre><strong>interface</strong> Shape {<br>  ...<br>  area: (length: number, height: number) =&gt; number;<br>}</pre><pre><strong>class</strong> Circle <strong>implements</strong> Shape {<br>  ...<br>  area = (length, height) =&gt; ???<br>}</pre><p>Kira-kira ada yang kurang tepat? Yes! Secara intuitif, lingkaran tidak memiliki attribute length dan height. Menurut saya, radius adalah <em>attribute</em> yang lebih tepat untuk menghitung luas lingkaran.</p><pre>area = (radius: number) =&gt; PI * radius * radius;</pre><p>Namun ada konsekuensi yang harus dibayar: dengan mengubah interface Shape. Diubah-pun akan membuat Rectangle dan Triangle tidak <em>compatible</em> lagi karena masing-masing punya caranya sendiri untuk menghitung luas. Syedih jadinya 😢</p><p>Untuk mengatasi masalah ini, variable-variable yang dibutuhkan untuk menghitung luas bisa dipindahkan ke <em>class constructor</em></p><pre><strong>interface</strong> Shape {<br>  ...<br>  <strong>area: () =&gt; number;</strong><br>}</pre><pre><strong>class</strong> Rectangle <strong>implements</strong> Shape {<br>  constructor(<strong>private</strong> length, <strong>private</strong> height) {}<br>  ...<br>  area = () =&gt; <strong>this</strong>.length * <strong>this</strong>.height<br>}</pre><pre>class Circle implements Shape {<br>  constructor(<strong>private</strong> radius) {}<br>  ...  <br>  area = () =&gt; PI * <strong>this</strong>.radius * <strong>this</strong>.radius<br>}</pre><p>Adapun di FP, <em>inhabitants</em> ADT <strong>bisa berupa apa saja</strong>, dan <em>behaviour</em>-nya (<em>function</em>) pun tinggal mengikuti bentuk masing-masing <em>inhabitant</em>-nya.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd04b6947213f7ee54dea4f5f9aa93f7/href">https://medium.com/media/cd04b6947213f7ee54dea4f5f9aa93f7/href</a></iframe><p>Pendapat saya pribadi, ADT dalam hal ini lebih fleksibel dan intuitif<em>. Pattern-matching to the rescue!</em> 😎</p><p><em>If you find this article useful, don’t hesitate to hit the clap button so that your friends could know this story.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F14cilFdQzr8hG0%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F14cilFdQzr8hG0%2Fgiphy.mp4&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F14cilFdQzr8hG0%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/21015ef08c5d5eb0780efa247c993030/href">https://medium.com/media/21015ef08c5d5eb0780efa247c993030/href</a></iframe><p>Semoga bermanfaat 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94a0f186b8d1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codewey/subtype-polymorphism-vs-algebraic-data-types-adt-94a0f186b8d1">Subtype Polymorphism vs Algebraic Data Types (ADT)</a> was originally published in <a href="https://medium.com/codewey">codewey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Programming: Mengenal Semigroup dan Monoid]]></title>
            <link>https://medium.com/codewey/functional-programming-mengenal-semigroup-dan-monoid-8c3a7d867197?source=rss----c57339f9150d---4</link>
            <guid isPermaLink="false">https://medium.com/p/8c3a7d867197</guid>
            <category><![CDATA[haskell]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jihad Dzikri Waspada]]></dc:creator>
            <pubDate>Thu, 04 Apr 2019 12:05:29 GMT</pubDate>
            <atom:updated>2019-04-04T12:26:54.926Z</atom:updated>
            <content:encoded><![CDATA[<h4>Abstraksi Penggabungan Dua Buah Tipe Data yang Sama</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uZ6pJ1OW2rRLSKv_Oa7fIQ.jpeg" /><figcaption><a href="https://www.freightrailreform.com/wp-content/uploads/2016/07/Rail-Switch.jpg">Source</a></figcaption></figure><p>Tulisan kali ini akan coba saya jelaskan dengan cepat. Sebelum memahami kedua konsep Semigroup dan Monoid, ada baiknya untuk memahami apa maksud dari <em>Identity</em>.</p><h3>Identity</h3><p>Identity merupakan suatu konsep yang, jika diaplikasikan dengan suatu value, akan langsung <strong>mengembalikan value itu sendiri</strong>.</p><pre><strong>const</strong> identity = x =&gt; x</pre><pre><strong>const</strong> five = 5<br>log(identity(five)) // =&gt; 5</pre><p><em>Sounds useless, right</em>?</p><h3>Semigroup</h3><p>Semigroup bisa diartikan dengan: suatu value yang bisa “disatukan” dengan value lain <strong>yang setipe</strong>. Bahasa OOP-nya: <em>Appendable</em>. Contoh paling mudah dipahami adalah penambahan dan perkalian angka, juga penggabungan pada String dan Array.</p><pre>&gt; 1 + 2 = 3</pre><pre>&gt; 6 * 7 = 42</pre><pre>&gt; &quot;gue elo &quot; + &quot;end&quot; == &quot;gue elo end&quot;</pre><pre>&gt; [1].concat([2]) == [1, 2]</pre><p>Terlihat pola yang serupa dari masing-masing contoh di atas dimana semua <em>operand</em> (1 dan 2 pada contoh pertama) dan hasil komputasi (3) memiliki tipe yang sama ⬇️</p><pre>(+) :: Num -&gt; Num -&gt; Num<br>(*) :: Num -&gt; Num -&gt; Num<br>(+) :: String -&gt; String -&gt; String<br>concat :: [a] -&gt; [a] -&gt; [a]</pre><p>Pada dasarnya, operasi <strong>penggabungan nilai</strong> pada Semigroup ini harus memenuhi 1 syarat saja, yaitu <em>Associativity</em>:</p><pre>&gt; (1 + 2) + 3 == 1 + (2 + 3)</pre><pre>&gt; (6 * 7) * 8 == 6 * (7 * 8)</pre><pre>&gt; (&quot;gue &quot; + &quot;elo &quot;) +  &quot;end&quot; == &quot;gue &quot; + (&quot;elo &quot; +  &quot;end&quot;)</pre><pre>&gt; <strong>([1].concat([2]))</strong>.concat([3]) == [1].concat<strong>([2].concat([3]))</strong></pre><h3>Monoid</h3><p>Rumus Monoid ⬇️</p><blockquote>Monoid = Semigroup + Identity</blockquote><p>Kita akan bahas segera maksud dari rumus ini</p><h4>Penambahan</h4><p>Pada operasi penambahan, nilai Identity-nya adalah 0. Mengapa demikian? <strong>Seperti yang telah dijelaskan di awal artikel, suatu value yang “diaplikasikan” dengan Identity hanya akan mengembalikan value tersebut kembali</strong>. Thus:</p><pre>1 + 0 = 1</pre><pre>atau</pre><pre>0 + 1 = 1</pre><p>Dengan demikian, tipe data Number<em> under addition</em> memiliki Identity 0 dan + sebagai operator Semigroup-nya.</p><p><em>Pseudocode</em>-nya bisa dituliskan seperti berikut:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/525d1a4486e754e0c8d3b71fd7dbdb8e/href">https://medium.com/media/525d1a4486e754e0c8d3b71fd7dbdb8e/href</a></iframe><h4>Perkalian</h4><p>Bisa ditebak kan, <em>under multiplication</em>, tipe data Number memliki Identity 1 karena semua angka yang dikalikan dengan 1 akan mengembalikan angka itu sendiri.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/450062dde32c22743dc913f60900aea0/href">https://medium.com/media/450062dde32c22743dc913f60900aea0/href</a></iframe><h4><strong>String</strong></h4><p>Tidak sebatas angka, tipe data String pun juga bisa memiliki instance Monoid karena bisa di-<em>append</em> dengan String lain dan memliki identity-nya.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d7e9d347570a46c0b1d06df2d43878e/href">https://medium.com/media/1d7e9d347570a46c0b1d06df2d43878e/href</a></iframe><h4>Boolean</h4><p>Boolean jugak? Iyes! <em>under operation</em> OR (<em>disjunction</em>) memliki identity false dan <em>under operation </em>AND (<em>conjunction</em>) memiliki identity true.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6e16b7fcf574bd5d7101838a65c7c9e/href">https://medium.com/media/b6e16b7fcf574bd5d7101838a65c7c9e/href</a></iframe><h4>Array</h4><p>Array juga demikian, ia memiliki Identity [] dan operator append untuk instance Semigroup-nya.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e091e5cdcb8720608be4e671f4390d08/href">https://medium.com/media/e091e5cdcb8720608be4e671f4390d08/href</a></iframe><p>Ada instance lain? Let’s try Object!</p><h4>Object</h4><p>Object di Javascript juga bisa memiliki instance Monoid-nya dengan {} sebagai nilai identity-nya dan Object.assign sebagai operator Semigroup-nya</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/450b276d147b4e283ebbc37d5bcba77b/href">https://medium.com/media/450b276d147b4e283ebbc37d5bcba77b/href</a></iframe><p>Masih banyak lagi sebenarnya tipe data tak-primitif yang bisa dijadikan instance Semigroup dan Monoid. Biar aku juga sekalian bisa belajar dari nulis artikel ini 😄🙏🏻</p><h4>CSS Color</h4><p>Untuk teknik color blending-nya, sebenarnya bebas aja mau kek gimana implementasinya. Tapi kita ambil contoh aja seperti yang didemonstrasikan di <a href="https://meyerweb.com/eric/tools/color-blend/#AAAAAA:4F22AC:1:hex">Meyerweb</a>.</p><p>Bagaimana untuk identity-nya? Bingo! Di CSS, value transparent is a valid color.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8dc1ba6eac27822ed4d7b0acf283f1b/href">https://medium.com/media/c8dc1ba6eac27822ed4d7b0acf283f1b/href</a></iframe><h4>JSX</h4><p>Kalau dipikir-pikir, JSX juga bisa masuk kategori Monoid karena semua HTML element dan React component kita bertipe JSX.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3d4a01a11c28b1347f65bda1cace3b9/href">https://medium.com/media/d3d4a01a11c28b1347f65bda1cace3b9/href</a></iframe><h4>Function</h4><p>Untuk operator identity-nya, saya kira sudah jelas juga bahwa identity function adalah const id = x =&gt; x. Nah untuk operasi Semigroup-nya ini yang agak menantang.</p><p>First rule, hasilnya harus berupa function juga, karena Semigroup bernotasi a -&gt; a -&gt; a.</p><p>Kedua, ketika kita ingin membuat sesuatu tipe data instance dari Semigroup, kita harus bisa membuktikan bahwa append(h, append(f, g))) dan append(append(h, f), g) akan membuahkan hasil yang sama (<strong>hukum Associativity di awal artikel</strong>)</p><p>Kayaknya pake fungsi compose bisa karena kan compose bersifat associative! Yuk dibuktikan dulu:</p><pre>// Andaikata<br>const f = x =&gt; x * 2<br>const g = y =&gt; y + 1<br>const h = z =&gt; String(z)</pre><pre>// Maka<br>// append(h, append(f, g)))<br>const _1 = compose(h, compose(f, g)))<br>log(_1(3)) // =&gt; &#39;8&#39;</pre><pre>// append(append(h, f), g)<br>const _2 = compose(compose(h, f), g)<br>log(_2(3)) // =&gt; &#39;8&#39;</pre><p>Wih masuk pak eko! 🎉 Untuk yang belum tahu apa itu compose</p><p><a href="https://medium.com/codewey/cleaner-code-dengan-function-composition-137f30d928e4">Cleaner Code dengan Function Composition</a></p><p>⚠️ Tapi tunggu dulu. Sekilas keliatan benar tapi ada sesuatu yang terlewatkan. Jika kita flashback pada contoh-contoh sebelumnya, operasi concat selalu berhasil jika argument pertama ditaruh di argument kedua dan sebaliknya (walaupun hasil akhirnya berbeda).</p><pre>// Addition<br>sumAddition.concat(1, 2) // works<br>sumAddition.concat(2, 1) // works</pre><pre>// Array<br>array.concat([1], [2]) // works<br>array.concat([2], [1]) // works</pre><pre>// CSS Colour (See the implementation! ⬆️)<br>cssColour.concat(&#39;transparent&#39;, &#39;#aaa&#39;) // works<br>cssColour.concat(&#39;#aaa&#39;, &#39;transparent&#39;) // works</pre><p>Tapi untuk <em>function composition</em> ini <strong>gak selamanya benar</strong>. Suppose:</p><pre>// length :: [a] -&gt; Int<br>const length = xs =&gt; xs.length</pre><pre>// toUpper :: String -&gt; String<br>const toUpper = str =&gt; str.toUpperCase()</pre><pre>funcMonoid.concat(length, toUpper)(&#39;Jihad&#39;) // works, 5<br>funcMonoid.concat(toUpper, length)(&#39;Jihad&#39;) // error!<br><strong>// Uncaught TypeError: str.toUpperCase is not a function</strong></pre><p>So gimana? 🤔</p><p>Dari fakta ini, kita bisa menarik kesimpulan bahwa instance Monoid untuk Function hanya berlaku untuk function yang <em>endomorphic</em>. <strong>Endomorphism adalah suatu fungsi yang tipe argument dan return value-nya sama</strong>.</p><pre>endoFunc :: a -&gt; a</pre><p>Dengan ini kita bisa menjamin bahwa <em>function composition</em> tersebut akan selalu berhasil saat runtime.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d98ad96d1909821d4933337397c7759/href">https://medium.com/media/7d98ad96d1909821d4933337397c7759/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ca3349c8d379524b7359e03edcef8a3/href">https://medium.com/media/2ca3349c8d379524b7359e03edcef8a3/href</a></iframe><p>Dan untuk function yang tidak <em>endomorphic</em>, kita tetap bisa membuat instance Monoid-nya, namun dengan syarat <strong>return value dari function tersebut harus memiliki instance dari Monoid juga</strong>. Syarat berikutnya, <strong>kedua function tersebut harus memiliki tipe yang sama</strong>. Pada contoh di bawah ini, kedua function-nya memiliki tipe Int -&gt; String.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff598643229a6450632dcd398be506d8/href">https://medium.com/media/ff598643229a6450632dcd398be506d8/href</a></iframe><h3>Kegunaan</h3><p>Kalau saya pribadi, saya nggak melihat keuntungan menggunakan Monoid di Javascript mainly karena ekosistem JS yang gak tepat aja: bukan <em>statically-typed language</em>. Kalaupun bahasa tersebut <em>statically-typed</em> (think of Typescript, Kotlin, Java) tetep belum tentu bisa menerapkan Monoid se-simple Haskell atau Purescript.</p><p>Tapi kalau temen-temen mau liat kegunaan umum Monoid ini (dan lihat betapa verbose-nya jika digunakaan di bahasa selain Haskell/Purescript), bisa mampir ke link-link di bawah ini:</p><ol><li><a href="https://dev.to/gcanti/getting-started-with-fp-ts-semigroup-2mf7">https://dev.to/gcanti/getting-started-with-fp-ts-semigroup-2mf7</a></li><li><a href="https://dev.to/gcanti/getting-started-with-fp-ts-monoid-ja0">https://dev.to/gcanti/getting-started-with-fp-ts-monoid-ja0</a></li></ol><p>Dan ada komentar menarik di sini: <a href="https://dev.to/jbristow/comment/78dl">https://dev.to/jbristow/comment/78dl</a> 😄</p><h4>Emang gimana sih gimana kalau implementasi di Haskell?</h4><p>Simple banget!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca739bd3807bbfcdbab758aec9a9a3a4/href">https://medium.com/media/ca739bd3807bbfcdbab758aec9a9a3a4/href</a></iframe><p>Dengan begini, kita meng-<em>overload</em> operator concat (di-aliaskan dengan &lt;&gt;) dengan berbagai macam tipe data, sehingga tipe data yang telah memiliki instance Monoid dapat beroperasi dengan &lt;&gt;, seperti di bawah ini:</p><pre>Sum 1 &lt;&gt; Sum 2 == Sum 3<br>Prod 2 &lt;&gt; Prod 9 == Prod 18<br>&quot;Jihad&quot; &lt;&gt; &quot;Pita&quot; == &quot;JihadPita&quot;<br>Color &quot;transparent&quot; &lt;&gt; Color &quot;#aaa&quot; == Color &quot;#aaa&quot;</pre><p>Nah karena &lt;&gt; sudah <em>polymorphic</em> dengan berbagai macam tipe data, kita ndak perlu menghafal berbagai macam nama method/function hanya untuk <strong>menggabungkan</strong> sesuatu. Beberapa minggu yang lalu saya sedang latihan parser dengan Haskell (menggunakan Parsec), dan saya ingin menggabungkan 2 buah parser menjadi satu. Gak perlu buka dokumentasi, cukup dengan intuisi, saya gunakan &lt;&gt; dan ternyata berhasil-berhasil aja karena String sudah implement instance Monoid 😉</p><pre>openBracket :: Parser String<br>openBracket = string &quot;[&quot;</pre><pre>space :: Parser String<br>space = string &quot; &quot;</pre><pre>openBracketFollowedBySpace :: Parser String<br>openBracketFollowedBySpace = openBracket &lt;&gt; space</pre><h3>Apa yang Bisa Dipelajari?</h3><p>My takeaway: Functional Programming paradigm memungkinkan kita untuk <strong>membuat abstraksi sampai ke hal-hal yang sangat mendasar</strong>. Dalam hal Semigroup, kita <strong>mengabstraksi operasi penggabungan</strong> dari 2 buah tipe data. Kedepannya insyaallah saya akan menulis artikel tentang abstraksi FP soal operasional aritmatik dasar seperti +, -, *, dan / menggunakan typeclass <strong>Semiring</strong>, <strong>Ring</strong>, dan <strong>EuclideanRing</strong> (tapi gak tau kapan ya) 😄</p><p>Jika temen-temen tertarik bagaimana membuat abstraksi di FP, saya sangat rekomendasikan untuk nonton video ini:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGlUcCPmH8wI%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGlUcCPmH8wI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FGlUcCPmH8wI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fbfe11b6c3b31fda117096460aeab4e/href">https://medium.com/media/8fbfe11b6c3b31fda117096460aeab4e/href</a></iframe><p>Terima kasih semoga bermanfaat 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c3a7d867197" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codewey/functional-programming-mengenal-semigroup-dan-monoid-8c3a7d867197">Functional Programming: Mengenal Semigroup dan Monoid</a> was originally published in <a href="https://medium.com/codewey">codewey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Partial Application: Pecahkan Saja Fungsimu biar Ramai!]]></title>
            <link>https://medium.com/codewey/partial-application-pecahkan-saja-fungsimu-biar-ramai-9706a8b48fe9?source=rss----c57339f9150d---4</link>
            <guid isPermaLink="false">https://medium.com/p/9706a8b48fe9</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[bahasa-indonesia]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Jihad Dzikri Waspada]]></dc:creator>
            <pubDate>Thu, 28 Feb 2019 03:35:22 GMT</pubDate>
            <atom:updated>2019-02-28T03:30:48.906Z</atom:updated>
            <content:encoded><![CDATA[<h4>Fiddling dengan ES6/Typescript</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6-4Cgg1BwO7dH7gGpVms2Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/dvdVt32seOU?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Denis Bayer</a> on <a href="https://unsplash.com/search/photos/math?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Beberapa waktu yang lalu, ada temen lama nanyain soal <em>redux middleware</em> yang keliatannya nerima 3 parameter padahal nggak.</p><pre>const middleware = store =&gt; next =&gt; action =&gt; {<br>  ...<br>}</pre><p>Sesungguhnya daku tak tahu kenapa harus begitu (mungkin temen-temen yang penasaran bisa cari tau alasannya di link <a href="https://github.com/reduxjs/redux/issues/534">ini</a>). Tapi 2 hal yang langsung terbesit di kepala adalah: pattern di atas disebut <strong><em>Partial Application</em></strong>,<em> </em>yang kebetulan<em> </em>menggunakan konsep <strong><em>Higher Order Function</em></strong>. Untuk me-refresh ingatan, HOF adalah istilah untuk sebuah function yang menerima dan/atau mengembalikan sebuah function juga. Para pembaca yang budiman pasti udah pada tau ya hehe.</p><p>Untuk <em>partial application</em> sendiri, konsep ini sangat lumrah di Functional Programming yang berarti proses pemanggilan function dengan <em>argument</em> yang lebih sedikit dari yang semestinya, dan hasilnya adalah sebuah function baru dengan sisa <em>argument</em> yang belum dipanggil sebelumnya.</p><blockquote>Supplying fewer than the total number of arguments is referred to as partial application.</blockquote><p>Di beberapa bahasa seperti Haskell, Purescript, dan ReasonML, semua function yang kita buat sudah ter-curry <em>by default</em>, sehingga <em>partial application</em> pun kita dapatkan secara free 😍</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58254cf8c334f21d1d59de16fdfcccc2/href">https://medium.com/media/58254cf8c334f21d1d59de16fdfcccc2/href</a></iframe><p>Di Javascript, kita bisa menggunakan fungsi Daley .bind:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*ulxiUv0AeuVTrKoB-fJ3CQ.jpeg" /><figcaption>ya bro?</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d38557febb37bd22a08ff6edc7905c55/href">https://medium.com/media/d38557febb37bd22a08ff6edc7905c55/href</a></iframe><p>But hellooow kita idup di tahun 2019 tahunnya pilpres, ga jaman wkwk. Alternatifnya ya musti return functions secara eksplisit:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3d00544466b19a46d647300cad47296/href">https://medium.com/media/e3d00544466b19a46d647300cad47296/href</a></iframe><p>Tapi apa manfaatnya?</p><h3>Factory Function 🏭</h3><p>Pas lagi nulis artikel ini, aku pingin cari tau apa sih pendapat Pakde Google tentang “Factory Function” atau “Factory Method Pattern” ini. Banyak yang bilang kegunaan utamanya adalah untuk <a href="https://www.dofactory.com/javascript/factory-method-design-pattern">menyederhanakan <em>logic</em> pembuatan suatu object</a>. Sebagian yang lain bilang bisa digunakan <a href="https://medium.com/javascript-scene/javascript-factory-functions-with-es6-4d224591a8b1">sebagai alternatif </a><a href="https://medium.com/javascript-scene/javascript-factory-functions-with-es6-4d224591a8b1">class di Javascript</a>, dll.</p><p>Tapi karena kita sedang berbicara tentang <em>partial application</em>, tak usahakan membahas apa hubungan <em>partial application</em> dengan <em>factory function</em>. Nah menurut kesotoyanku, <em>factory function</em> itu jangan kita persempit scope-nya hanya untuk objects. Kita bisa gunakan term factory (indonesia: pabrik) secara literal untuk functions juga, dimana sebuah fungsi bisa menjadi “pabrik” untuk mencetak beberapa fungsi baru dengan <em>behaviour</em> yang berbeda-beda.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee77d39bd40149b2a0531d8d5438572a/href">https://medium.com/media/ee77d39bd40149b2a0531d8d5438572a/href</a></iframe><p>Pada contoh di atas, function add yang suangat suwimpel itu bisa kita anggap sebagai <em>factory function</em> yang menghasilkan 3 fungsi baru dengan <em>behaviour</em> yang baru juga: identity, increment, dan decrement.</p><h4>Event Listener</h4><p>Atau ketika kita attach <em>listener</em> di input field:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/935252a795872433a3601178599284ba/href">https://medium.com/media/935252a795872433a3601178599284ba/href</a></iframe><p>Snippet barusan mungkin udah sering temen-temen pake. Sadar nggak sadar, kita sudah make konsep <em>partial application</em>.</p><h4>Caching</h4><p>Kita bisa buat sebuah function sederhana untuk <em>caching</em> hasil komputasi dari function lain dengan <em>partial application</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e40c85cfc30685b78b78782ffc4d6603/href">https://medium.com/media/e40c85cfc30685b78b78782ffc4d6603/href</a></iframe><h4>More examples</h4><p>Agar lebih meyakinkan lagi, tak list beberapa library terkenal yang jelas menggunakan konsep <em>factory function</em> dengan <em>partial application</em> (untuk peningkatan performance):</p><ol><li>react-redux (<a href="https://react-redux.js.org/api/connect#factory-functions">https://react-redux.js.org/api/connect#factory-functions</a>)</li><li>reselect (<a href="https://github.com/reduxjs/reselect#q-how-do-i-create-a-selector-that-takes-an-argument">https://github.com/reduxjs/reselect#q-how-do-i-create-a-selector-that-takes-an-argument</a>)</li></ol><p><em>Neat</em> 🎉</p><h3>Applicative Functor 🧮</h3><p>Dulu saya pernah nulis tentang Applicative Functor (needs revision tho).</p><p><a href="https://medium.com/codewey/functional-programming-mengenal-applicative-functor-c8afb02eb5ad">Functional Programming: Mengenal Applicative Functor</a></p><p>Singkatnya, tugas utama Applicative Functor ini adalah untuk mengangkat “derajat” suatu function dari function biasa ke function yang bisa beroperasi di <em>monadic context</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be81b29f60a00df4418e752cc9b36998/href">https://medium.com/media/be81b29f60a00df4418e752cc9b36998/href</a></iframe><p>Yang mana kita tahu bahwa Applicative Functor gak akan mungkin bisa jalan kalau nggak pake <em>partial application</em>.</p><h3>Kesimpulan</h3><p>Potensi yang dimiliki <em>partial application</em> sebenarnya masih banyak karena <em>partial application</em> memungkinkan kita untuk membuat <em>composable function</em> (<em>and reusable!</em>). Contoh di atas cuman sebagian kecilnya aja. Mungkin temen-temen lain ada contoh tambahan atau ada saran? Monggo input-nya di kolom komentar. Kalau ndak ada yaa.. semoga bermanfaat 😃👏🏻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9706a8b48fe9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codewey/partial-application-pecahkan-saja-fungsimu-biar-ramai-9706a8b48fe9">Partial Application: Pecahkan Saja Fungsimu biar Ramai!</a> was originally published in <a href="https://medium.com/codewey">codewey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kode Terlalu Repetitif di Reducer? Introduce: Higher-Order Reducer]]></title>
            <link>https://medium.com/codewey/struktur-redux-store-kamu-terlalu-repetitif-introduce-higher-order-reducer-717677aeb6f9?source=rss----c57339f9150d---4</link>
            <guid isPermaLink="false">https://medium.com/p/717677aeb6f9</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jihad Dzikri Waspada]]></dc:creator>
            <pubDate>Sat, 24 Nov 2018 18:09:28 GMT</pubDate>
            <atom:updated>2018-04-22T10:41:52.580Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D5d8vD7LI-il6hfR3CWlmA.jpeg" /><figcaption>Simple Photograph (<a href="https://www.walldevil.com/colorful-fallingwater-paint-photography-closeup-simple-wallpaper-112803/">source</a>)</figcaption></figure><p>Salaam semuanya! Maaf udah lama ndak nulis lagi, diitung-itung udah 9 bulan vakuum. Entah kenapa semenjak nikah, rutinitas-rutinitas kayak nulis dan belajar-belajar jadi suka terbengkalai 😛 You know lah wkwk. Sampai akhirnya disentil sama Shifu <a href="https://medium.com/u/d09eac079a9c">Irfan Maulana</a> buat nulis lagi 😁 *maafkan saya Shifu</p><p>So, balik ke topik. Higher-Order Reducer. Entah istilah ini tepat atau nggak, saya sendiri kurang begitu yakin, tapi saya akan coba terangkan secara singkat dimulai dari permasalahan yang sangat sangat simple: <strong>Async Actions</strong>.</p><h3>The problem</h3><p>Biasanya, <em>Async Actions</em> ini direpresentasikan dengan tambahan 3 suffix berikut: REQUEST, SUCCESS, dan FAILED.</p><pre><strong>const</strong> createAction = actionName =&gt; payload =&gt; ({<br>  type: actionName,<br>  payload<br>})</pre><pre><strong>const</strong> getUserRequest = createAction(&#39;GET_USER_REQUEST&#39;)<br><strong>const</strong> getUserSuccess = createAction(&#39;GET_USER_SUCCESS&#39;)<br><strong>const</strong> getUserFailed = createAction(&#39;GET_USER_FAILED&#39;)</pre><p>Setelah berhasil mendapatkan datanya dari suatu <em>endpoint</em>, kita <strong>hanya ingin menyimpan datanya di redux store</strong>. Urusan pengolahan <em>business logic</em> bisa kita serahkan ke function lain (use <a href="https://github.com/reactjs/reselect">reselect</a>), saat ini kita hanya fokus pada penyimpanan datanya saja.</p><p>Kita bisa handle ketiga <em>action creators</em> ini di <em>reducer</em> seperti:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/451bbe9dbc4a9cc8f16aedea5ecfbf9e/href">https://medium.com/media/451bbe9dbc4a9cc8f16aedea5ecfbf9e/href</a></iframe><p>Sangat standar. Works good. Nothing special.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*GeCbe-eQF177plHfMMafcQ.gif" /><figcaption>Muka Standar</figcaption></figure><p>BUT. Bagimana jadinya kalo <em>Async Action</em> kita lebih dari satu? Bagaimana kalau kita ingin fetch post juga? Solusi paling mudah: tinggal kopas aja dari user dan ganti <em>key</em>-nya jadi post 😎</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65386acecf368ce5c37b1a4f27355101/href">https://medium.com/media/65386acecf368ce5c37b1a4f27355101/href</a></iframe><p>Hmm, ada yang salah? Keliatannya sih baik-baik aja, tapi agak kurang sreg gimanaa gitu ya. <em>I smell repetitive code</em>, yang mungkin saja OK, tapi <em>in most cases not OK</em>. Karena bisa jadi, kita gak cuma akan fetch user dan post saja, mungkin kita juga mau fetch data-data lain dan menyimpan hasilnya di redux store. Jika hal itu dilakukan dengan metode <em>copy-paste-modify</em> seperti halnya di atas, konsekuensinya adalah <em>longer repetitive code</em>, <strong>WICIS</strong> gak baik.</p><p>(sengaja saya bold, biar keliatan pinter bahasa inggris 😌)</p><blockquote>Less code === Less bug</blockquote><p>Jadi, bagaimana solusinya?</p><h3>Higher-Order Reducer</h3><p>Sesuai namanya, Higher-Order Reducer adalah suatu <em>reducer</em> yang menerima dan/atau mengembalikan <em>reducer</em> lain. Singkat cerita, kita akan meng-<em>extract</em> bagian yang repetitif tersebut menjadi sebuah reducer. <em>Reducer</em> di dalam <em>reducer</em>. Sebagai glue-nya, kita bisa menggunakan combineReducer dari redux.</p><p>Tapi sebelum masuk ke bagian intinya, saya ingin sedikit mengubah fungsi createAction dan menambahkan sebuah fungsi baru bernama createAsyncAction agar solusi yang ditawarkan menjadi lebih menarik.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f93e855d59a87f56faa11e582e9c2473/href">https://medium.com/media/f93e855d59a87f56faa11e582e9c2473/href</a></iframe><p>(Yha, <em>function</em> adalah sebuah Object di Javascript. Bisa dicoba dengan menjalankan function seperti layaknya mengakses sebuah object seperti: document.addEventListener.length. Lihat apa yang akan terjadi, nomor 7 bikin kamu geleng-geleng kepala!)</p><p>Daaan sekarang ke intinya, <em>setting up the reducer</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb1eb6ce3d16c2bcbf83274c1ae1701b/href">https://medium.com/media/bb1eb6ce3d16c2bcbf83274c1ae1701b/href</a></iframe><p>Perbedaan mendasar dari HOR ini adalah, kita membuat satu <em>reducer</em> sendiri untuk masing-masing <em>object</em> (dalam hal ini user dan post). Dibandingkan solusi awal yang hanya mengambalikan <strong>1 reducer (untuk 2 object)</strong>, dengan solusi HOR ini kita mengembalikan<strong> 2 reducer sekaligus (1 reducer untuk 1 object)</strong>.</p><p>Jika dianalogikan, struktur redux store pada solusi awal adalah</p><pre>// redux store solusi awal<br>(state, action) =&gt; ({<br>  user: { <strong>// &lt;- PLAIN OBJECT</strong><br>    data: {}<br>    asyncState: ...,<br>  },<br>  post: { <strong>// &lt;- PLAIN OBJECT</strong><br>    data: {}<br>    asyncState: ...,<br>  },<br>  ...<br>})</pre><p>Bandingkan dengan menggunakan HOR:</p><pre>// redux store solusi HOR<br>(state, action) =&gt; ({<br>  user: (ownState, action) =&gt; ({ <strong>// &lt;- REDUCER</strong><br>    data: {}<br>    asyncState: ...,<br>  }),<br>  post: (ownState, action) =&gt; ({ <strong>// &lt;- REDUCER</strong><br>    data: {}<br>    asyncState: ...,<br>  }),<br>  ...<br>})</pre><p>Yha, sangat sangat sederhana. Tapi terkadang untuk menciptakan sesuatu yang sederhana itu tidak mudah. Senada dengan ucapan Legenda Sepak Bola Barcelona, Johan Cruyff ketika mencetus taktik sepakbola tiki-taka:</p><blockquote><strong>Playing football</strong> is <strong>very simple</strong>, <strong>but playing simple football</strong> is the hardest thing there is — Johan Cruyff</blockquote><p>atau Legenda Sinetron Kolosal Indosari ketika terbang dengan naga:</p><blockquote>Coding is very simple, but finding simple solution with code is the hardest thing there is — Jihad D. Waspada</blockquote><h3>Penutup</h3><p>Dengan memanfaatkan konsep Higher-Order Reducer, kita bisa <strong>mengeliminasi kode yang repetitif di <em>reducer</em> sembari tetap menjaga struktur redux store</strong> kita. Potensi kegunaan HOR ini sangat luas, bisa diterapkan di kasus-kasus yang lain. Saya pribadi menggunakan konsep HOR ini untuk pekerjaan yang berhubungan dengan Form.</p><p>Oh ya, createAsyncCreator di atas, saya <em>derive</em> dari Project <a href="https://github.com/aikoven/typescript-fsa">Typescript-FSA</a>. Sangat merekomendasikan library ini karena Typescript nya maknyus. Integrasi ke berbagai <em>side-effect library</em>-nya juga cukup memadai. Bisa ke Saga, ke Observable, atau bahkan ke reducer itu sendiri. Cek aja ya 😉</p><p>Terkahir, semoga tulisan ini bisa bermanfaat. Dan doakan juga semoga saya bisa konsisten nulis di medium lagi 😄. Dan semoga yang jomblo segera dapet istri! Bye!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=717677aeb6f9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codewey/struktur-redux-store-kamu-terlalu-repetitif-introduce-higher-order-reducer-717677aeb6f9">Kode Terlalu Repetitif di Reducer? Introduce: Higher-Order Reducer</a> was originally published in <a href="https://medium.com/codewey">codewey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tentang Loading State…]]></title>
            <link>https://medium.com/codewey/tentang-loading-state-886dbb1cfe8d?source=rss----c57339f9150d---4</link>
            <guid isPermaLink="false">https://medium.com/p/886dbb1cfe8d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Jihad Dzikri Waspada]]></dc:creator>
            <pubDate>Sat, 24 Nov 2018 18:09:04 GMT</pubDate>
            <atom:updated>2018-04-30T07:33:52.955Z</atom:updated>
            <content:encoded><![CDATA[<h4>Invalidate the invalids</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oQXT3LKxRHELzgutvn1XZg.png" /><figcaption>Loading (<a href="https://www.videoblocks.com/video/computer-screen-loading-bar-animation-3-ruhxzp-6xj149kn2r">source</a>)</figcaption></figure><p>Bagi kamu-kamu yang berkarir sebagai Frontend atau Full-stack(overflow) developer, <em>handling </em><strong><em>loading states</em></strong><em> is a must</em>, apalagi ketika berhadapan dengan <em>async operations</em>. Dari beberapa aplikasi yang pernah saya kerjakan, saya menemukan adanya kesamaan dalam penanganan <em>async operations</em> seperti ini:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68d782fa1ea643d11d65f85a248221b3/href">https://medium.com/media/68d782fa1ea643d11d65f85a248221b3/href</a></iframe><p>Dialah si 3 serangkai isLoading, isLoaded, dan error. Di level <em>component</em>, kita biasa menggunakan mereka dengan</p><pre>render() {<br>  const { isLoading, error } = this.props;</pre><pre>  if (<strong>isLoading</strong>) return &lt;SpinnerLoading /&gt;</pre><pre>  if (<strong>error</strong>) return &lt;ErrorMessage /&gt;</pre><pre>  return &lt;SomeComponent /&gt;<br>}</pre><p>Kalo jalan sih jalan. Tapi menurut hemat saya, ada satu masalah desain yang kurang tepat di sini.</p><h3>Invalid States</h3><p>Kalau kita perhatikan satu per satu ketiga serangkai di atas, masing-masing punya <em>rule</em>-nya sendiri-sendiri:</p><ol><li>Jika kita ingin mengekspresikan keadaan sedang <em>loading</em>, maka isLoading harus true, sedangkan isLoaded dan error haruslah false.</li><li>Jika kita ingin mengekspresikan keadaan dimana proses <em>fetching</em> data-nya berhasil, maka isLoaded harus true, sedangkanisLoading dan error haruslah false.</li><li>Jika kita ingin mengekspresikan keadaan dimana terjadi error ketika <em>fetch</em> data, maka error harus diisi dengan <em>error msg</em>, sedangkan isLoading dan isLoaded haruslah false.</li></ol><p>Pendekatan seperti ini dirasa kurang sreg karena membuka peluang kepada terjadinya <em>invalid states</em>. Maksudnya apa? Mari coba menjawab pertanyaan berikut:</p><blockquote>Jika isLoading dan isLoaded keduanya saya set dengan true, <em>state</em> apa yang kira-kira sedang saya coba representasikan?</blockquote><p>Jawabannya: ndak ada. Karena secara intuitif, <strong>tidak mungkin kita bilang si anak sudah lahir sementara sang ibu masih mengandung</strong>. Inilah yang kita sebut dengan <em>Invalid State</em>.</p><h3>Let’s invalidate the invalid ones</h3><p>Solusinya sederhana, dengan mengekspresikannya langsung.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a434c95ba9eb56bb857bcac17a38cb9e/href">https://medium.com/media/a434c95ba9eb56bb857bcac17a38cb9e/href</a></iframe><p>Bagi pengguna Typescript, bisa menggunakan <a href="https://www.typescriptlang.org/docs/handbook/enums.html">Enumeration</a>:</p><pre><strong>export</strong> <strong>enum</strong> AsyncState { fetching, success, error }</pre><p>dan sisanya sama seperti <em>gist</em> di atas.</p><p>Dengan cara seperti ini, kita tidak perlu lagi mengecek ketiga state tersebut hanya untuk memahami dimana kita berada. Kita tidak perlu lagi mengecek isLoaded dan error hanya untuk memahami bahwa isLoading bernilai true. Cukup dengan melihat AsyncState.fetching kita sudah paham. <strong>Dan tentunya, kita tidak lagi membuka peluang terhadap lahirnya <em>state</em> lain di luar ketiga <em>state</em> tersebut</strong> (loading, success, error).</p><blockquote>“Intellectuals solve problems, geniuses prevent them”</blockquote><blockquote>— Albert Einstein</blockquote><p>Semoga bermanfaat~</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=886dbb1cfe8d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codewey/tentang-loading-state-886dbb1cfe8d">Tentang Loading State…</a> was originally published in <a href="https://medium.com/codewey">codewey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Phantom Type di Typescript]]></title>
            <link>https://medium.com/codewey/phantom-type-di-typescript-5e523652dd9?source=rss----c57339f9150d---4</link>
            <guid isPermaLink="false">https://medium.com/p/5e523652dd9</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[bahasa-indonesia]]></category>
            <dc:creator><![CDATA[Jihad Dzikri Waspada]]></dc:creator>
            <pubDate>Sat, 24 Nov 2018 18:00:10 GMT</pubDate>
            <atom:updated>2018-09-17T11:18:46.802Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TZl_UqVCsGuE77i9yvJsYQ.jpeg" /><figcaption>source: <a href="http://wallpaperswide.com/cod_ghosts-wallpapers.html">http://wallpaperswide.com/cod_ghosts-wallpapers.html</a></figcaption></figure><p>Phantom Type adalah istilah untuk sebuah type yang salah satu type parameter-nya tidak muncul di sebalah kanan definisinya (gak tau gimana jelasin ke Bahasa Indonesia yang enak 😞). Pake contoh aja ya biar lebih nangkep:</p><pre><strong>type</strong> Either&lt;L, R&gt; = Left&lt;L&gt; | Right&lt;R&gt;</pre><p>Type di atas adalah salah satu contoh Phantom Type karena Left hanya menggunakan generics L dan Right hanya menggunakan generics R: L dan R tidak keluar secara berbarengan.</p><pre><strong>type</strong> Tuple&lt;A, B&gt; = [A, B]</pre><p>Type ini bukan merupakan Phantom Type karena A dan B digunakan sepenuhnya.</p><h3>Yak, terus?</h3><p>“Terus, terus, terus.” — Kang Parkir</p><p>Temen-temen pasti pernah main sama <em>measurement unit</em> kayak Kilometer, Celcius, atau bahkan mata uang. 100 derajat Celcius !== 100 derajat Fahrenheit. Tapi kadang kita justru agak <em>sloppy</em> dalam perhitungan “relatif” seperti ini.</p><pre><strong>const</strong> isBoiling = (degree: <strong>number</strong>) =&gt; degree &gt;= 100;</pre><pre><strong>const</strong> celcius100 = 100;<br><strong>const</strong> fahrenheit100 = 100;</pre><pre>isBoiling(celcius100); // true<br>isBoiling(fahrenheit100); // true, tapi kenyataannya salah, karena air mendidih di 212F, 100C === 212F</pre><p>Ada berbagai macam solusi. Misal, kita ubah nama variabel degree menjadi degreeInCelcius, atau kasih DocBlock di atas nama fungsinya yang menjelaskan bahwa fungsi ini hanya menerima satuan Celcius. Tapi rasanya akan lebih asik kalau kita bisa memanfaatkan compiler untuk menangani masalah ini. Lho emang bisa? Insyallah 😎</p><h4>Proposed Solution</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa3752e27086039301485f01e3734775/href">https://medium.com/media/fa3752e27086039301485f01e3734775/href</a></iframe><p>Sekilas, type parameter A nggak berguna, karena gak dipake dimana-mana :( Tapi dari deklarasi fungsi isBoiling, argument temp sudah sangat jelas menyatakan bahwa ia hanya menerima Celcius, bukan yang lain.</p><p>Namun sayangnya, bila dijalankan, Typescript belum bisa membedakan Temp&lt;Celcius&gt; dan Temp&lt;Fahrenheit&gt; adalah sesuatu yang berbeda 😞</p><pre>const c100 = new Temp&lt;Celcius&gt;(100);<br>const f100 = new Temp&lt;Fahrenheit&gt;(100);</pre><pre>isBoiling(c100); // type-check<br>isBoiling(f100); // type-check</pre><p>Ini dikarenakan nature Typescript <strong>yang meng-infer suatu type dari strukturnya, bukan dari nama-nya</strong> (bisa dibaca disini: <a href="https://basarat.gitbooks.io/typescript/docs/types/type-compatibility.html#structural">https://basarat.gitbooks.io/typescript/docs/types/type-compatibility.html#structural</a>).</p><p>Jadi, kita harus revisi!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db27405d07d2002b4c5bb1748d8c9dfd/href">https://medium.com/media/db27405d07d2002b4c5bb1748d8c9dfd/href</a></iframe><p>Ketika kita supply f100 ke fungsi isBoiling, error-nya jelas:</p><pre>Argument of type &#39;Temp&lt;Fahrenheit&gt;&#39; is not assignable to parameter of type &#39;Temp&lt;Celcius&gt;&#39;.<br>  Type &#39;Fahrenheit&#39; is not assignable to type &#39;Celcius&#39;.<br>    Property &#39;__celcius__&#39; is missing in type &#39;Fahrenheit&#39;.</pre><p>MASHHUKK PAK EKKOO!</p><p>Sebagai alternatif, kita juga bisa menggunakan fitur Enumeration (<a href="https://www.typescriptlang.org/docs/handbook/enums.html">https://www.typescriptlang.org/docs/handbook/enums.html</a>) untuk membuat “type” yang unique:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f8f0284475bd75e9e966621836cf9b6/href">https://medium.com/media/4f8f0284475bd75e9e966621836cf9b6/href</a></iframe><p>pesan errornya juga gak kalah jelas:</p><pre>Argument of type &#39;Temp&lt;Unit.Fahrenheit&gt;&#39; is not assignable to parameter of type &#39;Temp&lt;Unit.Celcius&gt;&#39;.<br>  Type &#39;Unit.Fahrenheit&#39; is not assignable to type &#39;Unit.Celcius&#39;.</pre><p>Jadi terserah mau pakai yang mana :))</p><h4>Contoh 2</h4><p>Salah satu contoh yang paling terkenal dari Phantom Type adalah validasi data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/285b63b573f48ca2c994f9fdaff99cbe/href">https://medium.com/media/285b63b573f48ca2c994f9fdaff99cbe/href</a></iframe><p>Harusnya sih sudah sangat jelas: data hanya bisa dikirim ke Backend setelah divalidasi terlebih dahulu. <em>Types make everything even more clear</em> 😙</p><h3>Kesimpulan</h3><p>Teknik ini sangat berguna ketika kita <strong>ingin membedakan</strong> suatu data dengan data lainnya, namun keduanya memiliki tipe yang sama.</p><pre><strong>const</strong> date: <strong>string</strong> = &#39;2018-09-17&#39;;<br><strong>const</strong> dateIsoXXX: <strong>string</strong> = &#39;17 Sept 2018 UTC+2&#39; // whatever</pre><p>bisa disubstitusi dengan</p><pre><strong>interface</strong> MyDate <strong>extends</strong> String { __my_date__: <strong>never</strong> }<br><strong>interface</strong> MyDateIsoXXX <strong>extends</strong> String { __xxx__: <strong>never</strong> }</pre><pre><strong>const</strong> date: MyDate = &#39;2018-09-17&#39;;<br><strong>const</strong> dateIsoXXX: MyDateIsoXXX = &#39;17 Sept 2018 UTC+2&#39;;</pre><p>dan sebagainya. Zero overhead ketika run time karena interface di Typescript akan dihilangkan dari code. Semoga bermanfaat 🙂</p><h4>Referensi</h4><ol><li><a href="https://medium.com/@gcanti/phantom-types-with-flow-828aff73232b">https://medium.com/@gcanti/phantom-types-with-flow-828aff73232b</a></li><li><a href="https://medium.com/@dhruvrajvanshi/advanced-typescript-patterns-6cf8826c7944">https://medium.com/@dhruvrajvanshi/advanced-typescript-patterns-6cf8826c7944</a></li><li><a href="https://robhoward.id.au/blog/2017/02/effective-types-phantom-types-with-flow/">https://robhoward.id.au/blog/2017/02/effective-types-phantom-types-with-flow/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e523652dd9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codewey/phantom-type-di-typescript-5e523652dd9">Phantom Type di Typescript</a> was originally published in <a href="https://medium.com/codewey">codewey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Typescript Nominal Typing]]></title>
            <link>https://medium.com/codewey/typescript-nominal-typing-99c1d91a891c?source=rss----c57339f9150d---4</link>
            <guid isPermaLink="false">https://medium.com/p/99c1d91a891c</guid>
            <category><![CDATA[bahasa-indonesia]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Jihad Dzikri Waspada]]></dc:creator>
            <pubDate>Sat, 24 Nov 2018 17:59:31 GMT</pubDate>
            <atom:updated>2019-08-09T08:24:06.763Z</atom:updated>
            <content:encoded><![CDATA[<h3>Nominal Typing di Typescript</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Gkd9c2YVjChdhhiSdYq3Q.jpeg" /><figcaption>Unique (src: <a href="https://www.one-mind-one-energy.com/images/unique.jpg">https://www.one-mind-one-energy.com/images/unique.jpg</a>)</figcaption></figure><p>Seperti yang kita ketahui, teknik type check yang digunakan Typescript adalah <a href="https://www.typescriptlang.org/docs/handbook/type-compatibility.html">structural checking</a>. Bahkan di level <em>class</em> pun masih <em>structural check</em>, agak berbeda dengan Flow yang menggunakan <em>nominal check </em>di level ini (<a href="https://flow.org/en/docs/lang/nominal-structural/#toc-nominal-typing">https://flow.org/en/docs/lang/nominal-structural/#toc-nominal-typing</a>). Sehingga code ini pun <em>typechecked</em> di Typescript:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0e8ea8b6619cd947de204d4bb7b0f97/href">https://medium.com/media/e0e8ea8b6619cd947de204d4bb7b0f97/href</a></iframe><p>Di beberapa bahasa pemrograman seperti Java, class A dan class B dianggap sesuatu yang berbeda, walaupun secara structural sama. Inilah yang dimaksud dengan <em>nominal check</em> atau <em>nominal typing</em>.</p><p>Nominal types akan sangat berguna untuk modelling data yang tidak pandang struktur. Misal seperti membedakan Celcius dengan Fahrenheit:</p><pre>const fiveC: Celcius = 5;<br>const fiveF: Fahrenheit = 5;</pre><p>yang walaupun sama-sama bertipe number, mereka tidaklah sama. 5℃ !== 5℉. Seperti yang pernah saya bahas di artikel sebelumnya:</p><p><a href="https://medium.com/@Dewey92/phantom-type-di-typescript-5e523652dd9">Phantom Type di Typescript</a></p><p>And in fact, Phantom Type adalah salah satu cara untuk mencapai Nonimal Typing. Namun di artikel ini, saya akan propose solusi yang lebih general dari Phantom Type, yang bisa diterapkan di tipe data apapun. Nama umumnya adalah Branding.</p><h3>Branding</h3><p>Teknik <em>branding</em> ini sebenarnya sama persis seperti Phantom Type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4397c5053a2c99e5692c3619c6b8d548/href">https://medium.com/media/4397c5053a2c99e5692c3619c6b8d548/href</a></iframe><p>Jika kita coba membuat sebuah <em>function</em> yang menerima argument bertipe Celcius namun malah memberinya Fahrenheit, maka compiler akan komplain:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/536455a67b6d7af84871b6b9038ac417/href">https://medium.com/media/536455a67b6d7af84871b6b9038ac417/href</a></iframe><p>Berhasil! fiveC dan fiveF ter-model-kan pada saat compile time, sehingga tidak perlu khawatir akan “tertukar” saat run time. Code kita pun menjadi sangat <em>expressive</em> :)</p><p>Bila kita mampir sebentar ke internal compiler Typescript itu sendiri, kita bisa langsung melihat <a href="https://github.com/Microsoft/TypeScript/blob/master/src/compiler/types.ts#L4">penggunaan nominal type ini</a>.</p><h4>Improvements</h4><p>Kita bisa membuat improvements dari implementasi Brand&lt;Name, Type&gt; yang kita buat di atas. Karena pada praktiknya, implementasi di atas agak kaku:</p><pre>const fiveC: Celcius = 5; // error</pre><pre>Type &#39;5&#39; is not assignable to type &#39;Brand&lt;&quot;Celcius&quot;, number&gt;&#39;.<br>  Type &#39;5&#39; is not assignable to type &#39;{ _brand: &quot;Celcius&quot;; }&#39;.</pre><p>So, kita hanya perlu mengubah properti _brand menjadi optional:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b473c7c284cc0f0c58c2f39e056f4fab/href">https://medium.com/media/b473c7c284cc0f0c58c2f39e056f4fab/href</a></iframe><p>Masih ada yang bisa di-improve btw. Kalau diperhatikan, key _brand, masih bisa diakses dari luar dan kita gak mau begitu supaya code tetap clean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*2HbMLFiumRKTailTlCClDQ.png" /><figcaption>nope!</figcaption></figure><p>Caranya dengan menggunakan Symbol sebagai key-nya dan tidak meng-export key tersebut.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6249cdf295767f1091cd6b97f88b8d6/href">https://medium.com/media/d6249cdf295767f1091cd6b97f88b8d6/href</a></iframe><p>Sekarang key-nya menajdi tidak accessable ke user!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*Gtf4Xydzqii3FI7Jk1DzHQ.png" /><figcaption>yes!</figcaption></figure><p>Done 🎉🎉🎉</p><p>BTW, saya pribadi lebih suka dengan term “new type” dibanding “brand”, mengambil keyword dari Haskell (<a href="https://wiki.haskell.org/Newtype">https://wiki.haskell.org/Newtype</a>):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/110595f8936db8d51a05b03080b39ec6/href">https://medium.com/media/110595f8936db8d51a05b03080b39ec6/href</a></iframe><p>Tapi ndak ada alasan spesifik kok, cuman preferensi 🙂</p><h3>Kesimpulan</h3><p>Tulisan ini saya rasa terlalu singkat, jadi disimpulkan sendiri aja ya 😁.</p><p><em>Clap if you find this article useful 👏🏻</em></p><p>Semoga bermanfaat! 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99c1d91a891c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codewey/typescript-nominal-typing-99c1d91a891c">Typescript Nominal Typing</a> was originally published in <a href="https://medium.com/codewey">codewey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mengapa Typescript?]]></title>
            <link>https://medium.com/codewey/mengapa-typescript-9914c7c14793?source=rss----c57339f9150d---4</link>
            <guid isPermaLink="false">https://medium.com/p/9914c7c14793</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[bahasa-indonesia]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Jihad Dzikri Waspada]]></dc:creator>
            <pubDate>Sat, 24 Nov 2018 17:58:57 GMT</pubDate>
            <atom:updated>2018-10-20T07:52:35.933Z</atom:updated>
            <content:encoded><![CDATA[<h4>Kenapa why selalu always tetapi but tidak pernah never?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*0DGG_Ct35XdusaZZ3oz1yA@2x.png" /><figcaption>image <a href="https://netbasal.com/getting-to-know-the-partial-type-in-typescript-ecfcfbc87cb6">source</a></figcaption></figure><p><strong>Karena because itu that!</strong></p><p>Pertama kali saya kerja di Bloomon, saya bergabung bersama squad yang sedang mengembangkan system in-house company ini yang kebetulan menggunakan Typescript di sisi frontend-nya. Setelah launching 5 bulan kemudian, kami berpindah squad biar gak nganggur. Main task baru saya kali ini adalah me-maintain website utama company yang ditulis menggunakan Javascript. Merasa kurang nyaman, kami propose develop projek ini menggunakan Typescript dan secara tidak mengejutkan kami “diprotes” sama temen-temen yang sudah lama di squad ini, “Javascript aja udah cukup tauk pake k!”, “Kasih types itu nggak penting..”, “type is typing.. (capek-capekin aja nulis code lebih panjang)”, dan sebagainya. 😅</p><p>Jika kamu punya pertanyaan dan pernyataan serupa: apakah worth menggunakan Typescript, apakah Javascript saja belum cukup, apakah TS dapat meningkatkan productivity, apa kau dengaar suara angin yang berhembus di muka bumiii, semoga beberapa alasan di bawah ini dapat menjawab ya 😉</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F2ndPRb7WKys%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D2ndPRb7WKys&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F2ndPRb7WKys%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/880442f270c78fa90eec8426b2e64671/href">https://medium.com/media/880442f270c78fa90eec8426b2e64671/href</a></iframe><p>⚠️ <em>Perlu diingat bahwa di sini saya nggak akan membanding-bandingkan Typescript dengan Flow, keduanya memiliki plus-minus nya masing-masing. Terlebih, saya nggak pernah pake Flow, jadi ndak bisa bikin judgement </em>😛</p><h4>1. Membantu New Joiner Cepat Beradaptasi 📚</h4><p>Ini satu alasan yang menurut saya puaaaling penting. Sekitar satu minggu yang lalu ketika satu-satunya backend developer di squad saya sedang off dan ada tiket backend yang harus diselesaikan, mau nggak mau saya (sebagai frontend dev) harus ngerjain tiket itu biar disayang PO. Pas saya oprek salah satu service yang ditulis di Node.js, ada sebuah function bernama prepareUser (bukan nama sebenarnya 🕵🏻‍) yang menerima sebuah input dan mengembalikan <em>sesuatu</em>.</p><pre><strong>const</strong> data = prepareUser(rawUser);</pre><p>Dua pertanyaan seketika muncul: Apa tipe data rawUser? Apa nilai dari data? Most likely, jawabannya: rawUser itu pasti object om, data juga pasti object. Nah masalahnya, object yang kayak gimana?</p><p>Untuk mengetahuinya, saya harus liat detail implementasi dari prepareUser yang masyaallah sungguh sangat indah:</p><pre><strong>function</strong> prepareUser(rawUser) {<br>  // ...<br>  <strong>if</strong> (rawUser.countryCode === &#39;nld&#39;) Object.assign(res, ...);<br>  <strong>if</strong> (rawUser.id) Object.assign(res, ...);<br>  // ...<br>  <strong>return</strong> res;<br>}</pre><p>Baru setelah melakukan scanning isi function yang berjumlah 129 baris itu, saya jadi tahu, oh, object rawUser itu setidaknya harus punya attribute countryCode dan id. Dan nilai kembalian dari fungsi tersebut adalah object juga dengan segala attribute yang di-assign ke variable res. Butuh waktu sekitar 10 menit untuk mencerna itu semua.</p><p>Jika ditulis menggunakan Typescript, mungkin akan lain cerita:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Ftypescript-whi4py%3Fembed%3D1%26file%3Dindex.ts%26hideExplorer%3D1%26hideNavigation%3D1%26view%3Deditor&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Ftypescript-whi4py%3Fembed%3D1%26file%3Dindex.ts%26hideExplorer%3D1%26hideNavigation%3D1%26view%3Deditor&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/9118a989671c956053f17119dffcadaf/href">https://medium.com/media/9118a989671c956053f17119dffcadaf/href</a></iframe><p>Dari code di atas, saya langsung tahu bahwa rawUser ternyata adalah sebuah object bertipe User, yang wajib memiliki attribute email dan countryCode, dan tidak harus memiliki attribute id. Pun dengan data, saya tidak perlu melihat implementasi dari function prepareUser, cukup dengan meng-hover mouse saya di atas variable data dan boom, semua jelas seketika 😉.</p><p><strong>Ini baru satu function lho, di satu file, belum di file lain, belum di folder lain, belum di projek lain. Betapa frustasinya kita jika harus membaca semua isi function hanya untuk mengetahui apa parameter dan nilai kembaliannya.</strong></p><h4>2. Typescript is Just Javascript ️❤️</h4><p>Mungkin terdengar agak klise, tapi beberapa kali saya perhatikan masih cukup banyak yang menganggap Typescript adalah sebuah bahasa pemrograman yang baru, sangat berbeda dengan Javascript pada umumnya, harus tau ekosistemnya, dan butuh waktu yang nggak sebentar untuk mempelajarinya. <em>I would say no</em>. Karena pada dasarnya, Typescript adalah superset dari ECMAScript, yang berarti <strong>semua yang kamu lakukan di Javascript pasti bisa dilakukan di Typescript</strong>. Malah, semua proposal fitur ECMAScript yang sudah mencapai <em>stage-3</em> ke atas sudah diterapkan di Typescript secara <em>default</em> seperti async-await, <em>generators</em>, import(), <em>spread operator</em>, dll. Selengkapnya bisa dicek di sini: <a href="https://kangax.github.io/compat-table/es6/#typescript3.1">https://kangax.github.io/compat-table/es6/#typescript3.1</a>. <strong>Semua developer Javascript pasti bisa menggunakan Typescript</strong>.</p><p>Dan yang terpenting adalah filosofi dari Typescript itu sendiri: <strong>“<em>Align with current and future ECMAScript proposals</em>”</strong>. Core team Typescript nggak akan menanggapi request fitur yang tidak sesuai dengan spesifikasi ECMAScript (misal yang berpotensi mengubah syntax penulisan Javascript). Full list goal-nya bisa dibaca di sini: <a href="https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals">https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals</a></p><p>Jadi, dari segi <em>syntax</em> dan <em>compatibility</em>-nya dengan Javascript, kita aman 😉</p><h4>3. Safer Code ⛑</h4><p>Kita bisa kok menganggap <strong>Typescript hanyalah sebuah <em>tool</em></strong> untuk melakukan <em>static type-checking</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/befbb554fa09f8159a2ba7c56bd3eb06/href">https://medium.com/media/befbb554fa09f8159a2ba7c56bd3eb06/href</a></iframe><p>Pada baris ke-8, kita men-declare argument product harus memliki tipe ProductModel. Itulah mengapa di baris ke-11 ndak ada error dan di baris ke-14 terjadi error. Error karena kita malah pass sebuah object kopong sedangkan fungsi getFinalPrice hanya menerima object yang setidaknya memiliki attribute id, name, price, dan tax.</p><p>Contoh lain dimana TS dapat membantu correctness program kita:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03896c760048fcd7bb82646fece4ee7f/href">https://medium.com/media/03896c760048fcd7bb82646fece4ee7f/href</a></iframe><p>Kira-kira, apa tipe data product di baris ke-18? Apakah ProductModel? Atau yang lainnya?</p><p>Salah! (ngegas) Jawabannya adalah ProductModel | undefined. Karena ketika kita memanggil funsgi getProductById, kita mencari apakah item ber-id 1 ada di dalam productList, yang mana <strong>bisa jadi item tersebut tidak ada di dalam list</strong>. TS akan komplain apabila kita coba memanggil fungsi getFinalPrice setelahnya:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0600f8b4db9bb05f52206e6842c7b1a/href">https://medium.com/media/f0600f8b4db9bb05f52206e6842c7b1a/href</a></iframe><p>Untuk mendapatkan value-nya, bisa melakukan “if-else” seperti biasa:</p><pre><strong>const</strong> finalPrice = product ? getFinalPrice(product) : 0;</pre><pre>// atau</pre><pre><strong>if</strong> (!product) <strong>throw</strong> <strong>new</strong> Error(&#39;No product found&#39;);<br><strong>const</strong> finalPrice = getFinalPrice(product);</pre><p><strong>SAFE! 😺 </strong>Intermezzo: ada sebuah studi baru-baru ini menyimpulkan bahwa penggunaan type ketika development dapat mengurangi bug sebesar 15%.</p><p><a href="https://blog.acolyer.org/2017/09/19/to-type-or-not-to-type-quantifying-detectable-bugs-in-javascript/">To type or not to type: quantifying detectable bugs in JavaScript</a></p><p>(Sayangnya di artikel tersebut menyebutkan bahwa TS butuh sytax yang lebih panjang daripada Flow agar menjadi produktif 🙈🙈🙈)</p><h4>4. Zero Overhead ketika Run Time 0️⃣</h4><p>Semua “type” dan/atau “interface” yang kita tulis di Typescript akan hilang ketika di-<em>transpile</em>. Jadi serumit apapun “type” yang kita buat, nggak akan berarti apa-apa ketika <em>run time</em> karena semuanya akan dihapus: <em>zero overhead</em>. Output code-nya pun bisa terbaca jelas 😃</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lxul3Pw7AL1qN8leeRqqGw.png" /><figcaption>Sebelah kiri TS, sebelah kanan output JS-nya</figcaption></figure><p>Gambar ini semakin menunjukkan bahwa Typescript hanyalah Javascript yang diberi type. Kalau penasaran dan mau explore lebih jauh, bisa main-main <a href="http://www.typescriptlang.org/play/#src=interface%20ProductModel%20%7B%0D%0A%20%20id%3A%20number%3B%0D%0A%20%20name%3A%20string%3B%0D%0A%20%20price%3A%20number%3B%0D%0A%20%20tax%3A%20number%0D%0A%7D%0D%0A%0D%0Aconst%20getFinalPrice%20%3D%20(product%3A%20ProductModel)%20%3D%3E%0D%0A%20%20product.price%20%2B%20product.tax%3B%0D%0A%0D%0Aconsole.log(%0D%0A%20%20getFinalPrice(%7B%20id%3A%201%2C%20name%3A%20&#39;A&#39;%2C%20price%3A%201%2C%20tax%3A%200.5%20%7D)%0D%0A)%3B">ke TS playground</a>.</p><h4>5. Inference 🧠</h4><p>Beberapa dari kita mungkin pernah berasumsi: “hmm biasanya kalo bahasa yang ada <em>type</em> nya itu terlalu <em>verbose</em>, semua perlu kita kasih type!”. Eit tunggu dulu, di beberapa kasus, <em>Typescript does that for you</em>.</p><pre><strong>const</strong> name: string = &#39;Jihad&#39;;<br><strong>const</strong> name2 = &#39;Jihad&#39;;</pre><p>name2 akan secara otomatis bertipe string tanpa perlu melakukan <em>type assertion </em>seperti name. Pun dengan fungsi getFinalPrice tadi, TS meng-infer-nya dengan:</p><pre><strong>const</strong> getFinalPrice: (product: ProductModel) =&gt; number</pre><p>padahal kita tidak pernah men-<em>declare</em> <em>return type</em>-nya. Contoh lain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XuDRwt4sn-cMi4ImDic5gg.png" /><figcaption>TS Object Inference</figcaption></figure><p>Kita tahu bahwa kita “tidak bisa” mengubah value dari object yang di-define di dalam Object.freeze, TS pun meng-infer-nya dengan type Readonly plus bonus <em>key name</em> dengan <em>value type</em> nya! How nice!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Ftypescript-whi4py%3Fembed%3D1%26file%3Dinference.ts%26hideExplorer%3D1%26hideNavigation%3D1%26view%3Deditor&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Ftypescript-whi4py%3Fembed%3D1%26file%3Dinference.ts%26hideExplorer%3D1%26hideNavigation%3D1%26view%3Deditor&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6c3cc3275d7f8badc225b796d57ce9b/href">https://medium.com/media/b6c3cc3275d7f8badc225b796d57ce9b/href</a></iframe><blockquote>A good language is when the compiler helps you, not you helping the compiler</blockquote><h4>6. Tooling 🛠</h4><p>Ini dia nih yang gak kalah penting, <em>tooling</em>! Tooling bisa menjadi salah satu faktor terbesar sebuah bahasa pemrograman agar dapat diadopsi dengan mudah secara luas. Bentuk tooling yang paling umum adalah kemudahan konfigurasi di text editor. Untungnya, TS sudah di-support by <em>default</em> oleh text editor yang super kece: VS Code!</p><pre>1. install VS Code<br>2. mkdir new-project<br>3. cd new-project<br>4. npm i -D typescript<br>5. tsc --init<br>6. Enjoy! 🎉</pre><p>Terlebih VS Code support code intellisense yang memberikan kita rekomendasi type yang kompatible seperti contoh di bawah ini:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n_Kl3sVk9m1bxuoNzrTCbg.png" /><figcaption>intellisense</figcaption></figure><p>Pun ketika melakukan refactoring: misal saya ingin mengubah nama attribute di dalam interface ProductModel dari id menjadi productId. Ketika kita Klik Kanan -&gt; Rename Symbol, semua variable dan data yang dianggap oleh Typescript bertipe ProductModel[&#39;id&#39;], akan berubah namanya menjadi ProductModel[&#39;productId&#39;] dimanapun ia berada, walaupun digunakan di banyak file.</p><h4>7. Supports JSX by Default 🎗</h4><p>Buat kamu-kamu developer React (kayak saya), gak perlu cemas karena TS secara <em>default</em> sudah support JSX. Sebagai bukti yang valid, bisa langsung <a href="https://github.com/Microsoft/TypeScript/blob/07966dcb124ee379a4f062c1032fec0a6c4eaf19/src/compiler/types.ts#L403-L413">dicek ke source code compiler Typescript itu sendiri</a> 😛</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O5jYX_mAkGn_CB-n48GzAQ.png" /><figcaption>React in TS</figcaption></figure><p>Syaratnya cuman satu, file ini harus disimpan dengan extension .tsx.</p><h3>Kesimpulan</h3><p>Menurut saya pribadi, Typescript akan sangat sangat membantu jika scope projek kita cukup besar dan dikembangkan bersama oleh banyak developer. Komunikasi bisa terbantu lewat type dan interface. Ketika ada perubahan struktur data (misal response dari suatu endpoint berubah), refactor akan sangat mudah karena kita akan di-guide oleh Typescript. Bisa dicari dengan kata kunci “Type Driven Development”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a8721e37d3fa0e2eb6372f4ba6a1315/href">https://medium.com/media/6a8721e37d3fa0e2eb6372f4ba6a1315/href</a></iframe><p>Code kita pun akan terdokumentasi dengan baik seperti contoh di atas. DeliveryTimeResponse adalah bentuk object response dari suatu endpoint. Kita ndak perlu test manual dan mengingat-ingat bagaimana bentuk response-nya dari server. Cukup lihat interface saja. Ketika ada perubahan bentuk pun kita cukup ubah interface dan sesuaikan di function transformDeliveryTimeReponse. All nice and clean 🛀🏻</p><p>So, gunakanlah Typescript 😄</p><p><em>If you find this article useful, hit the green clap so you can help others discover the article </em>👏🏻</p><p>Semoga bermanfaat 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9914c7c14793" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codewey/mengapa-typescript-9914c7c14793">Mengapa Typescript?</a> was originally published in <a href="https://medium.com/codewey">codewey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>