<?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[Stories by Tiara Dewangga on Medium]]></title>
        <description><![CDATA[Stories by Tiara Dewangga on Medium]]></description>
        <link>https://medium.com/@ktiarad?source=rss-3eb2e6c2ec38------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*N_1AeLwcKzf-q897RPI66Q.jpeg</url>
            <title>Stories by Tiara Dewangga on Medium</title>
            <link>https://medium.com/@ktiarad?source=rss-3eb2e6c2ec38------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 11:35:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ktiarad/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Clean Code: My Notes]]></title>
            <link>https://medium.com/@ktiarad/clean-code-my-notes-2a289cbe97cc?source=rss-3eb2e6c2ec38------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a289cbe97cc</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Tiara Dewangga]]></dc:creator>
            <pubDate>Fri, 29 Sep 2023 16:12:36 GMT</pubDate>
            <atom:updated>2023-09-29T16:12:36.956Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z3ysJC4NVoisD-ff" /><figcaption>Photo by <a href="https://unsplash.com/@oskaryil?utm_source=medium&amp;utm_medium=referral">Oskar Yildiz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hi, I’m Tiara.</p><p>I’ve finished reading Clean Code by Uncle Bob, and I want to create my own notes based on it. I won’t summarize the entire book in this one-page article. Instead, I’ll share the key takeaways I’ve gained from it.</p><p>While I don’t consider this book to be the definitive guide for creating clean code since it largely reflects Uncle Bob’s preferences, it does raise awareness about the importance of writing clean code. The main point here is that clean code enhances code readability, which in turn leads to maintainable code and improved productivity.</p><p>Since I’m currently working with Go, I don’t think that all the suggestions from this book are directly applicable to my tasks. The book is based on Java, which, of course, has different characteristics compared to Go.</p><p>These are the notes I will use on a daily basis, and I have also included my perspectives and preferences.</p><h3>Naming</h3><ul><li>Use descriptive name<br>I believe that this point is emphasized the most: “Names in software are 90 percent of what make software readable.” Let’s consider the following code examples. The variable p reveals nothing. Despite having a comment explaining its purpose, it can reduce the readability of overall codes. In Example 2, those variables clearly describe their intended functions.</li></ul><pre>// Example 1<br>var p float64 // final price<br><br>// Example 2<br>var basePrice float64<br>var totalDiscount float64<br>var finalPrice float64</pre><ul><li>Avoid disinformation<br>Avoid ambiguous names; be clear about what the variable, class, or function truly does. Don’t overuse abbreviation, such as r for radius and w for width, except they are commonly used such as ctx for context in Go.</li><li>Use pronounceable and searchable names<br>Coding may seem like an individual task, but in a collaborative team, it becomes a social activity. Use names that are easy to pronounce to facilitate communication.</li></ul><h3>Functions</h3><ul><li>Single Responsibility Principle<br>A function should have a single, clearly defined responsibility indicated by its name. For instance, getUserData() should exclusively return user data without performing other tasks. Don’t hide side effects within the name of a function. Take a look at this example. This function should only update transaction status, but it also sends email to user. Furthermore, the returned result originates from SendEmailToUser(), which it is supposed to be UpdateTransactionData() . This example violates Single Responsibility Principle.</li></ul><pre>func (s *service) updateTransactionStatus(ctx context.Context, <br>  transaction UpdateTransactionRequest) (<br>  result UpdateTransactionResponse, err error) {<br>  result, err := s.UpdateTransactionData(ctx, transaction)<br>  if err != nil {<br>    return result, err<br>  }<br>  <br>  result, err := s.SendEmailToUser(ctx, transaction)<br>  if err != nil {<br>    return result, err<br>  }<br>  <br>  return result, err<br>}</pre><ul><li>As small as possible<br>A small function simplifies the creation of unit tests and facilitates the early detection of potential bugs. This principle is closely connected to the Single Responsibility Principle.</li><li>Number of arguments<br>It’s advisable to limit the number of arguments for a function. The most recommended are niladic functions (with no arguments), followed by monadic functions (with one argument) and dyadic functions (with two arguments). It’s best to avoid triadic functions (with three arguments) whenever possible. Fewer arguments simplify testing and reduce the chances of input errors due to argument swapping.<br>In Go, it’s advisable to include the context as an argument. We can manage function complexity and limit the number of arguments to a maximum of two whenever possible. This recommendation also applies to multiple return values in Go. While returning two values like return result, err is acceptable, for three or more values, it’s preferable to wrap them in a single struct. Regardless, always choose descriptive names that clearly convey the intention of each return value.</li></ul><pre>// not recommended<br>func createTransaction(ctx context.Context, <br>  userID int,<br>  transactionType string,<br>  description string,<br>  amount float64) (err error, status string, endingAmount float64) {<br>  // ...<br>}<br><br>// recommended<br>func createTransaction(ctx context.Context, <br>  transactionData CreateTransactionRequest) <br>  (err error, result CreateTransactionResponse) {<br>  // ...<br>}</pre><ul><li>Expected arguments<br>Always manage to use the expected arguments. Consider this example. The second example may seem exaggerated, but we sometimes unconsciously overuse arguments.</li></ul><pre>// expected argument<br>func isValidUser(userID int) bool {<br>  // process<br>}<br><br>// unexpected arguments<br>func isValidUser(userID int, numberOfFriend int) (isValid bool, friendIDs []int) {<br>  // process<br>}</pre><h3>Comments</h3><ul><li>Unused and dead code<br>Delete unused functions unless there is a clear comment explaining why it’s beneficial to keep them.</li><li>Redundant comment<br>“Comment should say things that the code cannot say for itself.” See the following example of redundant comment.</li></ul><pre><br>i += 1 // increment of i</pre><ul><li>Explanation of intent<br>I think it’s acceptable to use comments to provide an outline of the flow or important information for others to understand the code. However, it’s crucial to avoid unnecessary comments. According to Uncle Bob, comment can be used to provide the intent behind a decision. See the examples below. Additionally, comments can serve to alert others about the potential consequences of running specific functions.</li></ul><pre>// ===== NOT RECOMMENDED ======<br>// iterate over the list of user ID<br>for _, id := range userIDs {<br>  // do something with id<br>}<br><br>// the day after tomorrow<br>var dayAfterTomorrow string<br><br>// ===== RECOMMENDED =====<br>// sometimes the clients don&#39;t get the callback, so we need to resend it<br>result, err := resendCallback(ctx, request)</pre><ul><li>Journal comments<br>Rather than including all changes, logs, and contributors at the start of the code, Uncle Bob prefers to omit this information, relying on version control systems for tracking these details.</li><li>Out-of-update comment<br>Sometimes, the next developer may not be aware of existing comments, and when they make changes, these comments often go unmodified. It’s important to be mindful of comments that require regular updates. If the naming or logic of the code is clear enough on its own, consider deleting these comments.</li></ul><h3>General</h3><ul><li>Follow coding standard conventions<br>If the team follows industry conventions, adhere to them.</li><li>Replace magic numbers with constants<br>However, there are cases where using magic numbers is acceptable, especially when calculations involve well-known measurements. For less common numbers, constants are a better choice.</li></ul><pre>// using magic numbers vs consts; magic number here is more preferable<br>totalSeconds = days * 24 * 60 * 60<br>totalSeconds = days * HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE<br><br>// using magic numbers vs consts; const is more preferable<br>remainingTimeOff = 20 - takenTimeOff<br>remainingTimeOff = MAX_TIME_OFF - takenTimeOff</pre><ul><li>Vertical separation<br>In Go, it’s common practice to define variables and functions close to where they are used. For instance, the declaration of latestTransaction is placed before its assignment, rather than declaring it at the very beginning of the program.</li></ul><pre>transactionList, err := repository.GetTransactionList(ctx, ID)<br>if err != nil {<br>  return response, err<br>}<br><br>var latestTransaction Transaction<br>latestTransaction = transactionList[len(transactionList)-1]</pre><ul><li>Be consistent<br>Once you’ve selected a convention, maintain consistency throughout your codebase to prevent confusion. If you opt for the term Userstick with it consistently and avoid introducing Customerin the middle of your code unless they represent distinct concepts.</li><li>Selector arguments<br>Instead passing true or false as argument to select the behavior, it’s preferable to create separate functions to handle each behavior.</li><li>Use explanatory variables<br>In many cases, splitting code into multiple lines can improve readability, but it should be done thoughtfully. The choice between one-liners and multiline code depends on the specific context and what makes the code more understandable. The following example maybe too simple to be broken down into multiple lines, but the idea is to clarify the logic so the other will get it easily.</li></ul><pre>// one line<br>price := basePrice - (basePrice * discount) + (basePrice * tax)<br><br>// multiple lines<br>priceAfterDiscount := basePrice - (price * discount)<br>finalPrice := priceAfterDiscount - (price * tax)</pre><p>While there’s more to discuss, I’ll save it for the next article. It’s perfectly fine if we don’t always agree with Uncle Bob (or maybe don’t agree with me). Our ultimate goal is clear: clean code. Every programmer has their own style, but it’s essential to ensure that the code remains understandable to others.</p><p>That’s all for now, see you in the next article! Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a289cbe97cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tutorial Laravel Dasar: Siap Sekejap Membuat Authentication dan CRUD]]></title>
            <link>https://medium.com/@ktiarad/tutorial-laravel-dasar-siap-sekejap-membuat-authentication-dan-crud-8b0a2a907025?source=rss-3eb2e6c2ec38------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b0a2a907025</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Tiara Dewangga]]></dc:creator>
            <pubDate>Sat, 03 Jun 2023 16:04:29 GMT</pubDate>
            <atom:updated>2023-06-03T16:04:29.042Z</atom:updated>
            <content:encoded><![CDATA[<p>Halo, aku Tiara.</p><p>Di sini aku mau sharing catatan tentang tutorial Laravel dasar, terutama authentication dan CRUD (Create Read Update Delete) dengan studi kasus toko serba ada. Tutorial ini berfokus pada step by step membangun aplikasi dengan tingkat kesulitan dasar hingga medium, diharapkan pembaca sudah memiliki pemahaman dasar mengenai PHP dan database MySQL atau MariaDB. Konsep detail dari beberapa bagian mungkin akan dijelaskan di artikel terpisah agar artikel tidak terlalu panjang.</p><h3>Persiapan</h3><p>Sebelum memulai tutorial, pastikan sudah memiliki web server local seperti XAMPP. Pastikan juga sudah memiliki Composer sebagai package manager PHP. Composer bisa diunduh di sini.</p><p><a href="https://getcomposer.org/">Composer</a></p><p>Pada tutorial kali ini, kita akan membutuhkan npm (Node Package Manager) yaitu package manager berbasis JavaScript, yang bisa diunduh di sini.</p><p><a href="https://nodejs.org/en">Node.js - Run JavaScript Everywhere</a></p><blockquote>Jika setelah instalasi npm command berikut npm -vtidak bisa berjalan, silahkan tutup terminal (command prompt) dan buka lagi. Jika terminal dibuka di aplikasi VS Code, maka tutup dulu aplikasi VS Code, lalu buka kembali. Pengecekan versi biasanya dilakukan untuk memastikan bahwa suatu package telah terpasang dengan benar.</blockquote><p>Pastikan XAMPP dapat berjalan, terutama pada modul Apache dan MySQL. Silahkan masuk ke dashboard phpmyadmin dan buat database baru. Pada tutorial ini akan menggunakan nama database toko.</p><p>Buka terminal, arahkan ke folder yang diinginkan, lalu install Laravel dengan perintah berikut. Versi yang digunakan pada tutorial ini adalah Laravel versi 8.*.</p><pre>composer create-project --prefer-dist laravel/laravel=&quot;8.*&quot; toko</pre><p>toko di perintah tersebut merujuk pada nama project. Setelah perintah tersebut dijalankan, maka akan muncul folder dengan nama toko.</p><p>Silahkan buka text editor dan arahkan ke folder toko. Text editor yang disarankan adalah Visual Studio Code. Cek file .env . Lakukan konfigurasi database pada field yang memiliki prefix DB_ . Ubah nama database menjadi nama database yang tadi kita buat.</p><pre>DB_DATABASE=membership</pre><p>Silahkan ubah juga nama aplikasi pada field APP_NAME , misalnya &quot;Toko Kue&quot; .</p><p>Setelah persiapan selesai, silahkan coba jalankan aplikasi dengan perintah php artisan serve . Jika sudah berjalan sesuai ekspektasi, maka kita bisa lanjut ke step berikutnya.</p><h3>Authentication</h3><p>Pertama-tama, kita akan membuat Authentication terlebih dahulu. Kita tidak perlu membangun fitur Authentication dari awal karena Laravel sudah menyiapkan starter kit-nya yaitu Breeze. Penjelasan detail dari Breeze bisa dilihat di dokumentasi berikut.</p><p><a href="https://laravel.com/docs/10.x/starter-kits#laravel-breeze">Laravel - The PHP Framework For Web Artisans</a></p><p>Install Breeze terlebih dahulu pada folder project dengan perintah berikut.</p><pre>composer require laravel/breeze --dev</pre><p>Kemudian, arahkan terminal ke folder project lalu jalankan perintah berikut.</p><pre>php artisan breeze:install<br> <br>php artisan migrate<br>npm install<br>npm run dev</pre><p>Silahkan masuk ke web dengan endpoint /login (ditambahkan setelah address). Beberapa pengguna menemui tampilan berikut setelah install Breeze dimana tampilan tidak sesuai dengan ekspektasi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MzqfHwkq368jY7iipYSD-w.png" /><figcaption>Tampilan ketika login</figcaption></figure><p>Jika menemui kendala tersebut, silahkan ganti ikuti solusi yang terdapat di Stack Overflow berikut.</p><p><a href="https://stackoverflow.com/a/73478156">JetStream CSS and JS not working and showing @vite([&#39;resources/css/app.css&#39;, &#39;resources/js/app.js&#39;])</a></p><p>Apabila sudah berhasil, maka tampilan Login akan menjadi seperti ini.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hFg3tROBMQ2SPAvz1YOwIA.png" /><figcaption>Tampilan Login Breeze</figcaption></figure><p>Silahkan masuk ke endpoint /register terlebih dahulu, lalu isi form untuk membuat data user. Setelah register, maka kita akan otomatis login dan langsung diarahkan ke dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QSjo3HYtO_ktdpv2tpOpHA.png" /><figcaption>Tampilan Register Breeze</figcaption></figure><h3>CRUD</h3><h4>Model</h4><p>Kita siapkan tabelnya terlebih dahulu.</p><pre>php artisan make:migration create_customers_table</pre><p>File yyyy_mm_dd_hhmmss_create_customers_table.php akan ter-generate di folder database/migrations. Masuk ke file tersebut dan lakukan modifikasi pada method up() dan down() .</p><pre>public function up()<br>{<br>    Schema::create(&#39;customers&#39;, function (Blueprint $table) {<br>        $table-&gt;bigIncrements(&#39;id&#39;);<br>        $table-&gt;string(&#39;email&#39;)-&gt;unique();<br>        $table-&gt;string(&#39;name&#39;, 100);<br>        $table-&gt;string(&#39;address&#39;, 100);<br>        $table-&gt;integer(&#39;age&#39;);<br>        $table-&gt;timestamps();<br>        $table-&gt;softDeletes();<br>    });<br><br>    DB::table(&#39;customers&#39;)-&gt;insert(<br>        [<br>            [<br>                &#39;email&#39; =&gt; &#39;dinda@email.com&#39;,<br>                &#39;name&#39; =&gt; &#39;Dinda&#39;,<br>                &#39;address&#39; =&gt; &#39;Palembang&#39;,<br>                &#39;age&#39; =&gt; 23<br>            ],<br>            [<br>                &#39;email&#39; =&gt; &#39;dandi@email.com&#39;,<br>                &#39;name&#39; =&gt; &#39;Dandi&#39;,<br>                &#39;address&#39; =&gt; &#39;Pekanbaru&#39;,<br>                &#39;age&#39; =&gt; 20<br>            ]<br>        ]<br>    );<br>}<br><br>public function down()<br>{<br>    Schema::dropIfExists(&#39;customers&#39;);<br>}</pre><p>Lakukan migrasi hanya di tabel customers dengan perintah berikut.</p><pre>php artisan migrate:refresh --path=/database/migrations/yyyy_mm_dd_hhmmss_create_customers_table.php</pre><p>Cek database dan pastikan table customers sudah terbuat.</p><p>Kita siapkan model Customer dengan perintah berikut.</p><pre>php artisan make:model Customer</pre><p>Model akan ter-generate di folder /app/Models . Agar bisa menggunakan method soft delete, maka impor class SoftDeletes berikut sehingga baris model menjadi sebagai berikut.</p><pre>namespace App\Models;<br><br>use Illuminate\Database\Eloquent\Factories\HasFactory;<br>use Illuminate\Database\Eloquent\Model;<br>use Illuminate\Database\Eloquent\SoftDeletes; // import SoftDeletes<br><br>class Customer extends Model<br>{<br>    use HasFactory;<br>    use SoftDeletes; // menggunakan class SoftDeletes<br>}</pre><h4>Controller</h4><p>Lalu siapkan controller CustomerController dengan perintah berikut.</p><pre>php artisan make:controller CustomerController</pre><p>Controller akan ter-generate di folder /app/Http/Controllers .</p><p>Pada bagian awal CustomerControllers kita akan mengimpor model Controller, sehingga baris awal file CustomerController.php kurang lebih akan menjadi seperti ini.</p><pre>namespace App\Http\Controllers;<br><br>use Illuminate\Http\Request;<br>use App\Models\Customer; // model yang diimpor</pre><p>Kita akan menyiapkan routes. Silahkan buka file /routes/web.php . Tambahkan CustomerController untuk diimpor sehingga route bisa mengakses controller tersebut. Baris awal file kurang lebih akan menjadi seperti ini.</p><pre>use Illuminate\Support\Facades\Route;<br>use App\Http\Controllers\CustomerController;</pre><p>Tambahkan routes berikut.</p><pre>// Create<br>Route::get(&#39;/create-customer&#39;, [CustomerController::class, &#39;createCustomer&#39;])-&gt;name(&#39;create&#39;);<br>Route::post(&#39;/insert-customer&#39;, [CustomerController::class, &#39;insertCustomer&#39;])-&gt;name(&#39;insert&#39;);<br><br>// Read<br>Route::get(&#39;/&#39;, [CustomerController::class, &#39;getCustomers&#39;])-&gt;middleware([&#39;auth&#39;])-&gt;name(&#39;dashboard&#39;);<br>Route::get(&#39;/dashboard&#39;, [CustomerController::class, &#39;getCustomers&#39;])-&gt;middleware([&#39;auth&#39;])-&gt;name(&#39;dashboard&#39;);<br><br>// Update<br>Route::patch(&#39;/save-customer/{customer_id}&#39;, [CustomerController::class, &#39;updateCustomer&#39;])-&gt;name(&#39;save&#39;);<br>Route::get(&#39;/update-customer/{customer_id}&#39;, [CustomerController::class, &#39;showFormUpdate&#39;])-&gt;name(&#39;update&#39;);<br><br>// Delete<br>Route::delete(&#39;/delete-customer/{customer_id}&#39;, [CustomerController::class, &#39;deleteCustomer&#39;])-&gt;name(&#39;delete&#39;);</pre><p>Terdapat perubahan pada route / .</p><pre>// Ganti baris berikut<br>Route::get(&#39;/&#39;, function () {<br>    return view(&#39;welcome&#39;);<br>});<br><br>// Menjadi baris berikut<br>Route::get(&#39;/&#39;, [CustomerController::class, &#39;getCustomers&#39;])-&gt;middleware([&#39;auth&#39;])-&gt;name(&#39;dashboard&#39;);</pre><p>Berikut code yang dipakai untuk CustomerController .</p><pre>class CustomerController extends Controller<br>{<br>    public function getCustomers() {<br>        $customers = Customer::all();<br><br>        return view(&#39;customer.list&#39;)-&gt;with(compact(&#39;customers&#39;));<br>    }<br><br>    public function createCustomer() {<br>        return view(&#39;customer.form&#39;);<br>    }<br><br>    public function insertCustomer(Request $request) {<br>        $customer = new Customer();<br><br>        $customer-&gt;name = $request-&gt;name;<br>        $customer-&gt;email = $request-&gt;email;<br>        $customer-&gt;address = $request-&gt;address;<br>        $customer-&gt;age = $request-&gt;age;<br><br>        $customer-&gt;save();<br><br>        return redirect(&#39;/dashboard&#39;);<br>    }<br><br>    public function showFormUpdate($customer_id) {<br>        $customer = Customer::find($customer_id);<br><br>        return view(&#39;customer.edit&#39;)-&gt;with(compact(&#39;customer&#39;));<br>    }<br><br>    public function updateCustomer(Request $request, $customer_id) {<br>        $customer = Customer::find($customer_id);<br><br>        $customer-&gt;name = $request-&gt;name;<br>        $customer-&gt;email = $request-&gt;email;<br>        $customer-&gt;address = $request-&gt;address;<br>        $customer-&gt;age = $request-&gt;age;<br><br>        $customer-&gt;save();        <br><br>        return redirect(&#39;/dashboard&#39;);<br>    }<br><br>    public function deleteCustomer($customer_id) {<br>        Customer::where(&#39;id&#39;,$customer_id)-&gt;delete();<br><br>        return redirect(&#39;/dashboard&#39;);<br>    }<br>}</pre><h4>View</h4><p>Kita akan menyiapkan tampilan untuk dashboard. Karena tabel yang ditampilkan menggunakan Bootstrap, maka tambahkan baris berikut di file /resources/views/layouts/app.blade.php dalam tag &lt;head&gt;&lt;/head&gt; .</p><pre>&lt;link href=&quot;https://getbootstrap.com/docs/4.0/dist/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot;&gt;</pre><p>Proses CRUD akan dijalankan di dashboard. Tambahkan baris berikut pada file /resources/views/dashboard.blade.php setelah tag &lt;div class=&quot;py-12&quot;&gt;&lt;/div&gt;</p><pre>&lt;div class=&quot;py-12&quot;&gt;<br>    &lt;div class=&quot;max-w-7xl mx-auto sm:px-6 lg:px-8&quot;&gt;<br>        &lt;div class=&quot;bg-white overflow-hidden shadow-sm sm:rounded-lg&quot;&gt;<br>            &lt;div class=&quot;p-6 bg-white border-b border-gray-200&quot;&gt;<br>                @yield(&#39;content&#39;)<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/div&gt;</pre><p>Pada folder views kita buat folder baru yaitu customer . Tambahkan beberapa file views.</p><p>/resources/views/customer/list.blade.php</p><pre>@extends(&#39;dashboard&#39;)<br><br>@section(&#39;content&#39;)<br>&lt;div class=&quot;container&quot;&gt;<br>  &lt;div class=&quot;row&quot;&gt;<br>  &lt;h2&gt;Section title&lt;/h2&gt;<br>    &lt;a href=&quot;{{ route(&#39;create&#39;) }}&quot; class=&quot;btn btn-primary&quot;&gt;Create New&lt;/a&gt;<br>    &lt;div class=&quot;table-responsive&quot;&gt;<br>      &lt;table class=&quot;table table-striped table-sm&quot;&gt;<br>        &lt;thead&gt;<br>          &lt;tr&gt;<br>            &lt;th&gt;Name&lt;/th&gt;<br>            &lt;th&gt;Email&lt;/th&gt;<br>            &lt;th&gt;Address&lt;/th&gt;<br>            &lt;th&gt;Usia&lt;/th&gt;<br>            &lt;th&gt;Action&lt;/th&gt;<br>          &lt;/tr&gt;<br>        &lt;/thead&gt;<br>        &lt;tbody&gt;<br>          @foreach ($customers as $customer)<br>          &lt;tr&gt;<br>            &lt;td&gt;{{ $customer-&gt;name }}&lt;/td&gt;<br>            &lt;td&gt;{{ $customer-&gt;email }}&lt;/td&gt;<br>            &lt;td&gt;{{ $customer-&gt;address }}&lt;/td&gt;<br>            &lt;td&gt;{{ $customer-&gt;age }}&lt;/td&gt;<br>            &lt;td&gt;<br>                &lt;a href=&quot; {{ route(&#39;update&#39;, [&#39;customer_id&#39;=&gt;$customer-&gt;id] ) }}&quot; class=&quot;btn btn-warning&quot;&gt;Update&lt;/a&gt;<br>                &lt;form action=&quot;{{ route(&#39;delete&#39;, [&#39;customer_id&#39;=&gt;$customer-&gt;id] ) }}&quot; method=&quot;POST&quot;&gt;<br>                  @csrf<br>                  @method(&#39;DELETE&#39;)<br>                  &lt;button type=&quot;submit&quot; class=&quot;btn btn-danger&quot;&gt;Delete&lt;/button&gt;<br>                &lt;/form&gt;<br>            &lt;/td&gt;<br>          &lt;/tr&gt;<br>          @endforeach<br>        &lt;/tbody&gt;<br>      &lt;/table&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;<br>@endsection</pre><p>/resources/views/customer/form.blade.php</p><pre>@extends(&#39;dashboard&#39;)<br><br>@section(&#39;content&#39;)<br>&lt;div class=&quot;container&quot;&gt;<br>        &lt;form method=&quot;POST&quot; action=&quot;{{ route(&#39;insert&#39;) }}&quot;&gt;<br>        @csrf<br>        &lt;div class=&quot;form-group&quot;&gt;<br>            &lt;label for=&quot;exampleInputEmail1&quot;&gt;Name&lt;/label&gt;<br>            &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;exampleInputEmail1&quot; aria-describedby=&quot;emailHelp&quot; placeholder=&quot;Enter name&quot; name=&quot;name&quot;&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;form-group&quot;&gt;<br>            &lt;label for=&quot;exampleInputEmail1&quot;&gt;Email&lt;/label&gt;<br>            &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;exampleInputEmail1&quot; aria-describedby=&quot;emailHelp&quot; placeholder=&quot;Enter email&quot; name=&quot;email&quot;&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;form-group&quot;&gt;<br>            &lt;label for=&quot;exampleInputEmail1&quot;&gt;Address&lt;/label&gt;<br>            &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;exampleInputEmail1&quot; aria-describedby=&quot;emailHelp&quot; placeholder=&quot;Enter address&quot; name=&quot;address&quot;&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;form-group&quot;&gt;<br>            &lt;label for=&quot;exampleInputEmail1&quot;&gt;Age&lt;/label&gt;<br>            &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;exampleInputEmail1&quot; aria-describedby=&quot;emailHelp&quot; placeholder=&quot;Enter age&quot; name=&quot;age&quot;&gt;<br>        &lt;/div&gt;<br><br>        &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;Submit&lt;/button&gt;<br>        &lt;/form&gt;        <br>&lt;/div&gt;<br><br>@endsection</pre><p>/resources/views/customer/edit.blade.php</p><pre>@extends(&#39;dashboard&#39;)<br><br>@section(&#39;content&#39;)<br>&lt;div class=&quot;container&quot;&gt;<br>        &lt;form method=&quot;POST&quot; action=&quot;{{ route(&#39;save&#39;, [&#39;customer_id&#39; =&gt; $customer-&gt;id]) }}&quot;&gt;<br>        @method(&#39;patch&#39;)<br>        @csrf<br>        &lt;div class=&quot;form-group&quot;&gt;<br>            &lt;label for=&quot;exampleInputEmail1&quot;&gt;Name&lt;/label&gt;<br>            &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;exampleInputEmail1&quot; aria-describedby=&quot;emailHelp&quot; placeholder=&quot;Enter email&quot; name=&quot;name&quot; value=&quot;{{ $customer-&gt;name }}&quot;&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;form-group&quot;&gt;<br>            &lt;label for=&quot;exampleInputEmail1&quot;&gt;Email&lt;/label&gt;<br>            &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;exampleInputEmail1&quot; aria-describedby=&quot;emailHelp&quot; placeholder=&quot;Enter email&quot; name=&quot;email&quot; value=&quot;{{ $customer-&gt;email }}&quot;&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;form-group&quot;&gt;<br>            &lt;label for=&quot;exampleInputEmail1&quot;&gt;Address&lt;/label&gt;<br>            &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;exampleInputEmail1&quot; aria-describedby=&quot;emailHelp&quot; placeholder=&quot;Enter email&quot; name=&quot;address&quot; value=&quot;{{ $customer-&gt;address }}&quot;&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;form-group&quot;&gt;<br>            &lt;label for=&quot;exampleInputEmail1&quot;&gt;Age&lt;/label&gt;<br>            &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;exampleInputEmail1&quot; aria-describedby=&quot;emailHelp&quot; placeholder=&quot;Enter email&quot; name=&quot;age&quot; value=&quot;{{ $customer-&gt;age }}&quot;&gt;<br>        &lt;/div&gt;<br><br>        &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;Submit&lt;/button&gt;<br>        &lt;/form&gt;        <br>&lt;/div&gt;<br><br>@endsection</pre><p>Silahkan coba aplikasi. Coba untuk register, login, read data, create data, update data, dan delete data.</p><p>Demikianlah tutorial dari pembuatan aplikasi sederhana ini. Tentu aplikasi bisa dikembangkan lebih kompleks sesuai dengan kebutuhan. Jika ada pertanyaan atau masukan, saya akan senang menerimanya. Terima kasih ^^</p><blockquote>Fyi judul “Siap Sekejap” merujuk pada majalah memasak “Sedap Sekejap” yang banyak peminatnya sekitar tahun 2000-an.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b0a2a907025" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object Oriented Programming: A Relearn Note]]></title>
            <link>https://medium.com/@ktiarad/object-oriented-programming-a-relearn-note-3c6f6e93f38d?source=rss-3eb2e6c2ec38------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c6f6e93f38d</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Tiara Dewangga]]></dc:creator>
            <pubDate>Sun, 21 May 2023 06:05:05 GMT</pubDate>
            <atom:updated>2023-05-23T15:30:58.841Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi, it’s Tiara!</p><p>Since I wanted to relearn about Object Oriented Programming (OOP) then I try to write notes about it. Feel free to give advice, do correction about my explanation, or give improvement to my writing.</p><p>In my opinion, the best programming language to learn OOP is Java, since it implements almost all the OOP object in general. Other programming languages also provide OOP concepts with their own style such as PHP, Go, Python, etc. For this note, I prefer to use Java.</p><h3>Class and Object</h3><p>Class is a template or a blueprint for an object. Then, object is an instance of a class. Since class works as a blueprint, then it can’t be manipulated. If we want to work with data or execute the functions in a class, then this class need to be instantiated as an object.</p><p>A class typically consists of:</p><ol><li>Attributes: variables (properties) of a class, the data can be stored in each instance;</li><li>Methods: functions (behaviors) of a class;</li><li>Constructors: initialization of a class, when a class is instantiated, then these initialization will setup default values to the object’s attributes;</li><li>Access modifiers: such as public, private, or protected; which control the visibility and accessibility of class members. Public allows a properties or methods can be accessed outside the class, private only allows in that class, while protected allows only the child of that class.</li></ol><p>As example, imagine a building construction. The blueprint defines the specification and functionality that all buildings should have. This blueprint is the class. Then, the building is constructed from the blueprint, and this building can be anything, it can be a home, school, hospital, etc. Therefore, these buildings are the objects.</p><p>Here is the example of a class.</p><pre>public class Building {<br>    // Attributes<br>    String buildingType;<br>    int width;<br>    int length;<br>    String location;<br><br>    // Methods<br>    void build() {<br>      // Code to build the building<br>    }<br><br>    void renovate() {<br>      // Code to renovate the building<br>    }<br>}</pre><p>To build the real building, then we need to instantiate the class Building .</p><pre>Building school = new Building();</pre><p>Sometimes, we use the term “implementation,” such as “object is the implementation of class.” Note that implementation and instantiation have different meaning in OOP. Implementation provides the actual code of a class or an interface (which will be explained later). On the other hand, instantiation is the process of creating an object (instance) of a class. In this context, we use the term “instantiation.”</p><h3>This</h3><p>this refers to the current object/instance of a class. When we want to refer an instance variable (attribute) in a class, we use this . Without this then we refer to a local variable in a method.</p><h3>Basic Fundamental of OOP</h3><h4>Inheritance</h4><p>This principle enables classes to inherit properties and behaviors from other classes. The one which inherits (gets the class members) is the child class, while the other one (gives the class members) is the parent class. It allows code reuse and hierarchy relationship among classes.</p><pre>public class Building {<br>    String buildingType;<br>    <br>    void build() {<br>      // Code to build the building<br>    }<br>}<br><br>public class PersonalBuilding extends Building {<br>    void rent() {<br>      // Code to self renovation<br>    }<br>}<br><br>public class BusinessBuilding extends Building {<br>    void monetize() {<br>      // Code to monetize business building<br>    }<br>}</pre><h4>Encapsulation</h4><p>It ensures that the internal state of an object is hidden and can be accessed only through well-defined interfaces. We don’t want to expose all the attributes and methods to other class, just let the data be processed inside the class.</p><pre>public class Building{<br>    private String buildingType;<br>    private int area;<br><br>    public String getBuildingType() {<br>        return buildingType;<br>    }<br><br>    public void setBuildingType(String buildingType) {<br>        this.buildingType = buildingType;<br>    }<br><br>    public int getArea() {<br>        return area;<br>    }<br><br>    public void setArea(int area) {<br>        if (age &gt;= 0) {<br>            this.area = area;<br>        } else {<br>            System.out.println(&quot;Invalid area value.&quot;);<br>        }<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        Building myBuilding = new Building();<br><br>        // Accessing private variables indirectly through getter and setter methods<br>        myBuilding.setBuildingType(&quot;House&quot;);<br>        myBuilding.setArea(120);<br><br>        System.out.println(&quot;Building Type: &quot; + myBuilding.getBuildingType());<br>        System.out.println(&quot;Area: &quot; + myBuilding.getArea());<br>    }<br>}</pre><h4>Abstraction</h4><p>It simplifies complex systems by identifying essential features and ignoring irrelevant details. Abstraction involves creating abstract class and interface.</p><p>Abstract class is a base class which needs to be implemented by other class and can’t be instantiated directly as an object. If we want to create an instance from an abstract class, then we need to create a new class which extends this abstract class, then create an instance of this new class.</p><p>Interestingly, abstract class is a combination of inheritance and abstraction. The abstract class works as a parent class, while the other classes will inherit this class.</p><pre>abstract class Building {<br>    protected int width;<br>    protected int length;<br>  <br>    public void build() {<br>       // Code to build the building<br>    }<br><br>    abstract int calculateBudget();<br>}<br><br>class PersonalBuilding extends Building {<br>    @Override <br>    int calculateBudget(){<br>      // Code to calculate budget for pesonal building<br>    }<br>}<br><br>class BusinessBuilding extends Building {<br>    @Override <br>    int calculateBudget(){<br>      // Code to calculate budget for pesonal building<br>    }<br>}</pre><p>Interface is a set of signatures. Interface is a contract that a class can implement, and a class which implements this interface have to use all the methods. If a method in an interface is not implemented, then it can cause error when compiling. Signature is an abstraction of a method, which consists the name, parameter, and return type.</p><pre>interface Building{<br>    void build();<br>    void renovate();<br>}<br><br>class PersonalBuilding implements Building{<br>    @Override<br>    public void build() {<br>        System.out.println(&quot;Build building.&quot;);<br>    }<br><br>    @Override<br>    public void renovate() {<br>        System.out.println(&quot;Renovate building.&quot;);<br>    }<br>}</pre><h4>Polymorphism</h4><p>Polymorphism refers to the ability of objects of different classes to respond to the same message (method invocation) in different ways. This principle is also used in abstraction. In abstraction, we need to override the method which is stated in abstract class or interface.</p><pre>class Building{<br>    public void build() {<br>        System.out.println(&quot;Build a building.&quot;);<br>    }<br>}<br><br>class PersonalBuilding extends Building{<br>    @Override<br>    public void build() {<br>        System.out.println(&quot;Build a personal building.&quot;);<br>    }<br>}<br><br>class BusinessBuilding extends Building {<br>    @Override<br>    public void build() {<br>        System.out.println(&quot;Build a business building.&quot;);<br>    }<br>}</pre><p>I also created some examples of these fundamentals in PHP language.</p><p><a href="https://github.com/ktiarad/basic-oop-php">GitHub - ktiarad/basic-oop-php</a></p><p>That’s all, I would be glad to hear any feedback about my relearn notes. Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c6f6e93f38d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Goroutines: Insert 1 Juta File dari CSV ke PostgreSQL]]></title>
            <link>https://medium.com/@ktiarad/goroutines-insert-1-juta-file-dari-csv-ke-postgresql-19a2668e5206?source=rss-3eb2e6c2ec38------2</link>
            <guid isPermaLink="false">https://medium.com/p/19a2668e5206</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Tiara Dewangga]]></dc:creator>
            <pubDate>Fri, 24 Feb 2023 14:43:56 GMT</pubDate>
            <atom:updated>2023-02-24T14:43:56.579Z</atom:updated>
            <content:encoded><![CDATA[<p>Halo, ini Tiara.</p><p>Saya mengikuti tutorial dari Mas Noval Agung, berikut tutorialnya.</p><p><a href="https://dasarpemrogramangolang.novalagung.com/D-insert-1mil-csv-record-into-db-in-a-minute.html">Golang Insert 1 Juta Data dari File CSV Ke Database Server, Menggunakan Teknik Worker Pool, Database Connection Pool, dan Mekanisme Failover - Dasar Pemrograman Golang</a></p><p>Saya mencoba untuk mengubah dan menambah beberapa hal selama mengikuti tutorial tersebut, di antaranya:</p><ol><li>Database menggunakan PostgreSQL</li><li>Struktur repository dibuat module package</li></ol><p>Berikut repository GitHub saya.</p><p><a href="https://github.com/ktiarad/goroutines-insert-1mil-csv-record-into-db">GitHub - ktiarad/goroutines-insert-1mil-csv-record-into-db</a></p><p>Pada tutorial Mas Noval, kita cukup bekerja dengan satu file yaitu main.go , selain go.mod dan go.sum . Di sini, saya sengaja untuk memecah package tersebut menjadi beberapa package. Repository ini terkesan lebih rumit, tetapi menurut saya cukup baik untuk belajar membuat struktur kode repository Golang.</p><p>File /config/constant.go juga menyimpan konstanta lokasi file disimpan. Untuk menjalankan program ini, maka siapkan terlebih dahulu folder /resources berisi file csv. Karena file tersebut tidak bisa diakses di <a href="http://downloads.majestic.com/majestic_million.csv">link ini</a>, maka saya mengunduhnya dari web alternatif berikut.</p><p><a href="https://datahub.io/rising.odegua/majestic-millions">Majestic millions</a></p><p>Buat database di PostgreSQL terlebih dahulu. Query-nya terdapat pada file goinsertmil.sql . Kemudian lakukan setting database di file /config/constant.go sesuai setting database Anda.</p><p>Berikut penjelasan singkat dari repository saya:</p><ul><li>config</li></ul><p>Sesuai namanya, file ini berisi konfigurasi yang terdiri dari konstanta dan fungsi untuk koneksi ke database.</p><ul><li>model</li></ul><p>Model dari Domain dideklarasikan di sini.</p><ul><li>repository</li></ul><p>Package ini berisi fungsi untuk menjalankan query ke database. Dalam InsertDomain() terdapat inisialisasi koneksi baru setiap menjalankan query INSERT untuk mencegah race condition. Parameter model Domain dalam InsertDomain() akan diubah menjadi []interface{} untuk bisa dijalankan dengan conn.ExecContext() . Function GenerateDollarsMark akan mengubah data menjadi $1, $2, ... karena PostgreSQL menggunakan format demikian, sementara MySQL menggunakan (?, ?, ...) .</p><ul><li>service</li></ul><p>Fungsi utama Goroutines akan dijalankan di package ini. Di sini, database (dalam DomainRepository ) dan sync.WaitGroup dibuat sebagai properti class ImportDataServices .</p><ul><li>main.go</li></ul><p>Pada file utama ini, terdapat inisialisasi database, repository, service, WaitGroup, dan channel. Di sini juga dijalankan go untuk DispatchWorkers , yang artinya terdapat go dalam go.</p><p>Saat mengikuti tutorial ini, saya mengalami kendala, yaitu</p><p>error connect to db: pq: sorry, too many clients already</p><p>dengan setting sebagai berikut</p><pre>DbMaxConns = 100<br>TotalWorker = 100</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*j-jQ1LE8hzh4_sqFC3xafw.png" /><figcaption>DbMaxConns = 100, TotalWorker = 100</figcaption></figure><p>Setelah bereksperimen dengan const berikut di config/constant.go, ternyata bisa berhasil.</p><pre>DbMaxConns = 50<br>TotalWorker = 50</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*7hxGfANvA1N8xunQj6eWNQ.png" /><figcaption>DbMaxConns = 50, TotalWorker = 50</figcaption></figure><p>Ketika DbMaxConns = 100 dan TotalWorker = 50 , program ini masih bisa berjalan sampai selesai.</p><p>Pada logic berikut</p><pre>for workerIndex := 0; workerIndex &lt;= config.TotalWorker; workerIndex++ {<br>    //<br>}</pre><p>Berarti total akan ada workerIndex sejumlah config.TotalWorker + 1 . Jika TotalWorker = 50 , maka workerIndex ada 51, dengan index 0 hingga 50 sementara koneksi hanya tersedia 50.</p><p>Tetapi jika TotalWorker = 100 yang artinya akan ada 101 workerIndex sementara koneksi hanya ada 100, program tidak berjalan sampai selesai.</p><p>Kenapa jika 50 bisa berjalan sampai selesai, namun jika 100 tidak bisa berjalan? Saya masih mencari jawabannya. Jika Anda punya ide atau jawaban, saya akan senang mendengarnya.</p><p>Jika ada masukan, just let me know. Terima kasih sudah mampir membaca! ^-^</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19a2668e5206" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka with Golang: Simple Producer and Consumer]]></title>
            <link>https://medium.com/@ktiarad/kafka-with-golang-simple-producer-and-consumer-f219b83373dc?source=rss-3eb2e6c2ec38------2</link>
            <guid isPermaLink="false">https://medium.com/p/f219b83373dc</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[it]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Tiara Dewangga]]></dc:creator>
            <pubDate>Sun, 29 Jan 2023 13:49:06 GMT</pubDate>
            <atom:updated>2023-01-31T14:12:23.939Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi, it’s Tiara.</p><p>Okay let’s go!</p><p>Before start creating the app, let’s take a look at this following quick start, or you can follow my steps.</p><p><a href="https://kafka.apache.org/quickstart">Apache Kafka</a></p><p>Btw I’m using Linux Ubuntu 20.04.3</p><p>1.Download Kafka</p><p><a href="https://kafka.apache.org/downloads">Apache Kafka</a></p><p>Choose the <strong>binary downloads</strong> with Scala although we don’t use Scala.</p><p>Then extract with following commands.</p><pre>tar -xzf kafka_2.13-3.3.1.tgz<br><br>cd kafka_2.13-3.3.1</pre><p>2. Config and check properties</p><p>Not a complicated config, just make sure that we are aware of these values. You can change these as you wish. Please change the value in &lt;...&gt; .</p><p>/config/zookeeper.properties</p><pre>dataDir=&lt;path-to-your-kafka&gt;/kafka_version/data/zookeeper<br>clientPort=2181</pre><p>/config/server.properties</p><pre># This value should be the same with clientPort in zookeeper.properties<br>zookeeper.connect=localhost:2181</pre><p>/config/producer.properties</p><pre>bootstrap.servers=localhost:9092</pre><p>/config/consumer.properties</p><pre>bootstrap.servers=localhost:9092<br>group.id=&lt;consumer-group-name&gt;</pre><p>3. Start Kafka</p><pre># Start the ZooKeeper service<br>bin/zookeeper-server-start.sh config/zookeeper.properties</pre><p>Open other terminal, then run this:</p><pre># Start the Kafka broker service<br>bin/kafka-server-start.sh config/server.properties</pre><p>Then terminate those services with Ctrl + C respectively.</p><p>4. Create a topic</p><p>Change the &lt;topic-name&gt; as you wish.</p><pre>bin/kafka-topics.sh --create --topic &lt;topic-name&gt; --bootstrap-server localhost:9092</pre><p>5. Build app</p><p>You can create folder with any name as you wish. This folder can be in other place, not necessarily in Kafka folder. Here I use folder name kafkago .</p><pre>mkdir kafkago<br>cd kafkago<br>go mod init kafkago<br>code . # if you use VS Code</pre><p>Folder structure:</p><pre>kafkago<br>  ├─consumer<br>  │ └─ consumer.go<br>  ├─producer<br>  │ └─ producer.go<br>  ├─ go.mod<br>  ├─ go.sum<br>  └─ main.go</pre><p>producer.go</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;os&quot;<br><br> &quot;github.com/confluentinc/confluent-kafka-go/kafka&quot;<br>)<br><br>func main() {<br>    topic := &quot;topic-example&quot; // use the topic from step number 4<br><br>    p, err := kafka.NewProducer(&amp;kafka.ConfigMap{<br>        &quot;bootstrap.servers&quot;: &quot;localhost:9092&quot;,<br>    })<br>    if err != nil {<br>        fmt.Printf(&quot;Failed to create producer: %s\n&quot;, err)<br>        os.Exit(1)<br>    }<br><br>    go func() {<br>        for e := range p.Events() {<br>            switch ev := e.(type) {<br>            case *kafka.Message:<br>                if ev.TopicPartition.Error != nil {<br>                    fmt.Printf(&quot;Failed to deliver message: %v\n&quot;, ev.TopicPartition)<br>                } else {<br>                    fmt.Printf(&quot;Produced event to topic %s: key = %-10s value = %s\n&quot;, *ev.TopicPartition.Topic, string(ev.Key), string(ev.Value))<br>                }<br>            }<br>        }<br>    } ()<br><br>    users := map[string]string{<br>        &quot;1&quot;: &quot;val1&quot;,<br>        &quot;2&quot;: &quot;val2&quot;,<br>        &quot;3&quot;: &quot;val3&quot;,<br>        &quot;4&quot;: &quot;val4&quot;,<br>    }<br><br>    for key, val := range users {<br>        p.Produce(&amp;kafka.Message{<br>            TopicPartition: kafka.TopicPartition{Topic: &amp;topic, Partition: kafka.PartitionAny},<br>            Key: []byte(key),<br>            Value: []byte(val),<br>        }, nil)<br>    }<br><br>    p.Flush(15 * 1000)<br>    p.Close()<br>}</pre><p>consumer.go</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;os&quot;<br> &quot;os/signal&quot;<br> &quot;syscall&quot;<br> &quot;time&quot;<br><br> &quot;github.com/confluentinc/confluent-kafka-go/kafka&quot;<br>)<br><br>func main() {<br>    topic := &quot;topic-example&quot;<br>    <br>    c, err := kafka.NewConsumer(&amp;kafka.ConfigMap{<br>        &quot;bootstrap.servers&quot;: &quot;localhost:9092&quot;,<br>        &quot;group.id&quot;: &quot;test-consumer-group&quot;,<br>    })<br>    if err != nil {<br>        fmt.Printf(&quot;Failed to consume: %s\n&quot;, err)<br>        os.Exit(1)<br>    }<br><br>    err = c.SubscribeTopics([]string{topic}, nil)<br><br>    defer func() {<br>        fmt.Printf(&quot;Error when subscribe: %s\n&quot;, err)<br>    } ()<br><br>    sigchan := make(chan os.Signal, 1)<br>    signal.Notify(sigchan, syscall.SIGINT, syscall.SIGTERM)<br><br>    run := true<br>    for run {<br>        select {<br>        case sig := &lt;- sigchan:<br>            fmt.Printf(&quot;Caught signal %v: terminating\n&quot;, sig)<br>            run = false<br>        default:<br>            ev, err := c.ReadMessage(100 * time.Millisecond)<br>            if err != nil {<br>                continue<br>            }<br><br>            fmt.Printf(&quot;Consumed event from topic %s: key = %-10s value = %s\n&quot;, *ev.TopicPartition.Topic, string(ev.Key), string(ev.Value))<br>        }<br>    }<br><br>    c.Close()<br>}</pre><p>main.go</p><p>(Well, we will not use this one actually, (hopefully) will improve this in the future).</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br>)<br><br>func main() {<br> fmt.Println(&quot;Start Kafka&quot;)<br>}</pre><p>Then run go build .</p><p>6. Run the application</p><p>Start Kafka with step number 3 but don’t terminate it. Just terminate when you want to stop the service.</p><p>Then open another terminal, run the consumer:</p><pre>go run consumer/consumer.go</pre><p>And open another terminal to run the producer:</p><pre>go run producer/producer.go</pre><p>We will see when the producer is run, the consumer will consume the data.</p><p>That’s all. The detail explanation (if needed) will be written in other page. Just let me know for any feedback, I would be glad to hear from you. Thank you.</p><p>References:</p><ol><li><a href="https://kafka.apache.org/quickstart">https://kafka.apache.org/quickstart</a></li><li><a href="https://developer.confluent.io/get-started/go/?_ga=2.182484453.277454128.1671457517-896048922.1670765869">https://developer.confluent.io/get-started/go/</a></li><li><a href="https://www.youtube.com/playlist?list=PL-CtdCApEFH8dJMuQGojbjUdLEty8mqYF">Belajar Apache Kafka untuk Pemula — YouTube</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f219b83373dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Goroutines: Sebuah Catatan]]></title>
            <link>https://medium.com/@ktiarad/goroutines-sebuah-catatan-70314935b2f7?source=rss-3eb2e6c2ec38------2</link>
            <guid isPermaLink="false">https://medium.com/p/70314935b2f7</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[notes]]></category>
            <dc:creator><![CDATA[Tiara Dewangga]]></dc:creator>
            <pubDate>Thu, 26 Jan 2023 16:03:41 GMT</pubDate>
            <atom:updated>2023-01-29T01:51:57.899Z</atom:updated>
            <content:encoded><![CDATA[<h3>Goroutines: Sebuah Catatan Coret-Coret</h3><p>Hi, ini adalah catatan/rangkuman saya saat belajar Goroutines. Saya akan sangat senang untuk menerima feedback darimu.</p><p>Goroutines tidak bekerja secara parallel, melainkan concurrent. Goroutines bekerja di dalam sebuah thread.</p><p>Channel : alat komunikasi untuk sync/blocking dalam Goroutines</p><p>There are two types of channel:</p><ul><li>channel in : chan &lt;- string , the channel receive the data</li><li>channel out : &lt;-chan string , the channel send the data</li></ul><p>Buffered channel digunakan untuk menentukan jumlah data yang bisa dikirimkan dalam waktu yang bersamaan serta bekerja secara asynchronous, selama jumlah datanya tidak lebih dari kapasitas yang ditentukan. Contoh : make(chan string, 3)</p><p>Range channel : penggunaan for range pada channel</p><p>Select channel : penggunaan select case pada channel, ada beberapa channel dan dilakukan select case</p><p>Race condition disebabkan oleh suatu program yang dijalankan dalam multiple thread.</p><p>sync.Mutex : salah satu cara untuk mencegah race condition dengan lock dan unlock data</p><p>RWMutex : untuk mengatasi rebutan data antara Read dan Write saat proses lock dan unlock</p><p>sync.WaitGroup : untuk sinkronisasi Goroutine, ada Add() dan Done()</p><p>Perbedaan Channel dan WaitGroup:</p><ul><li>Channel : komunikasi data antar Goroutines</li><li>WaitGroup : sinkronisasi Goroutines, akan blocking sampai semua Goroutines selesai memproses</li></ul><p>Beberapa method sync:</p><ul><li>sync.Once : satu function hanya bisa diakses oleh satu Goroutine, setelah itu tidak bisa diakses lagi oleh Goroutine lain</li><li>sync.Pool : implementasi Go dengan object pool pattern (insert data ke pool, ambil data dari pool, kemudian dikembalikan lagi ke pool)</li><li>sync.Map : penggunaan Map yang aman untuk Goroutine</li><li>sync.Cond : locking dengan kondisi</li></ul><p>Atomic : penggunaan data primitive yang aman untuk Goroutine</p><p>GOMAXPROCS : untuk mengubah/mengambil data jumlah thread</p><p>Jumlah thread Go = jumlah CPU komputer</p><p>Method pada time:</p><ul><li>time.Timer : mengirim event ke channel dalam waktu (timer) tertentu</li><li>time.Tick : sama dengan timer tetapi berulang</li></ul><p>Sumber belajar :</p><ul><li><a href="https://www.udemy.com/course/pemrograman-go-lang-pemula-sampai-mahir/">https://www.udemy.com/course/pemrograman-go-lang-pemula-sampai-mahir/</a></li><li><a href="https://dasarpemrogramangolang.novalagung.com/">https://dasarpemrogramangolang.novalagung.com/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70314935b2f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>