<?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 Rivan Prawira on Medium]]></title>
        <description><![CDATA[Stories by Rivan Prawira on Medium]]></description>
        <link>https://medium.com/@prawiraa.rivan?source=rss-82176cae42df------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*u59BnAk2i4L93S1H</url>
            <title>Stories by Rivan Prawira on Medium</title>
            <link>https://medium.com/@prawiraa.rivan?source=rss-82176cae42df------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 14:47:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prawiraa.rivan/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[Writing Efficient Go Code: Clean Code Principles, Code Smells, and Conventions]]></title>
            <link>https://medium.com/@prawiraa.rivan/writing-efficient-go-code-clean-code-principles-code-smells-and-conventions-4117acfc2cb3?source=rss-82176cae42df------2</link>
            <guid isPermaLink="false">https://medium.com/p/4117acfc2cb3</guid>
            <category><![CDATA[code-smells]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[convention]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Rivan Prawira]]></dc:creator>
            <pubDate>Mon, 24 Mar 2025 04:06:54 GMT</pubDate>
            <atom:updated>2025-03-24T04:06:54.301Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A7LlYDBWnmS37hLUPwgwog.png" /><figcaption>source: Pinterest</figcaption></figure><p>Writing clean and maintainable code is a fundamental practice in software development. Clean code is easy to read, understand, and modify, making collaboration and long-term maintenance more efficient. Principles like DRY (Don’t Repeat Yourself) and KISS (Keep It Simple, Stupid) help developers write concise and effective code while avoiding unnecessary complexity.</p><p>However, bad coding habits can lead to code smells, which indicate deeper problems in the code structure. Issues like bloaters (overly large and complex code) and dispensable (unnecessary or redundant code) can make a project difficult to manage.</p><p>Additionally, every programming language has its own code conventions that promote consistency and readability. Following best practices for naming variables, organizing functions, and structuring code ensures clarity and maintainability.</p><p>In this article, we will explore the key principles of clean code, identify common code smells, and discuss the importance of adhering to coding conventions.</p><h3>Clean Code</h3><p>Clean code is more than just code that works — it is code that is <strong>easy to read, understand, and maintain</strong>. Writing clean code ensures that software remains scalable, reduces technical debt, and improves collaboration among developers. In Go, clean code is particularly important because of its simplicity and efficiency-focused philosophy. There is some practice and principles to help you write clean code.</p><h4>Meaningful Variable and Function Names</h4><p>Choose names for variables, functions, and classes that reflect their purpose and behavior. This makes the code self-documenting and easier to understand without extensive comments. Avoid single-letter variable names or cryptic abbreviations.</p><p><strong>Bad Naming in Go (Unclear, Cryptic, or Misleading)</strong></p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// Bad function name (vague, unclear)<br>func DoIt(x int) int {<br>    return x * x<br>}<br><br>// Bad variable names (single letters, no context)<br>func calc(a, b int) int {<br>    c := a + b<br>    return c<br>}<br><br>// Bad struct name (unclear purpose)<br>type Data struct {<br>    v int<br>}</pre><p><strong>Good Naming in Go (Descriptive, Clear, Meaningful)</strong></p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// Good function name (clear purpose)<br>func SquareNumber(num int) int {<br>    return num * num<br>}<br><br>// Good variable names (self-explanatory)<br>func AddNumbers(firstNumber, secondNumber int) int {<br>    sum := firstNumber + secondNumber<br>    return sum<br>}<br><br>// Good struct name (meaningful)<br>type SensorReading struct {<br>    Value int<br>}</pre><h4><strong>Keep Functions and Methods Short</strong></h4><p>Follow the Single Responsibility Principle (SRP), which states that a function should be dedicated to a single task and perform it efficiently. When a function is responsible for only one purpose, it becomes easier to understand, read, and maintain. This also enhances code reusability and simplifies debugging.</p><p>Moreover, adhering to SRP improves scalability, as smaller functions can be modified or extended without affecting other parts of the codebase. If a function becomes overly lengthy or complex, consider refactoring it into smaller, modular functions to enhance clarity and maintainability.</p><p><strong>Violating the Principle</strong></p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;os&quot;<br>)<br><br>// Bad: This function does too many things: reads a file, processes the data, and prints the result.<br>func ReadProcessAndPrintFile(filename string) {<br>    file, err := os.ReadFile(filename)<br>    if err != nil {<br>        fmt.Println(&quot;Error reading file:&quot;, err)<br>        return<br>    }<br><br>    // Processing data (e.g., converting to uppercase)<br>    processedData := string(file)<br>    processedData = processedData + &quot; - Processed&quot;<br><br>    // Printing the result<br>    fmt.Println(processedData)<br>}<br><br>func main() {<br>    ReadProcessAndPrintFile(&quot;data.txt&quot;)<br>}</pre><p><strong>Following the Principle</strong></p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;os&quot;<br>)<br><br>// Good: Function only reads a file<br>func ReadFile(filename string) (string, error) {<br>    file, err := os.ReadFile(filename)<br>    if err != nil {<br>        return &quot;&quot;, err<br>    }<br>    return string(file), nil<br>}<br><br>// Good: Function only processes data<br>func ProcessData(data string) string {<br>    return data + &quot; - Processed&quot;<br>}<br><br>// Good: Function only prints output<br>func PrintData(data string) {<br>    fmt.Println(data)<br>}<br><br>func main() {<br>    filename := &quot;data.txt&quot;<br><br>    content, err := ReadFile(filename)<br>    if err != nil {<br>        fmt.Println(&quot;Error reading file:&quot;, err)<br>        return<br>    }<br><br>    processedContent := ProcessData(content)<br>    PrintData(processedContent)<br>}</pre><h4>Use Comments Wisely and Make Them Meaningful</h4><p>Avoid commenting on obvious code, as unnecessary or unclear comments can clutter the codebase and reduce readability. While comments are meant to improve understanding, excessive or redundant ones can become outdated over time, leading to confusion rather than clarity.</p><p>Instead, prioritize writing clean, self-explanatory code where function names, variable names, and structure clearly convey their purpose. Meaningful comments should be reserved for explaining complex logic, assumptions, or decisions that may not be immediately apparent. Keeping the codebase concise and well-documented ensures maintainability and prevents misleading or obsolete comments from causing misunderstandings.</p><p><strong>Bad Comments</strong> <strong>(Unnecessary, Redundant, or Misleading)</strong></p><pre>// Increment i by 1                   (it is redundant)<br>i = i + 1 <br><br>// Open the file                      (states the obvious)<br>file, err := os.Open(&quot;data.txt&quot;)<br><br>// Check if error exists              (does not provide additional insight)<br>if err != nil {<br>    fmt.Println(&quot;Error opening file&quot;)<br>}</pre><p><strong>Good Comments</strong> <strong>(Informative, Concise, and Necessary)</strong></p><pre>// ReadConfig loads application settings from config.json<br>func ReadConfig() (Config, error) {<br>    ...<br>}<br><br>// Close the file to prevent memory leaks<br>defer file.Close()<br><br>// Retry three times in case of network failure<br>for i := 0; i &lt; 3; i++ {<br>    err := sendRequest()<br>    if err == nil {<br>        break<br>    }<br>}</pre><h4>Consistent Formatting and Indentation</h4><p>Maintain a consistent coding style and indentation when writing Go code. A well-structured and uniformly formatted codebase enhances readability, making it easier to understand and maintain. Go has an official style guide enforced by tools like gofmt and golint, which should be followed to ensure consistency across projects.</p><p>Beyond indentation, consistency also applies to naming conventions, spacing, and code structure. Use idiomatic Go practices, such as camel case for variable and function names (e.g., myVariable, ProcessData), proper package structuring, and clear separation of concerns. Following these conventions improves collaboration among developers and reduces cognitive load when reviewing or debugging code.</p><p><strong>Bad Coding Style in Go (Inconsistent, Unformatted, Hard to Read)</strong></p><pre>package main <br>import (&quot;fmt&quot; <br>        &quot;math&quot;<br>) <br><br>func main(){<br>fmt.Println(&quot;Hello, Go!&quot;)<br>}</pre><p><strong>Good Coding Style in Go (Consistent, Clean, Readable)</strong></p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;math&quot;<br>)<br><br>func main() {<br>    fmt.Println(&quot;Hello, Go!&quot;)<br>}</pre><h4>Avoid Deep Nesting Conditionals</h4><p>Deep nesting occurs when multiple conditions are stacked inside one another, leading to code that is hard to read, debug, and maintain. Excessive nesting can make it difficult to track logic flow, increasing the chances of introducing errors.</p><p>A better approach is to reduce nesting by using guard clauses, early returns, or restructuring logic to improve readability and maintainability.</p><p><strong>Bad Example (Deep Nesting)</strong></p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func CheckUserAccess(age int, isAdmin bool) {<br>    if age &gt;= 18 {<br>        if isAdmin {<br>            fmt.Println(&quot;Access granted: Admin privileges&quot;)<br>        } else {<br>            fmt.Println(&quot;Access granted: User privileges&quot;)<br>        }<br>    } else {<br>        fmt.Println(&quot;Access denied&quot;)<br>    }<br>}<br><br>func main() {<br>    CheckUserAccess(20, false)<br>}</pre><p><strong>Good Example (Avoiding Deep Nesting)</strong></p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func CheckUserAccess(age int, isAdmin bool) {<br>    if age &lt; 18 {<br>        fmt.Println(&quot;Access denied&quot;)<br>        return<br>    }<br><br>    if isAdmin {<br>        fmt.Println(&quot;Access granted: Admin privileges&quot;)<br>        return<br>    }<br><br>    fmt.Println(&quot;Access granted: User privileges&quot;)<br>}<br><br>func main() {<br>    CheckUserAccess(20, false)<br>}</pre><h4>Follow The “Don’t Repeat Yourself” (DRY) Principle</h4><p>The DRY (Don’t Repeat Yourself) Principle is a fundamental software development guideline that encourages reducing code duplication. The idea is to write reusable code instead of copying and pasting similar logic multiple times. When the same logic is repeated in different places, it increases the risk of inconsistencies, makes debugging harder, and requires more effort when updates or changes are needed.</p><p><strong>Bad Example (Repeating Code)</strong></p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func PrintUserDetails(name string, age int) {<br>    fmt.Println(&quot;User Name:&quot;, name)<br>    fmt.Println(&quot;User Age:&quot;, age)<br>}<br><br>func PrintAdminDetails(name string, age int, role string) {<br>    fmt.Println(&quot;Admin Name:&quot;, name)<br>    fmt.Println(&quot;Admin Age:&quot;, age)<br>    fmt.Println(&quot;Admin Role:&quot;, role)<br>}<br><br>func main() {<br>    PrintUserDetails(&quot;Alice&quot;, 25)<br>    PrintAdminDetails(&quot;Bob&quot;, 30, &quot;Super Admin&quot;)<br>}</pre><p><strong>Good Example (Applying the DRY Principle)</strong></p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// A single function to handle both users and admins<br>func PrintPersonDetails(name string, age int, role ...string) {<br>    fmt.Println(&quot;Name:&quot;, name)<br>    fmt.Println(&quot;Age:&quot;, age)<br>    if len(role) &gt; 0 {<br>        fmt.Println(&quot;Role:&quot;, role[0]) // Print role if provided<br>    }<br>}<br><br>func main() {<br>    PrintPersonDetails(&quot;Alice&quot;, 25)              // User<br>    PrintPersonDetails(&quot;Bob&quot;, 30, &quot;Super Admin&quot;) // Admin<br>}</pre><h4>Implement “Keep It Simple, Stupid” (KISS) Principle</h4><p>The “Keep It Simple, Stupid” (KISS) Principle is a software development best practice that emphasizes writing simple, clear, and easily understandable code. The idea behind KISS is that simplicity leads to better readability, easier maintenance, and fewer bugs.</p><p>Code that is overly complex can be difficult to understand, modify, and debug. Instead of writing unnecessarily convoluted logic, developers should focus on writing code that does the job in the most straightforward and efficient way possible.</p><p><strong>Bad Example (Overly Complex Code)</strong></p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func CalculateDiscount(price float64, category string) float64 {<br>    var discount float64<br><br>    if category == &quot;student&quot; {<br>        if price &gt; 0 {<br>            discount = price * 0.10<br>        } else {<br>            discount = 0<br>        }<br>    } else if category == &quot;senior&quot; {<br>        if price &gt; 0 {<br>            discount = price * 0.15<br>        } else {<br>            discount = 0<br>        }<br>    } else {<br>        if price &gt; 0 {<br>            discount = price * 0.05<br>        } else {<br>            discount = 0<br>        }<br>    }<br><br>    return price - discount<br>}<br><br>func main() {<br>    fmt.Println(&quot;Student Price:&quot;, CalculateDiscount(100, &quot;student&quot;))<br>}</pre><p><strong>Good Example (Applying KISS Principle)</strong></p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// CalculateDiscount applies a discount based on the category<br>func CalculateDiscount(price float64, category string) float64 {<br>    if price &lt;= 0 {<br>        return price<br>    }<br><br>    discounts := map[string]float64{<br>        &quot;student&quot;: 0.10,<br>        &quot;senior&quot;:  0.15,<br>    }<br><br>    discountRate, exists := discounts[category]<br>    if !exists {<br>        discountRate = 0.05 // Default discount<br>    }<br><br>    return price - (price * discountRate)<br>}<br><br>func main() {<br>    fmt.Println(&quot;Student Price:&quot;, CalculateDiscount(100, &quot;student&quot;))<br>}</pre><h4>Focusing on “You Ain’t Gonna Need It” (YAGNI) Principle</h4><p>The “You Ain’t Gonna Need It” (YAGNI) Principle is a software development guideline that advises only implementing features, functions, or code that are strictly necessary at the moment. This means avoiding premature optimizations, speculative features, or unnecessary abstractions that may never be used.</p><p>The core idea behind YAGNI is simplicity and efficiency. Many developers anticipate future requirements and add extra features that are not currently needed, leading to unnecessary complexity. This not only increases development time but also makes maintenance harder. Instead, YAGNI encourages developers to focus only on the requirements at hand and refactor when actual needs arise.</p><p><strong>Bad Example (Violating YAGNI with Unnecessary Abstraction)</strong></p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// Unnecessary interface (over-engineered)<br>type Logger interface {<br>    Log(message string)<br>}<br><br>// Only one implementation (not needed yet)<br>type ConsoleLogger struct{}<br><br>func (c ConsoleLogger) Log(message string) {<br>    fmt.Println(&quot;Log:&quot;, message)<br>}<br><br>// Using the interface when we don&#39;t need it<br>func PerformLogging(logger Logger, message string) {<br>    logger.Log(message)<br>}<br><br>func main() {<br>    logger := ConsoleLogger{}<br>    PerformLogging(logger, &quot;Application started&quot;)<br>}</pre><p><strong>Good Example (Applying YAGNI with a Simpler Approach)</strong></p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// Directly using a function instead of an unnecessary abstraction<br>func Log(message string) {<br>    fmt.Println(&quot;Log:&quot;, message)<br>}<br><br>func main() {<br>    Log(&quot;Application started&quot;)<br>}</pre><h4>Test-Driven Development (TDD)</h4><p>Test-Driven Development (TDD) is a software development methodology that emphasizes writing tests before writing actual code. It follows a repetitive cycle of writing a failing test, writing just enough code to pass the test, and then refactoring the code to improve its quality.</p><p>TDD is commonly described using the “Red-Green-Refactor” cycle:</p><ol><li><strong>Red</strong> — Write a test that initially fails (because the feature isn’t implemented yet).</li><li><strong>Green </strong>— Write the simplest possible code to make the test pass.</li><li><strong>Refactor </strong>— Improve the code without changing behavior, ensuring that the test still passes.</li></ol><p>By following TDD, developers ensure that their code is robust, maintainable, and bug-free, as it forces them to think about functionality from the very beginning.</p><p><strong>Bad Example (Without TDD)</strong></p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func Add(a, b int) int {<br>    return a + b<br>}<br><br>func main() {<br>    fmt.Println(&quot;Result:&quot;, Add(3, 5)) // Manually testing the function<br>}</pre><p><strong>Good Example (Using TDD)</strong></p><p><strong>Step 1: Write a Failing Test (Red)</strong></p><pre>package main<br><br>import &quot;testing&quot;<br><br>func TestAdd(t *testing.T) {<br>    result := Add(3, 5)<br>    expected := 8<br><br>    if result != expected {<br>        t.Errorf(&quot;Expected %d, but got %d&quot;, expected, result)<br>    }<br>}</pre><p><strong>Step 2: Implement the Function (Green)</strong></p><pre>package main<br><br>func Add(a, b int) int {<br>    return a + b<br>}</pre><p><strong>Step 3: Refactor the Code (Refactor)</strong></p><p>If we notice inefficiencies or redundant logic, we can refactor with confidence, knowing our test will catch regressions.</p><h3>Code Smell</h3><p>Code smell refers to any symptom in the code that suggests a deeper problem in design, structure, or implementation. While not necessarily a bug, it indicates areas that may lead to maintainability issues, increased complexity, or technical debt if left unaddressed. Code smells often arise from poor coding practices, such as violating the Single Responsibility Principle (SRP), excessive dependencies, or unnecessary complexity. Identifying and refactoring code smells early helps improve readability, scalability, and long-term code health. There are various types of code smells, each highlighting specific design flaws that can hinder software quality. Some common examples include duplicated code, long methods, deep nesting, and excessive coupling, which can all make future modifications more difficult. Understanding these different types allows developers to recognize and address potential problems before they escalate.</p><h4>Bloaters</h4><p>Bloaters are a category of code smells that occur when a piece of code grows excessively in size, making it difficult to read, maintain, and modify. They usually result from gradual expansion over time rather than poor design from the start. Bloaters make the codebase unnecessarily complex, leading to reduced efficiency, scalability, and developer productivity.</p><p>There are some common types of Bloaters:</p><ol><li><strong>Long Method</strong> — A function that performs too many tasks, making it hard to understand and modify.</li><li><strong>Large Class </strong>— A class that takes on too many responsibilities, violating modular design principles.</li><li><strong>Primitive Obsession</strong> — Overuse of primitive data types (integers, strings, booleans) instead of using objects or structures.</li><li><strong>Long Parameter List</strong> — Functions with too many parameters, making them hard to call and modify.</li><li><strong>Data Clumps</strong> — Groups of related variables appearing together repeatedly across the codebase.</li></ol><h4>Object-Orientation Abusers</h4><p>Object-Orientation Abusers refer to poor practices in object-oriented programming (OOP) that misuse or misunderstand fundamental OOP principles such as encapsulation, inheritance, and polymorphism. These anti-patterns often result in overly complex, rigid, and difficult-to-maintain code. Instead of leveraging OOP effectively, these abuses lead to unnecessary complexity, tightly coupled code, and violations of SOLID principles.</p><p>There are some common types of Object-Orientation Abusers:</p><ol><li><strong>Switch Statements </strong>— Excessive use of switch statements instead of proper polymorphism, making the code difficult to extend and modify.</li><li><strong>Temporary Field</strong> — A field that exists only for specific cases, leading to unnecessary memory usage and confusion.</li><li><strong>Refused Bequest</strong> — A subclass inherits methods or properties from a parent class but does not use them, violating the Liskov Substitution Principle (LSP).</li><li><strong>Alternative Classes with Different Interfaces</strong> — Multiple classes perform similar functionality but use different method names, making it harder to integrate and reuse them.</li></ol><h4>Change Preventers</h4><p>Change Preventers are code smells that make modifying the code difficult and risky, leading to high maintenance costs and reduced agility in software development. When a small change in one part of the codebase forces modifications in multiple places, it increases the chances of introducing bugs and breaking functionality.</p><p>There are three common types of Change Preventers:</p><ol><li><strong>Divergent Change</strong> — A single class or module is modified frequently for different reasons, violating the Single Responsibility Principle (SRP).</li><li><strong>Shotgun Surgery</strong> — A small change in the code requires modifications in many different files or classes, increasing the risk of errors.</li><li><strong>Parallel Inheritance Hierarchies </strong>— Every time a new subclass is added in one hierarchy, a corresponding subclass must be created in another, leading to unnecessary complexity.</li></ol><h4>Dispensables</h4><p>Dispensables refer to unnecessary code elements that do not add value to a software system and should be removed to improve readability, maintainability, and efficiency. These elements make the code bloated, harder to understand, and more difficult to maintain over time.</p><p>There are several common types of Dispensables:</p><ol><li><strong>Comments</strong> — While comments can be helpful, unnecessary, redundant, or outdated comments clutter the code and make it harder to maintain.</li><li><strong>Duplicate Code</strong> — Repeating the same logic in multiple places makes the code hard to maintain. If a bug is found, it needs to be fixed everywhere.</li><li><strong>Lazy Class</strong> — A class that doesn’t have enough functionality to justify its existence, making the codebase unnecessarily complex.</li><li><strong>Data Class</strong> — A class that only contains data fields without meaningful behavior or logic.</li><li><strong>Dead Code</strong> — Unused variables, functions, or code blocks that remain in the system but are never called or needed.</li><li><strong>Speculative Generality </strong>— Code that was written for future use cases that never happen, making the system unnecessarily complex.</li></ol><h4>Couplers</h4><p>Couplers are code smells that indicate excessive dependency between components, making the system difficult to modify, test, and maintain. When different classes, functions, or modules are tightly coupled, a change in one part of the system forces changes in other parts, leading to fragile and inflexible code.</p><p>The goal of good software design is to promote low coupling and high cohesion, meaning components should depend on each other as little as possible while being self-contained.</p><p>There are four common types of Couplers:</p><ol><li><strong>Feature Envy </strong>— A method that accesses the data of another class too frequently instead of operating on its own data.</li><li><strong>Inappropriate Intimacy</strong> — Two classes are too tightly connected, often accessing private fields or methods of each other.</li><li><strong>Message Chains </strong>— A class calls a method, which calls another method, and so on, creating long dependency chains.</li><li><strong>Middleman</strong> — A class exists only to pass requests to another class, without adding value.</li></ol><h4>Other Smells</h4><p>However, the field of software engineering contains a wide variety of code smells beyond the ones discussed so far. These code smells manifest in different ways and can negatively impact the maintainability, readability, and scalability of a software system. While some are more common and easier to identify, others may be subtle and deeply embedded within the code structure.</p><ol><li><strong>Inconsistent Names</strong> — Different parts of the codebase use inconsistent naming conventions, making it difficult to understand and maintain.</li><li><strong>Uncommunicative Name</strong> — Variable, function, or class names do not clearly indicate their purpose, making the code difficult to understand.</li><li><strong>Type Embedded in Name</strong> — Including data types in variable or function names, which redundantly specifies something already defined by the language.</li><li><strong>Magic Numbers </strong>— Using hardcoded numerical values in the code without explanation, making it difficult to understand and modify.</li><li><strong>Incomplete Library Class </strong>— A third-party library does not provide all the necessary functionality, forcing developers to extend or modify it in ways that may not be ideal.</li></ol><h3>Code Convention</h3><p>Code convention refers to a set of guidelines and best practices that developers follow to write clean, consistent, and readable code. These conventions cover various aspects of coding, such as naming conventions, indentation, spacing, commenting, file organization, and overall structure.</p><p>Following a consistent coding standard makes collaboration easier, reduces errors, and improves maintainability. Many programming languages have established conventions, such as Golang’s official formatting.</p><h4>Naming Convention</h4><p>Consistent and meaningful names make the code self-explanatory.</p><ul><li><strong>Variables &amp; Functions — </strong>Variables should be descriptive, concise, and written in camelCase (for local variables) or PascalCase (if exported from a package).</li></ul><pre>var userName string   // Clear and meaningful<br>var accountBalance float64<br><br>var un string         // Too short, unclear<br>var x float64         // Meaningless single-letter name<br>var UserName string   // Capitalized, but not exported</pre><ul><li><strong>Constants — </strong>Constants should be written in PascalCase (for exported constants) or camelCase (for unexported constants). If the constant is a grouping of related values, use iota for enumeration.</li></ul><pre>// Exported constants<br>const MaxRetries = 5  <br>const DefaultTimeout = 30 * time.Second  <br><br>// Unexported constants (private)<br>const apiVersion = &quot;v1.0&quot;  <br><br>// Enumeration using iota<br>type UserRole int  <br><br>const (  <br>    Admin UserRole = iota  <br>    Editor  <br>    Viewer  <br>)<br><br><br>const max_retries = 5      // Snake_case is not idiomatic in Go  <br>const DEFAULT_TIMEOUT = 30 // Uppercase is for global constants in C  <br>const AdminRole = 0        // Should use iota for enumeration  </pre><ul><li>S<strong>tructs &amp; Interfaces — </strong>Naming rules for these should follow PascalCase for exported types and camelCase for unexported ones.</li></ul><pre>// Exported struct (Public)<br>type UserProfile struct {  <br>    FirstName string  <br>    LastName  string  <br>    Age       int  <br>}  <br><br>// Unexported struct (Private)<br>type databaseConnection struct {  <br>    host string  <br>    port int  <br>}  <br><br>// Interface (Ends with -er if it represents behavior)<br>type Reader interface {  <br>    Read() ([]byte, error)  <br>}<br><br><br>type user_profile struct { }  // Snake_case is not idiomatic in Go  <br>type userprofile struct { }   // Should use PascalCase  <br>type Readable interface { }   // Non-standard interface naming</pre><ul><li><strong>Projects &amp; Package —</strong> Package names should be short, simple, and lowercase without underscores. Avoid pluralization and unnecessary prefixes.</li></ul><pre>package auth       // Authentication logic  <br>package storage    // File or database storage  <br>package handler    // HTTP request handlers  <br>package config     // Configuration settings<br><br>package Authentication  // Capitalization is incorrect  <br>package storageUtils    // Avoid &quot;Utils&quot; in package names  <br>package db_manager      // Underscores are not idiomatic in Go  <br>package configs         // Avoid pluralization</pre><h4>Code Formatting</h4><p>Go follows a strict and consistent formatting style that makes the code readable, maintainable, and idiomatic. The Go compiler itself enforces formatting rules, and tools like gofmt and goimports ensure uniform style across projects.</p><ul><li><strong>Indentation — </strong>Go uses tabs (not spaces) for indentation and each indentation level is 1 tab.</li></ul><pre>//Correct usage using tab<br>func sayHello(name string) {<br>  fmt.Println(&quot;Hello,&quot;, name)<br>}<br><br><br>func sayHello(name string) {<br>    fmt.Println(&quot;Hello,&quot;, name)  // Spaces instead of tabs<br>}</pre><ul><li><strong>Spacing Rules —</strong> Proper spacing enhances readability and consistency in Go code.</li></ul><pre>//spaces around operators<br>sum := a + b - c * d / e<br><br>//single space after commas and around assignment operators<br>numbers := []int{1, 2, 3, 4}<br>fmt.Println(a, b, c)<br><br>//spaces before colons in struct tags<br>type User struct {<br> Name  string `json:&quot;name&quot;`<br> Email string `json:&quot;email&quot;`<br>}<br><br>//blank lines for logical separation<br>func main() {<br> fmt.Println(&quot;Start&quot;)<br><br> processData() // Logical separation<br><br> fmt.Println(&quot;End&quot;)<br>}</pre><ul><li><strong>Function Formatting — </strong>Functions should have consistent indentation and spacing for readability.</li></ul><pre>//Good example <br>func add(a, b int) int {<br> return a + b<br>}<br><br>//No space between parameters and inconsistent indentation<br>func add(a,b int)int {<br>    return a+b<br>}</pre><ul><li><strong>Control Structure (if, for, switch)</strong></li></ul><pre>//Good example<br>if x &gt; 10 {<br> fmt.Println(&quot;Greater than 10&quot;)<br>} else {<br> fmt.Println(&quot;Less than or equal to 10&quot;)<br>}<br><br>//No space before curly brace and inconsistent spacing<br>if(x&gt;10){<br>fmt.Println(&quot;Greater than 10&quot;)<br>}else{<br>fmt.Println(&quot;Less than or equal to 10&quot;)<br>}</pre><ul><li><strong>Struct Formatting</strong></li></ul><pre>//Good example<br>type Person struct {<br> Name string<br> Age  int<br>}<br><br>//Misaligned fields<br>type Person struct {<br>    Name     string<br>  Age int<br>}</pre><ul><li><strong>Loop Formatting</strong></li></ul><pre>//Good example<br>for i := 0; i &lt; 10; i++ {<br> fmt.Println(i)<br>}<br><br>//Inconsistent spacing and missing braces<br>for i:=0;i&lt;10;i++ <br>    fmt.Println(i)</pre><ul><li><strong>Import Formatting —</strong> Imports should be grouped and formatted properly.</li></ul><pre>//Good example<br>import (<br> &quot;fmt&quot;<br> &quot;os&quot;<br>)<br><br>//Unsorted imports<br>import (&quot;os&quot;<br>&quot;fmt&quot;)</pre><h4>Commenting</h4><p>Comments should explain why the code exists, not what it does (unless necessary). Also use doc comments (// or /** ... */) to describe functions, structs, and complex logic.</p><pre>//this is Go comment<br><br>#this is not Go comment<br><br>&lt;!-- this is also not Go comment --&gt;</pre><h4>Error Handling</h4><p>Handling errors correctly ensures robust and reliable applications. In Go, errors should be explicitly returned and checked. Always handle errors explicitly and provide meaningful error messages.</p><pre>//Good example<br>func readFile(filename string) ([]byte, error) {<br>    data, err := os.ReadFile(filename)<br>    if err != nil {<br>        return nil, fmt.Errorf(&quot;failed to read file: %w&quot;, err)<br>    }<br>    return data, nil<br>}</pre><pre>//Bad example<br>func readFile(filename string) []byte {<br>    data, _ := os.ReadFile(filename) // Ignoring error is bad practice!<br>    return data<br>}</pre><h4>Project Structure &amp; Architecture in Go</h4><p>A well-structured Go project improves maintainability, scalability, and readability. It ensures that code is modular, reusable, and follows best practices. Here’s how to organize a Go project efficiently.</p><p><strong>Basic Folder Structure — </strong>For small projects, a simple structure is sufficient:</p><pre>myproject/<br>│── main.go<br>│── go.mod<br>│── go.sum<br>│── README.md<br>│── /pkg<br>│── /cmd<br>│── /internal<br>│── /configs<br>│── /api<br>│── /scripts<br>│── /docs</pre><p>cmd/— <strong>Entry Points for Applications</strong></p><p>Each subfolder represents a different application or service. Also contains the main executable logic.</p><pre>cmd/<br>├── myapp/<br>│   ├── main.go<br>│   ├── config.go<br>│   └── server.go</pre><p>internal/ — <strong>Private Application Code</strong></p><p>Code that should not be imported by other projects. Keeps logic encapsulated and prevents external usage.</p><pre>internal/<br>├── services/<br>│   ├── user.go<br>│   ├── order.go<br>│   ├── payment.go<br>├── repository/<br>│   ├── user_repo.go<br>│   ├── order_repo.go</pre><p>pkg/ — <strong>Publicly Reusable Packages</strong></p><p>Common utilities that can be used across multiple projects.</p><pre>pkg/<br>├── logger/<br>│   ├── logger.go<br>├── utils/<br>│   ├── time.go<br>│   ├── strings.go</pre><p>configs/ — <strong>Configuration Files</strong></p><p>Stores settings like database credentials, API keys, and environment variables.</p><pre>configs/<br>├── config.yaml<br>├── config.json</pre><p>api/ — <strong>API Definitions &amp; Handlers</strong></p><p>Manages REST, gRPC, or GraphQL API definitions.</p><pre>api/<br>├── routes.go<br>├── middleware.go<br>├── controllers/<br>│   ├── user_controller.go<br>│   ├── order_controller.go</pre><p>scripts/ — <strong>Helper Scripts</strong></p><p>Contains database migrations, deployment scripts, and automation scripts.</p><pre>scripts/<br>├── migrate.sh<br>├── build.sh</pre><p>docs/ — <strong>Documentation</strong></p><p>Stores API specifications, architecture diagrams, and README files.</p><pre>docs/<br>├── architecture.md<br>├── api.md</pre><p><strong>Layered Architecture — </strong>For larger projects, a layered approach is recommended:</p><pre>/myproject<br>│── /cmd<br>│── /internal<br>│   ├── /domain       # Business entities<br>│   ├── /repository   # Data access layer<br>│   ├── /service      # Business logic<br>│   ├── /handler      # API Handlers<br>│── /configs<br>│── /api<br>│── /pkg<br>│── main.go</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4117acfc2cb3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing SOLID Principles in Golang Development]]></title>
            <link>https://medium.com/@prawiraa.rivan/implementing-solid-principles-in-golang-development-fcd4d7db6b59?source=rss-82176cae42df------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcd4d7db6b59</guid>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[solid-principles]]></category>
            <dc:creator><![CDATA[Rivan Prawira]]></dc:creator>
            <pubDate>Mon, 17 Mar 2025 04:37:35 GMT</pubDate>
            <atom:updated>2025-03-17T04:37:35.545Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*CcQxAQ23gdvD3NjvngTeSw.jpeg" /><figcaption>source: Pinterest</figcaption></figure><p>In modern software development, writing maintainable, scalable, and efficient code is crucial. The SOLID principles, a set of five design principles introduced by Robert C. Martin (Uncle Bob), serve as a foundation for building robust and flexible software architectures. These principles — Single Responsibility Principle (SRP), Open/Closed Principle (OCP), Liskov Substitution Principle (LSP), Interface Segregation Principle (ISP), and Dependency Inversion Principle (DIP) — help developers create clean and reusable code while reducing technical debt.</p><p>Golang, known for its simplicity, performance, and concurrency support, benefits greatly from the structured approach provided by SOLID principles. While Golang’s design encourages minimalism, applying SOLID concepts can further improve code quality, making it easier to extend, debug, and collaborate on large-scale projects.</p><p>In this article, we will explore how SOLID principles apply to Golang, providing practical examples and best practices to help developers write better Go code. Whether you are a beginner or an experienced Go developer, understanding and implementing these principles will enhance the maintainability and scalability of your applications.</p><h3>Single Responsibility Principle (SRP)</h3><p>A class, struct, or function should have only one responsibility, meaning it should have only one reason to change. This principle helps keep code modular and easier to maintain.</p><p>When a single module handles multiple responsibilities, changes in one part may unintentionally affect others, leading to a fragile codebase. SRP encourages splitting functionalities into smaller, independent units. This makes debugging, testing, and extending the code much easier.</p><p>For example, if a struct in Golang both retrieves user data from a database and handles user authentication, modifying authentication logic may require changes to the database logic, leading to unnecessary dependencies. Instead, separating these responsibilities into different structs ensures that each one remains focused on a single concern.</p><pre>type UserRepository struct {<br>    db *sql.DB<br>}<br><br>func (r *UserRepository) GetUserByID(id int) (*User, error) {<br>    // Fetch user from database<br>}<br><br>type AuthService struct {}<br><br>func (a *AuthService) Login(username, password string) bool {<br>    // Handle authentication logic<br>}</pre><h3>Open/Closed Principle (OCP)</h3><p>Software components should be open for extension but closed for modification. This means you should be able to add new functionality without modifying existing code.</p><p>Modifying existing code every time a new feature is added increases the risk of introducing bugs and breaking functionality. Instead, we should design our code in a way that allows extensions without altering the core logic.</p><p>In Golang, this is typically achieved through interfaces and composition. Instead of hardcoding specific implementations, you define abstractions (interfaces) that allow new implementations to be added later. This makes the code more flexible and adaptable to future requirements.</p><p>For example, if you have a function that sends notifications via email, and later you need to support SMS and push notifications, modifying the original function would violate OCP. Instead, defining a Notifier interface allows new notification types to be added without modifying the existing notification system.</p><pre>type Notifier interface {<br>    SendNotification(message string)<br>}<br><br>type EmailNotifier struct {}<br><br>func (e EmailNotifier) SendNotification(message string) {<br>    fmt.Println(&quot;Sending email:&quot;, message)<br>}<br><br>type SMSNotifier struct {}<br><br>func (s SMSNotifier) SendNotification(message string) {<br>    fmt.Println(&quot;Sending SMS:&quot;, message)<br>}<br><br>// Function that works with any Notifier without modifying existing code<br>func NotifyUser(n Notifier, message string) {<br>    n.SendNotification(message)<br>}</pre><h3>Liskov Substitution Principle (LSP)</h3><p>Subtypes should be replaceable for their base types without altering the correctness of the program.</p><p>This principle ensures that derived types (subtypes) can be used interchangeably with their base types without causing unexpected behavior. In Golang, since there is no classical inheritance, this applies to interfaces — any struct implementing an interface should behave as expected when used in place of another implementation.</p><p>For example, if we have an interface for geometric shapes with a method to calculate the area, any struct that implements this interface (e.g., Rectangle, Circle, Square) should work without requiring changes in the code using the interface.</p><p>Violating LSP leads to situations where certain implementations of an interface do not fully adhere to the expected behavior, causing errors when substituted in existing code.</p><pre>type Shape interface {<br>    Area() float64<br>}<br><br>type Rectangle struct {<br>    Width, Height float64<br>}<br><br>func (r Rectangle) Area() float64 {<br>    return r.Width * r.Height<br>}<br><br>type Square struct {<br>    Side float64<br>}<br><br>func (s Square) Area() float64 {<br>    return s.Side * s.Side<br>}<br><br>// Function works with any Shape<br>func PrintArea(s Shape) {<br>    fmt.Println(&quot;Area:&quot;, s.Area())<br>}</pre><h3>Interface Segregation Principle (ISP)</h3><p>Clients should not be forced to depend on interfaces they do not use. Instead of having large, generalized interfaces, break them into smaller, more specific interfaces.</p><p>If an interface has too many methods, implementing structs may be forced to define methods they don’t actually need. This creates unnecessary dependencies and makes the code more complex than necessary.</p><p>By keeping interfaces small and focused, each implementation only needs to provide the functionality it actually supports. This makes it easier to add new implementations without affecting unrelated parts of the code.</p><p>For example, instead of creating a single Worker interface that includes both Work() and Eat(), we can split it into separate Worker and Eater interfaces. This way, robots can implement Worker, and humans can implement both Worker and Eater without unnecessary dependencies.</p><p>Instead of a single interface with unrelated methods.</p><pre>type Worker interface {<br>    Work()<br>    Eat()<br>}</pre><p>Break it into smaller interface.</p><pre>type Worker interface {<br>    Work()<br>}<br><br>type Eater interface {<br>    Eat()<br>}<br><br>type Robot struct{}<br><br>func (r Robot) Work() {<br>    fmt.Println(&quot;Robot is working&quot;)<br>}<br><br>type Human struct{}<br><br>func (h Human) Work() {<br>    fmt.Println(&quot;Human is working&quot;)<br>}<br><br>func (h Human) Eat() {<br>    fmt.Println(&quot;Human is eating&quot;)<br>}</pre><h3>Dependency Inversion Principle (DIP)</h3><p>High-level modules should not depend on low-level modules. Both should depend on abstractions (interfaces), rather than concrete implementations.</p><p>DIP encourages the use of dependency injection to decouple high-level and low-level components. Instead of a high-level module being tightly coupled to a specific implementation, it should rely on an abstraction (interface). This makes the system more flexible and easier to modify.</p><p>For example, if a service directly depends on a MySQL database instance, changing to another database (e.g., PostgreSQL) would require modifying the service code. However, by introducing a Database interface, the service can work with any database implementation without requiring changes to its own logic.</p><p>This principle improves testability as well. Since dependencies are injected via interfaces, you can easily replace real implementations with mock objects for unit testing.</p><p>Instead of directly depending on a concrete database struct.</p><pre>type MySQLDatabase struct {}<br><br>func (m MySQLDatabase) Query(query string) string {<br>    return &quot;MySQL result&quot;<br>}<br><br>type Service struct {<br>    db Database<br>}<br><br>func (s Service) GetData() string {<br>    return s.db.Query(&quot;SELECT * FROM data&quot;)<br>}</pre><p>By defining a Database interface, we can swap MySQL with another database without modifying Service.</p><pre>type Database interface {<br>    Query(query string) string<br>}<br><br>func main() {<br>    mysql := MySQLDatabase{}<br>    service := Service{db: mysql}<br>    fmt.Println(service.GetData())<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcd4d7db6b59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object-Oriented Programming in Golang]]></title>
            <link>https://medium.com/@prawiraa.rivan/object-oriented-programming-in-golang-3591cb88791a?source=rss-82176cae42df------2</link>
            <guid isPermaLink="false">https://medium.com/p/3591cb88791a</guid>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[object-oriented-program]]></category>
            <dc:creator><![CDATA[Rivan Prawira]]></dc:creator>
            <pubDate>Mon, 17 Mar 2025 03:05:44 GMT</pubDate>
            <atom:updated>2025-03-17T03:05:44.361Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*VuSLTqjF25Im9dvDz8pJdw.jpeg" /><figcaption>source: Pinterest</figcaption></figure><p>Object-oriented programming (OOP) is a widely used programming paradigm that focuses on organizing code into objects that interact with each other to build applications. While Go is not a purely object-oriented language like Java or Python, it supports key OOP principles such as <strong>encapsulation, abstraction, inheritance, and polymorphism</strong>.</p><p>In this article, we will explore how to implement object-oriented programming concepts in Go using <strong>structs, methods, and interfaces</strong>.</p><h3>Class and Attribute</h3><p>Go does not have the class keyword like Java or Python, but <strong>structs</strong> in Go serve the same purpose as classes. A <strong>struct</strong> defines a blueprint for creating objects, and its <strong>attributes</strong> are defined as fields within the struct.</p><pre>type Animal struct {<br>  Name      string //Public attribute<br>  habitat   string //Private attribute<br>}</pre><p>Animal acts as a class, defined using a struct. In Animal, there are two attributes that is Name and habitat. Both have slightly difference which Name is a public attribute that can be accessed outside package, and habitat is a private attribute that only can be accessed within package. To create an object by instantiating a structure. We can create it like this.</p><pre>lion := Animal{Name: &quot;Leo&quot;, habitat: &quot;Forest&quot;}</pre><p>This creates an object lion with the values “Leo” and “Forest”.</p><p>In OOP, relationships between classes (structs) define how objects interact. Go supports the following relationships.</p><h4>Association</h4><p><strong>Association</strong> represents a relationship where one object interacts with another, but both objects exist independently. There is no strong ownership, meaning that even though objects communicate, they do not depend on each other for existence. For example, a Teacher and a Student can have an association where the teacher teaches a student, but both can exist separately. This is often implemented using references (pointers) or method parameters in Go.</p><pre>type Student struct {<br>  name  string<br>}<br><br>type Teacher struct {<br>  name  string<br>}<br><br>// Method demonstrating association<br>func (t Teacher) Teach(s Student) {<br>    fmt.Println(t.Name, &quot;is teaching&quot;, s.Name)<br>}<br><br>func main() {<br>    student := Student{Name: &quot;Alice&quot;}<br>    teacher := Teacher{Name: &quot;Mr. Smith&quot;}<br><br>    teacher.Teach(student) // Teacher uses Student but does not own it<br>}</pre><h4>Aggregation</h4><p><strong>Aggregation</strong> is a “has-a” relationship where one object contains another, but the contained object can still exist independently. The parent object does not have strong ownership over the child, meaning that if the parent is deleted, the child object remains. For instance, a Department can have multiple Employees, but an Employee can exist even if the Department is removed. In Go, this is typically implemented using struct fields without pointers.</p><pre>type Employee struct {<br>    Name  string<br>    Role  string<br>}<br><br>type Department struct {<br>    Name      string<br>    Employees []Employee // Aggregation: A department has employees<br>}<br><br>func main() {<br>    emp1 := Employee{Name: &quot;John&quot;, Role: &quot;Developer&quot;}<br>    emp2 := Employee{Name: &quot;Sarah&quot;, Role: &quot;Designer&quot;}<br><br>    dept := Department{<br>        Name:      &quot;IT Department&quot;,<br>        Employees: []Employee{emp1, emp2},<br>    }<br><br>    fmt.Println(&quot;Department:&quot;, dept.Name)<br>    fmt.Println(&quot;Employees:&quot;)<br>    for _, emp := range dept.Employees {<br>        fmt.Println(&quot;-&quot;, emp.Name, &quot;as&quot;, emp.Role)<br>    }<br>}</pre><h4>Composition</h4><p><strong>Composition</strong>, on the other hand, represents a strong “whole-part” relationship where the parent object fully owns the child, and the child cannot exist independently. If the parent is deleted, the child must also be deleted. A common example is a Car that has an Engine. The engine is an essential part of the car, and it does not exist separately. In Go, composition is usually implemented using struct fields with pointers to indicate strong ownership.</p><pre>type Engine struct {<br>    Type string<br>}<br><br>type Car struct {<br>    Brand  string<br>    Engine *Engine // Composition: Car owns Engine, and Engine cannot exist alone<br>}<br><br>func main() {<br>    car := Car{<br>        Brand:  &quot;Toyota&quot;,<br>        Engine: &amp;Engine{Type: &quot;V8&quot;},<br>    }<br><br>    fmt.Println(&quot;Car:&quot;, car.Brand)<br>    fmt.Println(&quot;Engine Type:&quot;, car.Engine.Type)<br>}</pre><p>In summary, association defines interactions without dependency, aggregation allows one object to contain another without full ownership, and composition represents a strict ownership relationship where the child object depends entirely on the parent. Understanding these relationships helps in designing modular and maintainable software systems in Go.</p><h3>Encapsulation</h3><p><strong>Encapsulation</strong> is the concept of wrapping data and methods inside a single unit. In Go, encapsulation is achieved by using a naming convention for fields and methods: Private fields and methods start with a lowercase letter, while public fields and methods start with an uppercase letter.</p><p>To maintain encapsulation, Go developers often use getter and setter methods to interact with private fields while ensuring controlled access. This approach prevents direct modification of data, reducing the risk of unintended changes and preserving data integrity.</p><pre>type Person struct {<br>    name string  // Private attribute<br>    Age  int     // Public attribute<br>}<br><br>// Constructor function<br>func NewPerson(name string, age int) Person {<br>    return Person{name: name, Age: age}<br>}<br><br>// Getter method<br>func (p Person) GetName() string {<br>    return p.name<br>}<br><br>// Setter method<br>func (p *Person) SetName(newName string) {<br>    p.name = newName<br>}<br><br>func main() {<br>    person := NewPerson(&quot;Alice&quot;, 25)<br><br>    fmt.Println(&quot;Name:&quot;, person.GetName()) // Access private attribute via getter<br>    person.SetName(&quot;Bob&quot;)                 // Modify private attribute via setter<br>    fmt.Println(&quot;Updated Name:&quot;, person.GetName())<br>}</pre><p>For example, a struct representing a Person might have a private field for the name, accessible only through a GetName() method. This way, if any validation or transformation is needed before returning the value, it can be done within the getter method. Similarly, a SetName() method ensures that only valid values are assigned to the field.</p><h3>Abstraction</h3><p><strong>Abstraction</strong> is an object-oriented programming (OOP) principle that focuses on hiding implementation details and exposing only essential features to the user. The goal of abstraction is to simplify complex systems by defining clear interfaces and behaviors while keeping the underlying logic hidden. This makes programs easier to understand, use, and maintain.</p><p>In Go, abstraction is primarily achieved using interfaces. An interface defines a set of methods that a type must implement, allowing different types to be used interchangeably without exposing their internal implementation. By working with interfaces instead of concrete types, developers can decouple different parts of the program, leading to a more flexible and maintainable design.</p><pre>// Define an abstract interface<br>type Shape interface {<br>    Area() float64<br>}<br><br>// Concrete implementation: Circle<br>type Circle struct {<br>    Radius float64<br>}<br><br>func (c Circle) Area() float64 {<br>    return math.Pi * c.Radius * c.Radius<br>}<br><br>// Concrete implementation: Rectangle<br>type Rectangle struct {<br>    Width, Height float64<br>}<br><br>func (r Rectangle) Area() float64 {<br>    return r.Width * r.Height<br>}<br><br>func main() {<br>    var s Shape<br><br>    s = Circle{Radius: 5}<br>    fmt.Println(&quot;Circle Area:&quot;, s.Area())<br><br>    s = Rectangle{Width: 4, Height: 6}<br>    fmt.Println(&quot;Rectangle Area:&quot;, s.Area())<br>}</pre><p>For example, consider an interface Shape that defines a method Area(). Different shapes like Circle and Rectangle can implement this interface, each providing its own logic for calculating the area. The user of the interface does not need to know the internal implementation of each shape; they only need to call the Area() method, trusting that it will return the correct result.</p><h3>Inheritance</h3><p><strong>Inheritance</strong> is a fundamental OOP concept where a class derives properties and behaviors from a parent class. Traditional object-oriented languages like Java and Python use inheritance to enable code reuse and hierarchical relationships between classes. However, Go does not support classical inheritance with the extends keyword. Instead, Go encourages the use of composition through struct embedding, which achieves similar functionality while avoiding the common pitfalls of inheritance.</p><pre>// Base struct<br>type Animal struct {<br>    Name string<br>}<br><br>// Method of the base struct<br>func (a Animal) Speak() {<br>    fmt.Println(a.Name, &quot;makes a sound&quot;)<br>}<br><br>// Derived struct using composition<br>type Dog struct {<br>    Animal // Embedding the Animal struct<br>    Breed  string<br>}<br><br>// Overriding Speak method<br>func (d Dog) Speak() {<br>    fmt.Println(d.Name, &quot;barks!&quot;)<br>}<br><br>func main() {<br>    dog := Dog{Animal: Animal{Name: &quot;Buddy&quot;}, Breed: &quot;Golden Retriever&quot;}<br><br>    dog.Speak() // Calls Dog&#39;s Speak method (Overridden)<br>    dog.Animal.Speak() // Calls Animal&#39;s Speak method (Base)<br>}</pre><p>In classical inheritance, a subclass automatically inherits fields and methods from a parent class. While this can promote code reuse, it often leads to tight coupling and makes the code harder to maintain, especially when deep inheritance chains are involved. Go addresses this by allowing struct embedding, where one struct contains another struct and directly accesses its fields and methods. This composition-over-inheritance approach makes code more modular and flexible.</p><h3>Polymorphism</h3><p><strong>Polymorphism</strong> is another essential OOP concept that allows different types to be treated as a common interface, enabling code generalization and flexibility. In Go, polymorphism is achieved through <strong>interfaces</strong>, which define a set of methods that a type must implement. Unlike traditional object-oriented languages that rely on explicit inheritance for polymorphism, Go’s interface-based approach promotes loose coupling and better separation of concerns.</p><pre>// Define an interface<br>type Animal interface {<br>    Speak()<br>}<br><br>// Structs implementing the interface<br>type Dog struct {<br>    Name string<br>}<br><br>func (d Dog) Speak() {<br>    fmt.Println(d.Name, &quot;barks!&quot;)<br>}<br><br>type Cat struct {<br>    Name string<br>}<br><br>func (c Cat) Speak() {<br>    fmt.Println(c.Name, &quot;meows!&quot;)<br>}<br><br>func main() {<br>    var animal Animal<br><br>    animal = Dog{Name: &quot;Buddy&quot;}<br>    animal.Speak() <br><br>    animal = Cat{Name: &quot;Whiskers&quot;}<br>    animal.Speak() <br>}</pre><p>With interfaces, Go allows different structs to be treated uniformly if they implement the same method signature. For example, an Animal interface with a Speak() method can be implemented by multiple structs, such as Dog and Cat, each defining its own version of Speak(). A function expecting an Animal interface as a parameter can then accept both Dog and Cat objects without knowing their specific types. This allows Go programs to be more scalable and extensible, as new types can be introduced without modifying existing code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3591cb88791a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn About Behavioral Design Pattern in Golang]]></title>
            <link>https://medium.com/@prawiraa.rivan/learn-about-behavioral-design-pattern-in-golang-209b2accc247?source=rss-82176cae42df------2</link>
            <guid isPermaLink="false">https://medium.com/p/209b2accc247</guid>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[behavioral-design-pattern]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Rivan Prawira]]></dc:creator>
            <pubDate>Mon, 10 Mar 2025 08:39:29 GMT</pubDate>
            <atom:updated>2025-03-10T08:39:29.323Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QM5iOpDNF_WeGHE3m0uEOQ.png" /><figcaption>source: Pinterest</figcaption></figure><p>In software development, design patterns provide proven solutions to common problems. Among these, behavioral design patterns focus on improving communication between objects, defining how they interact and distribute responsibilities efficiently. These patterns help create flexible and maintainable code by reducing dependencies and promoting clear separation of concerns.</p><p>Go, as a statically typed and concurrent programming language, presents a unique approach to implementing behavioral design patterns. Due to Go’s emphasis on simplicity, composition over inheritance, and the use of interfaces, many classic behavioral patterns are adapted differently compared to object-oriented languages like Java or C++.</p><p>This article explores various behavioral design patterns in Go, such as <strong>Chain of Responsibility</strong>, <strong>Command</strong>, <strong>Iterator</strong>, <strong>Mediator</strong>, <strong>Memento</strong>, <strong>Observer</strong>, <strong>State</strong>, <strong>Strategy</strong>, <strong>Template Method</strong>, and <strong>Visitor patterns</strong>, demonstrating how they can be implemented effectively using Go’s idiomatic constructs. Understanding these patterns will enhance your ability to write scalable and maintainable Go applications, especially in concurrent and distributed systems.</p><h3>Chain of Responsibility</h3><p>The <strong>Chain of Responsibility</strong> pattern is a behavioral design pattern that allows multiple objects to handle a request sequentially. Each handler either processes the request or passes it to the next handler in the chain.</p><p>In Golang, this pattern is useful for logging, event handling, middleware processing, and workflow automation where multiple processing steps might be involved.</p><h4>Animal Analogy</h4><p>In a forest ecosystem, animals often rely on each other to solve problems or fulfill needs. For example:</p><ol><li><strong>Rabbit</strong>: Tries to find food but can’t reach high branches.</li><li><strong>Deer</strong>: Can reach higher branches but can’t break tough nuts.</li><li><strong>Bear</strong>: Can break tough nuts and access hard-to-reach food sources.</li></ol><p>When a rabbit needs food, it first tries to solve the problem itself. If it can’t, it passes the request to the deer. If the deer can’t handle it, the request is passed to the bear. This forms a <strong>chain of responsibility</strong> where each animal tries to handle the request or passes it to the next animal in the chain.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// Request represents a food request in the forest<br>type Request struct {<br> foodType string<br>}<br><br>// Handler interface defines the method for handling requests<br>type Handler interface {<br> Handle(request *Request)<br> SetNext(handler Handler)<br>}<br><br>// BaseHandler provides default implementation for setting the next handler<br>type BaseHandler struct {<br> next Handler<br>}<br><br>func (b *BaseHandler) SetNext(handler Handler) {<br> b.next = handler<br>}<br><br>// Rabbit handles simple food requests<br>type Rabbit struct {<br> BaseHandler<br>}<br><br>func (r *Rabbit) Handle(request *Request) {<br> if request.foodType == &quot;Grass&quot; {<br>  fmt.Println(&quot;Rabbit: I can eat the grass!&quot;)<br>  return<br> }<br> if r.next != nil {<br>  fmt.Println(&quot;Rabbit: I can&#39;t handle this food. Passing it to the next animal.&quot;)<br>  r.next.Handle(request)<br> }<br>}<br><br>// Deer handles intermediate food requests<br>type Deer struct {<br> BaseHandler<br>}<br><br>func (d *Deer) Handle(request *Request) {<br> if request.foodType == &quot;Leaves&quot; {<br>  fmt.Println(&quot;Deer: I can reach the leaves!&quot;)<br>  return<br> }<br> if d.next != nil {<br>  fmt.Println(&quot;Deer: I can&#39;t handle this food. Passing it to the next animal.&quot;)<br>  d.next.Handle(request)<br> }<br>}<br><br>// Bear handles complex food requests<br>type Bear struct {<br> BaseHandler<br>}<br><br>func (b *Bear) Handle(request *Request) {<br> if request.foodType == &quot;Nuts&quot; {<br>  fmt.Println(&quot;Bear: I can break the nuts!&quot;)<br>  return<br> }<br> if b.next != nil {<br>  fmt.Println(&quot;Bear: I can&#39;t handle this food. No one else can help.&quot;)<br> }<br>}<br><br>func main() {<br> // Creating the chain of responsibility<br> rabbit := &amp;Rabbit{}<br> deer := &amp;Deer{}<br> bear := &amp;Bear{}<br><br> rabbit.SetNext(deer)<br> deer.SetNext(bear)<br><br> // Creating food requests<br> request1 := &amp;Request{foodType: &quot;Grass&quot;}  // Rabbit can handle<br> request2 := &amp;Request{foodType: &quot;Leaves&quot;} // Deer can handle<br> request3 := &amp;Request{foodType: &quot;Nuts&quot;}   // Bear can handle<br> request4 := &amp;Request{foodType: &quot;Fruit&quot;}  // No one can handle<br><br> // Handling the food requests<br> fmt.Println(&quot;Handling request for Grass:&quot;)<br> rabbit.Handle(request1) // Output: Rabbit: I can eat the grass!<br><br> fmt.Println(&quot;\nHandling request for Leaves:&quot;)<br> rabbit.Handle(request2) // Output: Rabbit: I can&#39;t handle this food. Passing it to the next animal.<br>                         //         Deer: I can reach the leaves!<br><br> fmt.Println(&quot;\nHandling request for Nuts:&quot;)<br> rabbit.Handle(request3) // Output: Rabbit: I can&#39;t handle this food. Passing it to the next animal.<br>                         //         Deer: I can&#39;t handle this food. Passing it to the next animal.<br>                         //         Bear: I can break the nuts!<br><br> fmt.Println(&quot;\nHandling request for Fruit:&quot;)<br> rabbit.Handle(request4) // Output: Rabbit: I can&#39;t handle this food. Passing it to the next animal.<br>                         //         Deer: I can&#39;t handle this food. Passing it to the next animal.<br>                         //         Bear: I can&#39;t handle this food. No one else can help.<br>}</pre><h4>Explanation</h4><ol><li><strong>Request</strong> — Represents a food request with a foodType (e.g., &quot;Grass&quot;, &quot;Leaves&quot;, &quot;Nuts&quot;).</li><li><strong>Handler Interface</strong> — Defines the Handle method for processing requests and the SetNext method for setting the next handler in the chain.</li><li><strong>Concrete Handlers </strong>—<strong> </strong>Include Rabbit, Deer, and Bear. Each handler checks if it can handle the request. If not, it passes the request to the next handler in the chain.</li><li><strong>Client Code</strong> — The main function demonstrates how the chain of responsibility processes food requests. If no handler can process the request (e.g., fruit), the request goes unhandled.</li></ol><h4>Where to Implements</h4><p>The pattern is beneficial when:</p><ol><li><strong>Processing requests dynamically</strong> — Requests go through multiple handlers until a suitable one is found.</li><li><strong>Avoiding tight coupling</strong> — The sender and receiver do not need direct knowledge of each other.</li><li><strong>Middleware and Filters</strong> — Used in HTTP middleware, authentication, validation, and logging.</li><li><strong>Flexible Request Handling</strong> — New handlers can be added without modifying existing ones.</li></ol><h3>Command</h3><p>The <strong>Command</strong> pattern is a behavioral design pattern that encapsulates a request as an object, allowing it to be parameterized, queued, and executed at a later time. It helps decouple the sender and receiver, making it easy to implement undo/redo, logging, and command execution scheduling.</p><h4>Animal Analogy</h4><p>In a forest, animals often communicate with each other to coordinate actions or respond to environmental changes. For example:</p><ul><li>A <strong>bird</strong> might issue a command to its flock to <strong>fly</strong> when it senses danger.</li><li>A <strong>lion</strong> might issue a command to its pride to <strong>hunt</strong> when prey is spotted.</li><li>A <strong>rabbit</strong> might issue a command to its family to <strong>hide</strong> when a predator is nearby.</li></ul><p>Each command is an object that encapsulates the action and the animal(s) that will perform it. This allows animals to issue commands dynamically and decouples the sender (e.g., the bird) from the receiver (e.g., the flock).</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// Animal represents an animal that can perform actions<br>type Animal struct {<br> name string<br>}<br><br>func (a *Animal) Fly() {<br> fmt.Printf(&quot;%s is flying.\n&quot;, a.name)<br>}<br><br>func (a *Animal) Hunt() {<br> fmt.Printf(&quot;%s is hunting.\n&quot;, a.name)<br>}<br><br>func (a *Animal) Hide() {<br> fmt.Printf(&quot;%s is hiding.\n&quot;, a.name)<br>}<br><br>// Command interface defines the Execute method<br>type Command interface {<br> Execute()<br>}<br><br>// FlyCommand encapsulates the Fly action<br>type FlyCommand struct {<br> animal *Animal<br>}<br><br>func (f *FlyCommand) Execute() {<br> f.animal.Fly()<br>}<br><br>// HuntCommand encapsulates the Hunt action<br>type HuntCommand struct {<br> animal *Animal<br>}<br><br>func (h *HuntCommand) Execute() {<br> h.animal.Hunt()<br>}<br><br>// HideCommand encapsulates the Hide action<br>type HideCommand struct {<br> animal *Animal<br>}<br><br>func (hi *HideCommand) Execute() {<br> hi.animal.Hide()<br>}<br><br>// AnimalGroup represents a group of animals that can execute commands<br>type AnimalGroup struct {<br> commands []Command<br>}<br><br>func (ag *AnimalGroup) AddCommand(command Command) {<br> ag.commands = append(ag.commands, command)<br>}<br><br>func (ag *AnimalGroup) ExecuteCommands() {<br> for _, command := range ag.commands {<br>  command.Execute()<br> }<br>}<br><br>func main() {<br> // Creating animals<br> bird := &amp;Animal{name: &quot;Eagle&quot;}<br> lion := &amp;Animal{name: &quot;Simba&quot;}<br> rabbit := &amp;Animal{name: &quot;Bunny&quot;}<br><br> // Creating commands<br> flyCommand := &amp;FlyCommand{animal: bird}<br> huntCommand := &amp;HuntCommand{animal: lion}<br> hideCommand := &amp;HideCommand{animal: rabbit}<br><br> // Creating an animal group and adding commands<br> animalGroup := &amp;AnimalGroup{}<br> animalGroup.AddCommand(flyCommand)<br> animalGroup.AddCommand(huntCommand)<br> animalGroup.AddCommand(hideCommand)<br><br> // Executing the commands<br> animalGroup.ExecuteCommands()<br>}</pre><h4>Explanation</h4><ol><li><strong>Animal</strong> — Represents an animal that can perform actions (e.g., fly, hunt, hide).</li><li><strong>Command Interface</strong> — Defines the Execute method that all commands must implement.</li><li><strong>Concrete Commands</strong> — There are three commands (FlyCommand, HuntCommand, and Hide Command). Each command holds a reference to the animal that will perform the action.</li><li><strong>Animal Group</strong> — Represents a group of animals that can execute commands. It can queue commands and execute them in sequence.</li><li><strong>Client Code</strong> — The main function demonstrates how animals issue and execute commands to perform actions.</li></ol><h4>Where to Implements</h4><p>This pattern is useful in:</p><ol><li><strong>Undo/Redo functionality</strong> — Keeps track of executed commands and reverts them if necessary.</li><li><strong>Task Queues &amp; Scheduling</strong> — Allows commands to be stored and executed later.</li><li><strong>Macro Commands</strong> — Groups multiple commands into a single action.</li><li><strong>Decoupling Senders and Receivers</strong> — Enables flexible command execution without hardcoding dependencies.</li><li><strong>Remote Controls &amp; UI Buttons</strong> — Allows dynamic command binding to user inputs.</li></ol><h3>Iterator</h3><p>The <strong>Iterator</strong> pattern is a behavioral design pattern that provides a way to sequentially access elements in a collection without exposing its underlying representation. This pattern is useful for traversing different data structures (like lists, trees, or maps) in a consistent way.</p><h4>Animal Analogy</h4><p>Imagine a <strong>flock of birds</strong> migrating across continents. The flock is a collection of birds, and you want to observe each bird in the flock without knowing how the flock is organized internally (e.g., whether it’s stored in a list, array, or tree). The <strong>Iterator Pattern</strong> can be used to traverse the flock and observe each bird one by one.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// Bird represents a bird in the flock<br>type Bird struct {<br> name string<br>}<br><br>func (b *Bird) Name() string {<br> return b.name<br>}<br><br>// Flock represents a collection of birds<br>type Flock struct {<br> birds []*Bird<br>}<br><br>func (f *Flock) AddBird(bird *Bird) {<br> f.birds = append(f.birds, bird)<br>}<br><br>// Iterator interface defines methods for traversing the flock<br>type Iterator interface {<br> HasNext() bool<br> Next() *Bird<br>}<br><br>// FlockIterator implements the Iterator interface for the Flock<br>type FlockIterator struct {<br> flock    *Flock<br> position int<br>}<br><br>func (fi *FlockIterator) HasNext() bool {<br> return fi.position &lt; len(fi.flock.birds)<br>}<br><br>func (fi *FlockIterator) Next() *Bird {<br> if fi.HasNext() {<br>  bird := fi.flock.birds[fi.position]<br>  fi.position++<br>  return bird<br> }<br> return nil<br>}<br><br>func main() {<br> // Creating a flock of birds<br> flock := &amp;Flock{}<br> flock.AddBird(&amp;Bird{name: &quot;Eagle&quot;})<br> flock.AddBird(&amp;Bird{name: &quot;Sparrow&quot;})<br> flock.AddBird(&amp;Bird{name: &quot;Parrot&quot;})<br><br> // Creating an iterator for the flock<br> iterator := &amp;FlockIterator{flock: flock, position: 0}<br><br> // Traversing the flock using the iterator<br> fmt.Println(&quot;Observing the flock:&quot;)<br> for iterator.HasNext() {<br>  bird := iterator.Next()<br>  fmt.Printf(&quot;Observing %s\n&quot;, bird.Name())<br> }<br>}</pre><h4>Explanation</h4><ol><li><strong>Birds</strong> — Represents a bird in the flock with a name.</li><li><strong>Flock</strong> — Represents a collection of birds. It has a method AddBird to add birds to the flock.</li><li><strong>Iterator Interface</strong> — Defines the HasNext and Next methods for traversing the flock.</li><li><strong>FlockIterator</strong> — Implements the Iterator interface for the Flock. It keeps track of the current position in the flock and provides methods to traverse the birds.</li><li><strong>Client Code</strong> — The main function demonstrates how to use the iterator to traverse the flock and observe each bird.</li></ol><h4>Where to Implements</h4><p>This pattern is beneficial when:</p><ol><li><strong>Abstracting traversal logic</strong> — Allows different types of collections to be iterated in a uniform way.</li><li><strong>Providing multiple traversal algorithms</strong> — Example: Forward, backward, or filtered iteration.</li><li><strong>Encapsulating iteration state</strong> — Hides complex internal data structure details.</li><li><strong>Reducing direct dependency on collection structure</strong> — The client does not need to know how data is stored.</li></ol><h3>Mediator</h3><p>The <strong>Mediator</strong> pattern is a behavioral design pattern that promotes loose coupling by centralizing communication between objects. Instead of objects communicating directly, they interact through a <strong>mediator</strong>, reducing dependencies and making the system more maintainable.</p><h4>Animal Analogy</h4><p>Imagine a <strong>forest ecosystem</strong> where animals need to communicate with each other to coordinate activities like hunting, warning about predators, or finding food. Instead of animals communicating directly with each other (which can become chaotic), they use a <strong>mediator</strong> (e.g., a central communication system) to relay messages. For example:</p><ul><li>A <strong>lion</strong> wants to warn other animals about a predator.</li><li>A <strong>bird</strong> wants to notify others about food.</li><li>A <strong>rabbit</strong> wants to alert others about danger.</li></ul><p>The <strong>Mediator Pattern</strong> can be used to centralize this communication, ensuring that animals don’t need to know about each other directly.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// Mediator interface defines the method for sending messages<br>type Mediator interface {<br> SendMessage(sender Animal, message string)<br>}<br><br>// Animal represents an animal in the forest<br>type Animal struct {<br> name     string<br> mediator Mediator<br>}<br><br>func (a *Animal) Send(message string) {<br> fmt.Printf(&quot;%s sends: %s\n&quot;, a.name, message)<br> a.mediator.SendMessage(a, message)<br>}<br><br>func (a *Animal) Receive(message string) {<br> fmt.Printf(&quot;%s receives: %s\n&quot;, a.name, message)<br>}<br><br>// ForestMediator implements the Mediator interface<br>type ForestMediator struct {<br> animals []*Animal<br>}<br><br>func (fm *ForestMediator) Register(animal *Animal) {<br> fm.animals = append(fm.animals, animal)<br>}<br><br>func (fm *ForestMediator) SendMessage(sender *Animal, message string) {<br> for _, animal := range fm.animals {<br>  if animal != sender {<br>   animal.Receive(message)<br>  }<br> }<br>}<br><br>func main() {<br> // Creating the mediator<br> mediator := &amp;ForestMediator{}<br><br> // Creating animals<br> lion := &amp;Animal{name: &quot;Lion&quot;, mediator: mediator}<br> bird := &amp;Animal{name: &quot;Bird&quot;, mediator: mediator}<br> rabbit := &amp;Animal{name: &quot;Rabbit&quot;, mediator: mediator}<br><br> // Registering animals with the mediator<br> mediator.Register(lion)<br> mediator.Register(bird)<br> mediator.Register(rabbit)<br><br> // Animals sending messages<br> lion.Send(&quot;There&#39;s a predator nearby!&quot;)<br> bird.Send(&quot;I found food near the river!&quot;)<br> rabbit.Send(&quot;I sense danger in the bushes!&quot;)<br>}</pre><h4>Explanation</h4><ol><li><strong>Mediator Interface</strong> — Defines the SendMessage method for relaying messages between animals.</li><li><strong>Animal</strong> — Represents an animal in the forest. Each animal has a name and a reference to the mediator. Animals use the Send method to send messages and the Receive method to receive messages.</li><li><strong>ForestMediator</strong> — Implements the Mediator interface. Keeps track of all registered animals and relays messages between them.</li><li><strong>Client Code</strong> — The main function demonstrates how animals communicate through the mediator without directly referencing each other.</li></ol><h4>Where to Implements</h4><p>This pattern is useful when:</p><ol><li><strong>Reducing direct dependencies</strong> between multiple objects.</li><li><strong>Managing complex object interactions</strong> in chat systems, air traffic control, event handling, or UI components.</li><li><strong>Enhancing maintainability</strong> by encapsulating communication logic in a central entity.</li><li><strong>Improving scalability</strong> by making it easier to modify or add new components without breaking existing ones.</li></ol><h3>Memento</h3><p>The <strong>Memento</strong> pattern is a behavioral design pattern that allows capturing and restoring an object’s state without exposing its internal details. This pattern is useful for implementing undo/redo functionality in applications.</p><h4>Animal Analogy</h4><p>Imagine a <strong>wildlife simulation</strong> where animals have different states, such as:</p><ul><li><strong>Hunger level</strong>: How hungry the animal is.</li><li><strong>Energy level</strong>: How much energy the animal has.</li><li><strong>Mood</strong>: The animal’s current mood (e.g., happy, scared).</li></ul><p>Sometimes, an animal might need to “remember” its previous state (e.g., before a predator attack or after finding food). The <strong>Memento Pattern</strong> can be used to save and restore the animal’s state.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// AnimalState represents the state of an animal<br>type AnimalState struct {<br> Hunger int<br> Energy int<br> Mood   string<br>}<br><br>// Animal represents an animal in the simulation<br>type Animal struct {<br> state AnimalState<br>}<br><br>func (a *Animal) SetState(state AnimalState) {<br> a.state = state<br>}<br><br>func (a *Animal) GetState() AnimalState {<br> return a.state<br>}<br><br>func (a *Animal) CreateMemento() *Memento {<br> return &amp;Memento{state: a.state}<br>}<br><br>func (a *Animal) RestoreMemento(memento *Memento) {<br> a.state = memento.GetState()<br>}<br><br>func (a *Animal) DisplayState() {<br> fmt.Printf(&quot;Hunger: %d, Energy: %d, Mood: %s\n&quot;, a.state.Hunger, a.state.Energy, a.state.Mood)<br>}<br><br>// Memento represents a snapshot of the animal&#39;s state<br>type Memento struct {<br> state AnimalState<br>}<br><br>func (m *Memento) GetState() AnimalState {<br> return m.state<br>}<br><br>// Caretaker manages the mementos<br>type Caretaker struct {<br> mementos []*Memento<br>}<br><br>func (c *Caretaker) AddMemento(memento *Memento) {<br> c.mementos = append(c.mementos, memento)<br>}<br><br>func (c *Caretaker) GetMemento(index int) *Memento {<br> if index &lt; len(c.mementos) {<br>  return c.mementos[index]<br> }<br> return nil<br>}<br><br>func main() {<br> // Creating an animal<br> lion := &amp;Animal{}<br> caretaker := &amp;Caretaker{}<br><br> // Setting the initial state of the lion<br> lion.SetState(AnimalState{Hunger: 50, Energy: 100, Mood: &quot;Happy&quot;})<br> fmt.Println(&quot;Initial state:&quot;)<br> lion.DisplayState()<br><br> // Saving the state to a memento<br> caretaker.AddMemento(lion.CreateMemento())<br><br> // Changing the lion&#39;s state (e.g., after a predator attack)<br> lion.SetState(AnimalState{Hunger: 80, Energy: 30, Mood: &quot;Scared&quot;})<br> fmt.Println(&quot;\nState after predator attack:&quot;)<br> lion.DisplayState()<br><br> // Restoring the lion&#39;s state from the memento<br> lion.RestoreMemento(caretaker.GetMemento(0))<br> fmt.Println(&quot;\nState after restoration:&quot;)<br> lion.DisplayState()<br>}</pre><h4>Explanation</h4><ol><li><strong>AnimalState</strong> — Represents the state of an animal, including hunger, energy, and mood.</li><li><strong>Animal</strong> — Represents an animal in the simulation. It has methods to set and get its state, create a memento (snapshot), and restore its state from a memento.</li><li><strong>Memento</strong> — Represents a snapshot of the animal’s state. It stores the state and provides a method to retrieve it.</li><li><strong>Caretaker</strong> — Manages the mementos (snapshots) and provides methods to add and retrieve them.</li><li><strong>Client Code</strong> — The main function demonstrates how to save and restore the lion’s state using the Memento Pattern.</li></ol><h4>Where to Implements</h4><p>This pattern is useful in scenarios where:</p><ol><li><strong>State needs to be saved and restored later</strong> — Example: Undo/redo functionality in text editors.</li><li><strong>Object internals should not be exposed</strong> — Keeps the object encapsulated.</li><li><strong>Maintaining history of changes</strong> — Useful in games, transaction systems, or configuration changes.</li><li><strong>Checkpointing and rollback functionality</strong> — In databases, workflows, or command processing systems.</li></ol><h3>Observer</h3><p>The <strong>Observer</strong> pattern is a behavioral design pattern that allows an object (the subject) to notify multiple observers about changes in its state. It is commonly used for event-driven programming, pub-sub models, and real-time notifications.</p><h4>Animal Analogy</h4><p>Imagine a <strong>forest ecosystem</strong> where animals need to be alerted about potential dangers, such as the presence of a predator. For example:</p><ul><li>A <strong>lion</strong> (the predator) enters the area.</li><li>Other animals (e.g., deer, rabbits, birds) need to be notified so they can take appropriate action (e.g., run, hide, fly away).</li></ul><p>The <strong>Observer Pattern</strong> can be used to implement this warning system. The lion is the <strong>subject</strong>, and the other animals are the <strong>observers</strong>. When the lion enters the area, it notifies all the observers, and they react accordingly.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// Subject interface defines methods for managing observers<br>type Subject interface {<br> Register(observer Observer)<br> Deregister(observer Observer)<br> Notify()<br>}<br><br>// Observer interface defines the method for receiving updates<br>type Observer interface {<br> Update(string)<br>}<br><br>// Lion represents the subject (the predator)<br>type Lion struct {<br> observers []Observer<br> location  string<br>}<br><br>func (l *Lion) Register(observer Observer) {<br> l.observers = append(l.observers, observer)<br>}<br><br>func (l *Lion) Deregister(observer Observer) {<br> for i, obs := range l.observers {<br>  if obs == observer {<br>   l.observers = append(l.observers[:i], l.observers[i+1:]...)<br>   break<br>  }<br> }<br>}<br><br>func (l *Lion) Notify() {<br> for _, observer := range l.observers {<br>  observer.Update(l.location)<br> }<br>}<br><br>func (l *Lion) EnterArea(location string) {<br> l.location = location<br> fmt.Printf(&quot;Lion has entered the %s!\n&quot;, location)<br> l.Notify()<br>}<br><br>// Deer represents an observer (prey)<br>type Deer struct {<br> name string<br>}<br><br>func (d *Deer) Update(location string) {<br> fmt.Printf(&quot;%s the Deer: Lion is in the %s! Running away!\n&quot;, d.name, location)<br>}<br><br>// Rabbit represents an observer (prey)<br>type Rabbit struct {<br> name string<br>}<br><br>func (r *Rabbit) Update(location string) {<br> fmt.Printf(&quot;%s the Rabbit: Lion is in the %s! Hiding in the bushes!\n&quot;, r.name, location)<br>}<br><br>// Bird represents an observer (prey)<br>type Bird struct {<br> name string<br>}<br><br>func (b *Bird) Update(location string) {<br> fmt.Printf(&quot;%s the Bird: Lion is in the %s! Flying away!\n&quot;, b.name, location)<br>}<br><br>func main() {<br> // Creating the subject (lion)<br> lion := &amp;Lion{}<br><br> // Creating observers (prey animals)<br> deer := &amp;Deer{name: &quot;Bambi&quot;}<br> rabbit := &amp;Rabbit{name: &quot;Thumper&quot;}<br> bird := &amp;Bird{name: &quot;Tweety&quot;}<br><br> // Registering observers with the subject<br> lion.Register(deer)<br> lion.Register(rabbit)<br> lion.Register(bird)<br><br> // Lion enters an area and notifies observers<br> lion.EnterArea(&quot;Savanna&quot;)<br><br> // Deregistering an observer (e.g., the bird flies away permanently)<br> lion.Deregister(bird)<br><br> // Lion enters another area and notifies remaining observers<br> lion.EnterArea(&quot;Forest&quot;)<br>}</pre><h4>Explanation</h4><ol><li><strong>Subject (Lion) — </strong>Represents the object that other animals observe. It maintains a list of observers and notifies them when its state changes (e.g., when it enters a new area).</li><li><strong>Observer Interface — </strong>Defines the Update method that all observers must implement.</li><li><strong>Concrete Observers (Deer, Rabbit, Bird) — </strong>Represent the animals that need to be notified about the lion’s presence. Each observer implements the Update method to react to the lion’s presence (e.g., run, hide, fly away).</li><li><strong>Client Code — </strong>The main function demonstrates how the lion notifies the observers when it enters a new area.</li></ol><h4>Where to Implements</h4><p>This pattern is useful in scenarios where:</p><ol><li><strong>Multiple objects need to react to a state change</strong> — Example: A notification system where multiple users receive updates.</li><li><strong>Decoupling event producers from consumers</strong> — Example: UI components updating based on a data model.</li><li><strong>Implementing pub-sub models</strong> — Example: Chat applications, stock market updates, or event-driven architectures.</li><li><strong>Asynchronous notifications</strong> — Example: Email alerts, logging systems, or real-time monitoring.</li></ol><h3>State</h3><p>The <strong>State</strong> pattern is a behavioral design pattern that allows an object to change its behavior dynamically based on its internal state. Instead of using multiple if-else conditions, it delegates state-specific behavior to separate state objects.</p><h4>Animal Analogy</h4><p>In a wildlife ecosystem where animals have different states, such as:</p><ul><li><strong>Hungry</strong>: The animal is looking for food.</li><li><strong>Tired</strong>: The animal is resting or sleeping.</li><li><strong>Scared</strong>: The animal is running away from danger.</li></ul><p>The <strong>State Pattern</strong> can be used to model how an animal’s behavior changes based on its current state. For example:</p><ul><li>A <strong>lion</strong> might hunt when hungry, sleep when tired, and run when scared.</li><li>A <strong>rabbit</strong> might forage when hungry, hide when tired, and flee when scared.</li></ul><pre>package main<br><br>import &quot;fmt&quot;<br><br>// AnimalState interface defines the behavior of an animal based on its state<br>type AnimalState interface {<br> Act()<br>}<br><br>// HungryState represents the animal&#39;s behavior when hungry<br>type HungryState struct {<br> animal *Animal<br>}<br><br>func (h *HungryState) Act() {<br> fmt.Printf(&quot;%s is looking for food.\n&quot;, h.animal.name)<br>}<br><br>// TiredState represents the animal&#39;s behavior when tired<br>type TiredState struct {<br> animal *Animal<br>}<br><br>func (t *TiredState) Act() {<br> fmt.Printf(&quot;%s is resting.\n&quot;, t.animal.name)<br>}<br><br>// ScaredState represents the animal&#39;s behavior when scared<br>type ScaredState struct {<br> animal *Animal<br>}<br><br>func (s *ScaredState) Act() {<br> fmt.Printf(&quot;%s is running away!\n&quot;, s.animal.name)<br>}<br><br>// Animal represents an animal in the simulation<br>type Animal struct {<br> name  string<br> state AnimalState<br>}<br><br>func (a *Animal) SetState(state AnimalState) {<br> a.state = state<br>}<br><br>func (a *Animal) Act() {<br> a.state.Act()<br>}<br><br>func main() {<br> // Creating a lion<br> lion := &amp;Animal{name: &quot;Simba&quot;}<br><br> // Changing the lion&#39;s state and observing its behavior<br> lion.SetState(&amp;HungryState{lion})<br> lion.Act() // Output: Simba is looking for food.<br><br> lion.SetState(&amp;TiredState{lion})<br> lion.Act() // Output: Simba is resting.<br><br> lion.SetState(&amp;ScaredState{lion})<br> lion.Act() // Output: Simba is running away!<br><br> // Creating a rabbit<br> rabbit := &amp;Animal{name: &quot;Thumper&quot;}<br><br> // Changing the rabbit&#39;s state and observing its behavior<br> rabbit.SetState(&amp;HungryState{rabbit})<br> rabbit.Act() // Output: Thumper is looking for food.<br><br> rabbit.SetState(&amp;TiredState{rabbit})<br> rabbit.Act() // Output: Thumper is resting.<br><br> rabbit.SetState(&amp;ScaredState{rabbit})<br> rabbit.Act() // Output: Thumper is running away!<br>}</pre><h4>Explanation</h4><ol><li><strong>AnimalState Interface — </strong>Defines the Act method that all states must implement.</li><li><strong>Concrete States — </strong>There are three states (HungryState, TiredState, and ScaredState). Each represent animal’s behavior.</li><li><strong>Animal — </strong>Represents an animal in the simulation. It has a state field that determines its current behavior. The SetState method changes the animal’s state, and the Act method delegates the behavior to the current state.</li><li><strong>Client Code — </strong>The main function demonstrates how an animal’s behavior changes based on its state.</li></ol><h4>Where to Implements</h4><p>This pattern is useful in scenarios where:</p><ol><li><strong>An object’s behavior depends on its state</strong> — Example: Traffic lights changing behavior based on color.</li><li><strong>State transitions are frequent and complex</strong> — Example: Media players switching between play, pause, and stop.</li><li><strong>Avoiding large conditional statements (</strong><strong>if-else or </strong><strong>switch-case)</strong> – Keeps the code <strong>clean and modular</strong>.</li><li><strong>Finite State Machines (FSMs)</strong> – Example: Game character states (running, jumping, attacking).</li></ol><h3>Strategy</h3><p>The <strong>Strategy</strong> pattern is a behavioral design pattern that allows an object to choose a behavior at runtime by defining a family of interchangeable algorithms. This pattern helps avoid if-else statements by encapsulating different strategies into separate classes.</p><h4>Animal Analogy</h4><p>In a wildlife ecosystem where different animals use different strategies to hunt for food. For example:</p><ul><li>A <strong>lion</strong> uses a <strong>stalk-and-pounce</strong> strategy.</li><li>A <strong>wolf</strong> uses a <strong>pack-hunting</strong> strategy.</li><li>An <strong>eagle</strong> uses a <strong>swoop-and-grab</strong> strategy.</li></ul><p>The <strong>Strategy Pattern</strong> can be used to encapsulate these hunting strategies and allow animals to switch between them dynamically.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// HuntingStrategy interface defines the method for hunting<br>type HuntingStrategy interface {<br> Hunt()<br>}<br><br>// StalkAndPounceStrategy represents the lion&#39;s hunting strategy<br>type StalkAndPounceStrategy struct{}<br><br>func (s *StalkAndPounceStrategy) Hunt() {<br> fmt.Println(&quot;The lion is stalking and pouncing on its prey!&quot;)<br>}<br><br>// PackHuntingStrategy represents the wolf&#39;s hunting strategy<br>type PackHuntingStrategy struct{}<br><br>func (p *PackHuntingStrategy) Hunt() {<br> fmt.Println(&quot;The wolf is hunting with its pack!&quot;)<br>}<br><br>// SwoopAndGrabStrategy represents the eagle&#39;s hunting strategy<br>type SwoopAndGrabStrategy struct{}<br><br>func (s *SwoopAndGrabStrategy) Hunt() {<br> fmt.Println(&quot;The eagle is swooping down and grabbing its prey!&quot;)<br>}<br><br>// Animal represents an animal in the simulation<br>type Animal struct {<br> name    string<br> strategy HuntingStrategy<br>}<br><br>func (a *Animal) SetStrategy(strategy HuntingStrategy) {<br> a.strategy = strategy<br>}<br><br>func (a *Animal) Hunt() {<br> fmt.Printf(&quot;%s is hunting: &quot;, a.name)<br> a.strategy.Hunt()<br>}<br><br>func main() {<br> // Creating animals with different hunting strategies<br> lion := &amp;Animal{name: &quot;Simba&quot;, strategy: &amp;StalkAndPounceStrategy{}}<br> wolf := &amp;Animal{name: &quot;Fang&quot;, strategy: &amp;PackHuntingStrategy{}}<br> eagle := &amp;Animal{name: &quot;Eddy&quot;, strategy: &amp;SwoopAndGrabStrategy{}}<br><br> // Animals hunting using their strategies<br> lion.Hunt()  // Output: Simba is hunting: The lion is stalking and pouncing on its prey!<br> wolf.Hunt()  // Output: Fang is hunting: The wolf is hunting with its pack!<br> eagle.Hunt() // Output: Eddy is hunting: The eagle is swooping down and grabbing its prey!<br><br> // Changing the lion&#39;s hunting strategy dynamically<br> lion.SetStrategy(&amp;PackHuntingStrategy{})<br> lion.Hunt() // Output: Simba is hunting: The wolf is hunting with its pack!<br>}</pre><h4>Explanation</h4><ol><li><strong>HuntingStrategy Interface — </strong>Defines the Hunt method that all hunting strategies must implement.</li><li><strong>Concrete Strategies — </strong>There are three strategies (StalkAndPounceStrategy, PackHuntingStrategy, SwoopAndGrabStrategy). Each strategy encapsulates a specific hunting behavior.</li><li><strong>Animal — </strong>Represents an animal in the simulation. It has a strategy field that determines its hunting behavior. The SetStrategy method allows the animal to switch strategies dynamically, and the Hunt method delegates the behavior to the current strategy.</li><li><strong>Client Code — </strong>The main function demonstrates how animals use different hunting strategies and how strategies can be changed dynamically.</li></ol><h4>Where to Implements</h4><p>This pattern is useful in scenarios where:</p><ol><li><strong>Multiple algorithms exist for a task</strong> — Example: Sorting data using different methods (quick sort, merge sort, bubble sort).</li><li><strong>Behavior needs to change dynamically</strong> — Example: Payment methods (credit card, PayPal, crypto).</li><li><strong>Avoiding long </strong><strong>if-else statements</strong> – Keeps the code <strong>clean and modular</strong>.</li><li><strong>Encapsulating related behaviors</strong> – Example: Different driving behaviors in a self-driving car.</li></ol><h3>Template Method</h3><p>The <strong>Template Method</strong> pattern is a behavioral design pattern that defines the skeleton of an algorithm in a base class but lets subclasses override specific steps of the algorithm without changing its structure.</p><h4>Animal Analogy</h4><p>In a wildlife ecosystem<strong> </strong>where different animals follow a daily routine, but the specific steps of the routine vary depending on the animal. For example:</p><ul><li>A <strong>lion</strong>’s daily routine might involve hunting, eating, and sleeping.</li><li>A <strong>rabbit</strong>’s daily routine might involve foraging, eating, and hiding.</li><li>A <strong>bird</strong>’s daily routine might involve flying, eating, and nesting.</li></ul><p>The <strong>Template Method Pattern</strong> can be used to define the skeleton of the daily routine in a base class, while allowing subclasses to implement the specific steps.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// Animal represents the base class for all animals<br>type Animal struct {<br> name string<br>}<br><br>func (a *Animal) DailyRoutine() {<br> a.WakeUp()<br> a.Eat()<br> a.Act()<br> a.Sleep()<br>}<br><br>func (a *Animal) WakeUp() {<br> fmt.Printf(&quot;%s wakes up.\n&quot;, a.name)<br>}<br><br>func (a *Animal) Eat() {<br> fmt.Printf(&quot;%s eats.\n&quot;, a.name)<br>}<br><br>func (a *Animal) Sleep() {<br> fmt.Printf(&quot;%s sleeps.\n&quot;, a.name)<br>}<br><br>// Act is a placeholder method to be overridden by subclasses<br>func (a *Animal) Act() {<br> // Default behavior (can be overridden)<br> fmt.Printf(&quot;%s does nothing.\n&quot;, a.name)<br>}<br><br>// Lion represents a lion with a specific daily routine<br>type Lion struct {<br> Animal<br>}<br><br>func (l *Lion) Act() {<br> fmt.Printf(&quot;%s hunts for prey.\n&quot;, l.name)<br>}<br><br>// Rabbit represents a rabbit with a specific daily routine<br>type Rabbit struct {<br> Animal<br>}<br><br>func (r *Rabbit) Act() {<br> fmt.Printf(&quot;%s forages for food.\n&quot;, r.name)<br>}<br><br>// Bird represents a bird with a specific daily routine<br>type Bird struct {<br> Animal<br>}<br><br>func (b *Bird) Act() {<br> fmt.Printf(&quot;%s flies around.\n&quot;, b.name)<br>}<br><br>func main() {<br> // Creating animals<br> lion := &amp;Lion{Animal{name: &quot;Simba&quot;}}<br> rabbit := &amp;Rabbit{Animal{name: &quot;Thumper&quot;}}<br> bird := &amp;Bird{Animal{name: &quot;Tweety&quot;}}<br><br> // Executing daily routines<br> fmt.Println(&quot;Lion&#39;s daily routine:&quot;)<br> lion.DailyRoutine()<br><br> fmt.Println(&quot;\nRabbit&#39;s daily routine:&quot;)<br> rabbit.DailyRoutine()<br><br> fmt.Println(&quot;\nBird&#39;s daily routine:&quot;)<br> bird.DailyRoutine()<br>}</pre><h4>Explanation</h4><ol><li><strong>Animal (Base Class) — </strong>Defines the skeleton of the daily routine using the DailyRoutine method. Provides default implementations for common steps like WakeUp, Eat, and Sleep. The Act method is a placeholder that subclasses can override to define specific behaviors.</li><li><strong>Concrete Subclasses (Lion, Rabbit, Bird) — </strong>Each subclass overrides the Act method to define its specific behavior (e.g., hunting, foraging, flying). The DailyRoutine method remains unchanged, ensuring a consistent structure for all animals.</li><li><strong>Client Code — </strong>The main function demonstrates how each animal follows its daily routine, with specific behaviors defined by the subclasses.</li></ol><h4>Where to Implements</h4><p>This pattern is useful when:</p><ol><li><strong>You have a series of steps that are mostly the same but need slight variations</strong> — Example: Cooking recipes with different ingredients but a fixed process.</li><li><strong>Avoiding code duplication across similar classes</strong> — Common behavior is defined in a base class, and variations are in subclasses.</li><li><strong>Ensuring a specific execution order of steps</strong> — Certain steps must always run in a defined order.</li><li><strong>Promoting code reuse and maintainability</strong> — Reduces redundant code and enforces a consistent process.</li></ol><h3>Visitor</h3><p>The <strong>Visitor</strong> pattern is a behavioral design pattern that allows adding new operations to objects without modifying their structure. Instead of defining the behavior inside the object itself, a separate visitor class is used to execute operations.</p><h4>Animal Analogy</h4><p>In a forest ecosystem where animals interact with their environment in different ways. For example:</p><ul><li>A <strong>lion</strong> might interact by marking its territory.</li><li>A <strong>bird</strong> might interact by building a nest.</li><li>A <strong>rabbit</strong> might interact by digging a burrow.</li></ul><p>Instead of adding these interaction methods directly to each animal class, we can use the <strong>Visitor Pattern</strong> to define a <strong>ForestVisitor</strong> that encapsulates these behaviors. This way, we can add new interactions without modifying the animal classes.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// Animal interface defines the Accept method for the Visitor Pattern<br>type Animal interface {<br> Accept(visitor ForestVisitor)<br>}<br><br>// ForestVisitor interface defines the Visit methods for each animal type<br>type ForestVisitor interface {<br> VisitLion(lion *Lion)<br> VisitBird(bird *Bird)<br> VisitRabbit(rabbit *Rabbit)<br>}<br><br>// Lion represents a lion in the forest<br>type Lion struct {<br> name string<br>}<br><br>func (l *Lion) Accept(visitor ForestVisitor) {<br> visitor.VisitLion(l)<br>}<br><br>// Bird represents a bird in the forest<br>type Bird struct {<br> name string<br>}<br><br>func (b *Bird) Accept(visitor ForestVisitor) {<br> visitor.VisitBird(b)<br>}<br><br>// Rabbit represents a rabbit in the forest<br>type Rabbit struct {<br> name string<br>}<br><br>func (r *Rabbit) Accept(visitor ForestVisitor) {<br> visitor.VisitRabbit(r)<br>}<br><br>// InteractionVisitor implements the ForestVisitor interface<br>type InteractionVisitor struct{}<br><br>func (i *InteractionVisitor) VisitLion(lion *Lion) {<br> fmt.Printf(&quot;%s the Lion is marking its territory.\n&quot;, lion.name)<br>}<br><br>func (i *InteractionVisitor) VisitBird(bird *Bird) {<br> fmt.Printf(&quot;%s the Bird is building a nest.\n&quot;, bird.name)<br>}<br><br>func (i *InteractionVisitor) VisitRabbit(rabbit *Rabbit) {<br> fmt.Printf(&quot;%s the Rabbit is digging a burrow.\n&quot;, rabbit.name)<br>}<br><br>func main() {<br> // Creating animals<br> lion := &amp;Lion{name: &quot;Simba&quot;}<br> bird := &amp;Bird{name: &quot;Tweety&quot;}<br> rabbit := &amp;Rabbit{name: &quot;Thumper&quot;}<br><br> // Creating the visitor<br> interactionVisitor := &amp;InteractionVisitor{}<br><br> // Animals interacting with the environment<br> lion.Accept(interactionVisitor) //Output: Simba the Lion is marking its territory.<br> bird.Accept(interactionVisitor) //Output: Tweety the Bird is building a nest.<br> rabbit.Accept(interactionVisitor) //Output: Thumper the Rabbit is digging a burrow.<br>}</pre><h4>Explanation</h4><ol><li><strong>Animal Interface — </strong>Defines the Accept method that all animals must implement. This method allows a visitor to “visit” the animal and perform operations on it.</li><li><strong>Concrete Animals (Lion, Bird, Rabbit) — </strong>Each animal implements the Accept method, which calls the appropriate Visit method on the visitor.</li><li><strong>ForestVisitor Interface — </strong>Defines the Visit methods for each animal type (e.g., VisitLion, VisitBird, VisitRabbit).</li><li><strong>InteractionVisitor — </strong>Implements the ForestVisitor interface. Encapsulates the specific interactions each animal has with the environment.</li><li><strong>Client Code — </strong>The main function demonstrates how the visitor performs interactions for different animals.</li></ol><h4>Where to Implements</h4><p>This pattern is useful when:</p><ol><li><strong>Need to add new operations without modifying existing structures</strong> — Example: Adding multiple tax calculations for different product types.</li><li><strong>Have a complex object structure and want to keep responsibilities separate</strong> — Example: Performing audits on different types of employees in an organization.</li><li><strong>Want to apply different operations to multiple object types in a hierarchy</strong> — Example: Serializing objects to different formats (JSON, XML, CSV).</li><li><strong>Want to follow the Open/Closed Principle</strong> — Objects remain unchanged while new behaviors are introduced externally.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=209b2accc247" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn About Structural Design Pattern in Golang]]></title>
            <link>https://medium.com/@prawiraa.rivan/learn-about-structural-design-pattern-in-golang-df2945d1e7f2?source=rss-82176cae42df------2</link>
            <guid isPermaLink="false">https://medium.com/p/df2945d1e7f2</guid>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[structural-design-pattern]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Rivan Prawira]]></dc:creator>
            <pubDate>Tue, 04 Mar 2025 08:40:44 GMT</pubDate>
            <atom:updated>2025-03-04T08:40:44.735Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zUszf1xfBA_nLFb_0n-Uzw.png" /><figcaption>source: Pinterest</figcaption></figure><p>Structural design patterns in Golang focus on simplifying object composition and relationships, enabling efficient and scalable software architecture. These patterns help developers create flexible and reusable code by defining structured ways to assemble objects and interfaces. In Go, which emphasizes composition over inheritance, structural patterns such as <strong>Adapter</strong>, <strong>Bridge</strong>, <strong>Composite</strong>, <strong>Decorator</strong>, <strong>Facade</strong>, <strong>Flyweight</strong>, and <strong>Proxy</strong> play a crucial role in organizing and managing complex codebases. By leveraging these patterns, developers can enhance maintainability, reduce coupling, and improve the extensibility of their applications.</p><p>Additionally, structural patterns provide a clear blueprint for integrating different components without altering their core logic, ensuring modularity and separation of concerns. Understanding these patterns is essential for building well-structured Go applications that can adapt to evolving requirements and scale efficiently.</p><h3>Adapter</h3><p>The <strong>Adapter</strong> pattern is a structural design pattern that allows incompatible interfaces to work together. It acts as a bridge between two interfaces, enabling objects with different structures to communicate without modifying their existing code. In Golang, the Adapter pattern is often implemented using struct embedding or interface implementation.</p><h4><strong>Animal Analogy</strong></h4><p>There is a Forest where animals have their own ways to move with different methods. Some animals fly() and the others either walk() or swim(). There should be a method that unified all move so it can be handled consistently.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>//Target interface that be expected<br>type Animal interface{<br>  Move()  string<br>}<br><br>//Adaptee 1: Lion with its own method<br>type Lion struct{}<br><br>func (l *Lion) Walk() string {<br>  return &quot;Walking..&quot;<br>}<br><br>//Adapter for Lion<br>type LionAdapter struct{<br>  lion  *Lion<br>}<br><br>func (la *LionAdapter) Move() string {<br>  return la.lion.Walk()<br>}<br><br>//Adaptee 2: Eagle with its own method<br>type Eagle struct{}<br><br>func (e *Eagle) Fly() string {<br>  return &quot;Flying..&quot;<br>}<br><br>//Adapter for Eagle<br>type EagleAdapter struct{<br>  eagle  *Eagle<br>}<br><br>func (ea *EagleAdapter) Move() string {<br>  return ea.eagle.Fly()<br>}<br><br>//Client function that works with any Animal<br>func HowToMove(animal Animal) {<br>  fmt.Println(animal.Move())<br>}<br><br>func main(){<br>  lion := &amp;Lion{}<br>  eagle := &amp;Eagle{}<br><br>  lionAdapter := &amp;LionAdapter{lion: lion}<br>  eagleAdapter := &amp;EagleAdaptor{eagle: eagle}<br><br>  HowToMove(lionAdapter) //Output: Walking..<br>  HowToMove(eagleAdapter) //Output: Flying..</pre><h4><strong>Explanation</strong></h4><ol><li>We define an Animal interface with a Move() method.</li><li>The Lionstruct has a Walk() method, and the Eaglestruct has a Fly() method, both of which do not match the Animal interface.</li><li>We create LionAdapter and EagleAdapter to adapt Lion and Eagle to the Animal interface.</li><li>The HowToMove() function can now work with both dogs and cats through their respective adapters.</li></ol><h4>Where to Implements</h4><p>The Adapter pattern is useful in the following scenarios:</p><ol><li><strong>Integrating third-party libraries</strong> — When a third-party package has a different interface than what your application expects.</li><li><strong>Migrating legacy code</strong> — When transitioning from an old system to a new one while maintaining compatibility.</li><li><strong>Standardizing multiple implementations</strong> — When different components have inconsistent methods but need to be used interchangeably.</li><li><strong>Bridging between different layers of an application</strong> — Such as converting API responses into a format your system understands.</li></ol><h3>Bridge</h3><p>The <strong>Bridge</strong> pattern is a structural design pattern that decouples abstraction from implementation, allowing them to evolve independently. This is achieved by introducing an interface as a “bridge” between high-level logic and specific implementations. In Golang, this pattern is useful when dealing with multiple variations of an entity that share similar behaviors but require flexibility in their implementations.</p><h4>Animal Analogy</h4><p>Imagine we have different animals that can move in different ways. For example, a Lion and an Eagle exist, but they have different movement styles (walking and flying). Instead of creating multiple subclasses for every combination (e.g., FlyingLion, WalkingEagle), we separate the animal type and movement type using the <strong>Bridge</strong> pattern.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// Implementor: Movement interface<br>type Movement interface {<br>    Move() string<br>}<br><br>// Concrete Implementations of Movement<br>type Walking struct{}<br><br>func (w *Walking) Move() string {<br>    return &quot;is walking&quot;<br>}<br><br>type Flying struct{}<br><br>func (f *Flying) Move() string {<br>    return &quot;is flying&quot;<br>}<br><br>// Abstraction: Animal struct with a Movement type<br>type Animal struct {<br>    name     string<br>    movement Movement<br>}<br><br>func (a *Animal) PerformMove() {<br>    fmt.Printf(&quot;%s %s\n&quot;, a.name, a.movement.Move())<br>}<br><br>func main() {<br>    // Create movement strategies<br>    walking := &amp;Walking{}<br>    flying := &amp;Flying{}<br><br>    // Create animals with different movement types<br>    lion := &amp;Animal{name: &quot;Simba&quot;, movement: walking}<br>    eagle := &amp;Animal{name: &quot;Ega&quot;, movement: flying}<br><br>    // Perform movements<br>    lion.PerformMove()  // Output: Lion is walking<br>    eagle.PerformMove() // Output: Eagle is flying<br>}</pre><h4>Explanation</h4><ol><li><strong>Movement Interface</strong> — Defines the Move() method that will be implemented differently for walking and flying.</li><li><strong>Concrete Implementations</strong> — Walking and Flying implement Move(), providing specific movement behaviors.</li><li><strong>Animal Struct (Abstraction)</strong> — Uses a Movement interface to define how it moves without hardcoding the movement type.</li><li><strong>Flexible Associations</strong> — The Animal struct can be paired with any Movement implementation dynamically.</li></ol><h4>Where to Implements</h4><p>The Bridge pattern is useful in scenarios where:</p><ol><li><strong>Have multiple variations of an entity</strong> — When a system has different categories (e.g., different types of animals with different movement styles).</li><li><strong>Need to reduce class explosion</strong> — Instead of creating a new subclass for every combination of features, you separate them into different abstractions.</li><li><strong>Want to allow independent development of features</strong> — Abstraction (high-level logic) and implementation (low-level details) can change separately.</li><li><strong>Need to support multiple platforms</strong> — The bridge pattern helps structure code for cross-platform compatibility.</li></ol><h3>Composite</h3><p>The <strong>Composite</strong> pattern is a structural design pattern that allows treating individual objects and groups of objects uniformly. It enables hierarchical tree structures where both leaf nodes (individual components) and composite nodes (groups of components) can be handled through a common interface.</p><p>In Golang, this pattern is useful when dealing with complex structures that require recursive processing, such as organizational hierarchies, file systems, or graphical user interfaces.</p><h4>Animal Analogy</h4><p>In the animal kingdom, many species form social groups or hierarchies. For example:</p><ul><li>A <strong>wolf pack</strong> is led by an <strong>alpha wolf</strong> and includes <strong>beta wolves</strong> and <strong>omega wolves</strong>.</li><li>A <strong>pride of lions</strong> consists of a <strong>lion leader</strong>, <strong>lionesses</strong>, and <strong>cubs</strong>.</li><li>A <strong>flock of birds</strong> has a <strong>leader bird</strong> and <strong>follower birds</strong>.</li></ul><p>The <strong>Composite Pattern</strong> can be used to represent these animal groups and their subgroups, allowing us to treat individual animals and groups of animals uniformly.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// AnimalComponent interface represents both individual animals and animal groups<br>type AnimalComponent interface {<br> Display(indentation string)<br>}<br><br>// IndividualAnimal represents a single animal<br>type IndividualAnimal struct {<br> name   string<br> role   string<br>}<br><br>func (a *IndividualAnimal) Display(indentation string) {<br> fmt.Println(indentation + &quot;Animal: &quot; + a.name + &quot; (&quot; + a.role + &quot;)&quot;)<br>}<br><br>// AnimalGroup represents a group of animals<br>type AnimalGroup struct {<br> groupName string<br> members   []AnimalComponent<br>}<br><br>func (g *AnimalGroup) Display(indentation string) {<br> fmt.Println(indentation + &quot;Group: &quot; + g.groupName)<br> for _, member := range g.members {<br>  member.Display(indentation + &quot;  &quot;)<br> }<br>}<br><br>// Add adds a member to the animal group<br>func (g *AnimalGroup) Add(member AnimalComponent) {<br> g.members = append(g.members, member)<br>}<br><br>func main() {<br> // Creating a wolf pack<br> alphaWolf := &amp;IndividualAnimal{name: &quot;Alpha&quot;, role: &quot;Leader&quot;}<br> betaWolf := &amp;IndividualAnimal{name: &quot;Beta&quot;, role: &quot;Second-in-Command&quot;}<br> omegaWolf := &amp;IndividualAnimal{name: &quot;Omega&quot;, role: &quot;Lowest Rank&quot;}<br><br> wolfPack := &amp;AnimalGroup{groupName: &quot;Wolf Pack&quot;}<br> wolfPack.Add(alphaWolf)<br> wolfPack.Add(betaWolf)<br> wolfPack.Add(omegaWolf)<br><br> // Creating a pride of lions<br> lionLeader := &amp;IndividualAnimal{name: &quot;Simba&quot;, role: &quot;Leader&quot;}<br> lioness1 := &amp;IndividualAnimal{name: &quot;Nala&quot;, role: &quot;Hunter&quot;}<br> cub1 := &amp;IndividualAnimal{name: &quot;Kion&quot;, role: &quot;Cub&quot;}<br><br> lionPride := &amp;AnimalGroup{groupName: &quot;Lion Pride&quot;}<br> lionPride.Add(lionLeader)<br> lionPride.Add(lioness1)<br> lionPride.Add(cub1)<br><br> // Creating a flock of birds<br> leaderBird := &amp;IndividualAnimal{name: &quot;Sky&quot;, role: &quot;Leader&quot;}<br> followerBird1 := &amp;IndividualAnimal{name: &quot;Feather&quot;, role: &quot;Follower&quot;}<br> followerBird2 := &amp;IndividualAnimal{name: &quot;Wing&quot;, role: &quot;Follower&quot;}<br><br> birdFlock := &amp;AnimalGroup{groupName: &quot;Bird Flock&quot;}<br> birdFlock.Add(leaderBird)<br> birdFlock.Add(followerBird1)<br> birdFlock.Add(followerBird2)<br><br> // Displaying the animal groups<br> fmt.Println(&quot;Wolf Pack Structure:&quot;)<br> wolfPack.Display(&quot;&quot;)<br><br> fmt.Println(&quot;\nLion Pride Structure:&quot;)<br> lionPride.Display(&quot;&quot;)<br><br> fmt.Println(&quot;\nBird Flock Structure:&quot;)<br> birdFlock.Display(&quot;&quot;)<br>}</pre><h4>Explanation</h4><ol><li><strong>AnimalComponent interface</strong> — Represents both individual animals and animal groups also defines a common method Display that all components must implement.</li><li><strong>IndividualAnimal</strong> — Represents a single animal with a name and role also implements the Display method to show its details.</li><li><strong>AnimalGroup</strong> — Represents a group of animals, contains a list of AnimalComponent objects also implements the Display method to show the group name and recursively display its members.</li><li><strong>ClientCode</strong> — The main function demonstrates how to build hierarchical animal groups using the Composite Pattern also creates wolf packs, lion prides, and bird flocks, and organizes them into a hierarchy.</li></ol><h4>Where to Implements</h4><p>The Composite pattern is beneficial in scenarios such as:</p><ol><li><strong>Hierarchical structures</strong> — Managing tree-like data structures, such as company departments, graphical elements, or animal groups.</li><li><strong>Recursive processing</strong> — When an operation needs to be applied to both individual objects and groups.</li><li><strong>Consistent interface</strong> — When you want to treat single objects and collections of objects uniformly.</li><li><strong>Reducing conditional logic</strong> — Instead of checking if an object is a single entity or a group, the Composite pattern ensures uniform handling.</li></ol><h3>Decorator</h3><p>The <strong>Decorator</strong> pattern is a structural design pattern that allows dynamically adding behaviors to objects without modifying their existing code. Instead of subclassing, the Decorator pattern wraps an object inside another object that provides additional functionality.</p><p>In Golang, this pattern is useful when you need to extend the behavior of objects at runtime while keeping the base structure unchanged.</p><h4>Animal Analogy</h4><p>Imagine a world where animals can gain special abilities or enhancements. For example:</p><ol><li>A <strong>basic animal</strong> can only perform its natural behaviors (e.g., a lion can roar).</li><li>You can <strong>decorate</strong> the animal with additional abilities, such as:</li></ol><ul><li><strong>Flying</strong>: The animal can now fly.</li><li><strong>Swimming</strong>: The animal can now swim.</li><li><strong>Super Strength</strong>: The animal gains extra strength.</li></ul><p>The <strong>Decorator Pattern</strong> can be used to dynamically add these abilities to animals without modifying their core behavior.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// Animal interface represents the basic behavior of an animal<br>type Animal interface {<br> Describe() string<br>}<br><br>// BasicAnimal represents a basic animal with no enhancements<br>type BasicAnimal struct {<br> name  string<br> sound string<br>}<br><br>func (a *BasicAnimal) Describe() string {<br> return fmt.Sprintf(&quot;%s says %s&quot;, a.name, a.sound)<br>}<br><br>// AnimalDecorator is the base decorator struct<br>type AnimalDecorator struct {<br> animal Animal<br>}<br><br>func (d *AnimalDecorator) Describe() string {<br> return d.animal.Describe()<br>}<br><br>// FlyingDecorator adds the ability to fly<br>type FlyingDecorator struct {<br> AnimalDecorator<br>}<br><br>func (f *FlyingDecorator) Describe() string {<br> return f.AnimalDecorator.Describe() + &quot; and can fly&quot;<br>}<br><br>// SwimmingDecorator adds the ability to swim<br>type SwimmingDecorator struct {<br> AnimalDecorator<br>}<br><br>func (s *SwimmingDecorator) Describe() string {<br> return s.AnimalDecorator.Describe() + &quot; and can swim&quot;<br>}<br><br>// SuperStrengthDecorator adds super strength<br>type SuperStrengthDecorator struct {<br> AnimalDecorator<br>}<br><br>func (ss *SuperStrengthDecorator) Describe() string {<br> return ss.AnimalDecorator.Describe() + &quot; and has super strength&quot;<br>}<br><br>func main() {<br> // Creating a basic lion<br> lion := &amp;BasicAnimal{name: &quot;Simba&quot;, sound: &quot;Roar&quot;}<br> fmt.Println(lion.Describe()) // Output: Simba says Roar<br><br> // Adding the ability to fly<br> flyingLion := &amp;FlyingDecorator{AnimalDecorator{lion}}<br> fmt.Println(flyingLion.Describe()) // Output: Simba says Roar and can fly<br><br> // Adding the ability to swim<br> swimmingLion := &amp;SwimmingDecorator{AnimalDecorator{lion}}<br> fmt.Println(swimmingLion.Describe()) // Output: Simba says Roar and can swim<br><br> // Adding super strength<br> strongLion := &amp;SuperStrengthDecorator{AnimalDecorator{lion}}<br> fmt.Println(strongLion.Describe()) // Output: Simba says Roar and has super strength<br><br> // Combining multiple decorators<br> superLion := &amp;SuperStrengthDecorator{AnimalDecorator{<br>  &amp;FlyingDecorator{AnimalDecorator{lion}},<br> }}<br> fmt.Println(superLion.Describe()) // Output: Simba says Roar and can fly and has super strength<br>}</pre><h4>Explanation</h4><ol><li><strong>Animal Interface</strong> — Representsthe basic behavior of an animal (e.g., Describe method).</li><li><strong>BasicAnimal</strong> — Represents a basic animal with no enhancements (e.g., a lion that can only roar).</li><li><strong>AnimalDecorator</strong> — The base decorator struct that embeds an Animal and implements the Animal interface. It acts as a wrapper around the original animal.</li><li><strong>Concrete Decorator</strong> — Including FlyingDecorator, SwimmingDecorator, SuperStregthDecorator. Each decorator enhances the behavior of the animal by modifying the Describe method.</li><li><strong>Client Code</strong> — The main function demonstrates how to dynamically add abilities to an animal using decorators. It can combine multiple decorators to create animals with multiple abilities.</li></ol><h4>Where to Implements</h4><p>The Decorator pattern is useful in the following scenarios:</p><ol><li><strong>Adding functionality dynamically</strong> — When you need to extend object behavior without modifying the original struct.</li><li><strong>Avoiding subclass explosion</strong> — Instead of creating multiple subclasses for each variation, decorators provide flexibility.</li><li><strong>Open-Closed Principle</strong> — You can extend functionality without modifying existing code.</li><li><strong>Cross-cutting concerns</strong> — Used for logging, caching, authentication, or adding features like speed boost to an entity.</li></ol><h3>Facade</h3><p>The <strong>Facade</strong> pattern is a structural design pattern that provides a simplified interface to a complex system. Instead of exposing multiple subsystems directly to the client, a facade acts as a wrapper that streamlines interactions with the system.</p><p>In Golang, the Facade pattern is useful when working with complicated APIs, libraries, or subsystems that require multiple steps to perform an operation.</p><h4>Animal Analogy</h4><p>Imagine a system that models the behaviors of animals in the wild. Each animal has multiple behaviors, such as:</p><ol><li><strong>Eating</strong>.</li><li><strong>Sleeping</strong>.</li><li><strong>Making sounds</strong>.</li><li><strong>Moving</strong>.</li></ol><p>Individually, these behaviors can be complex to manage. For example:</p><ul><li><strong>Eating</strong> might involve hunting, foraging, or grazing.</li><li><strong>Sleeping</strong> might involve finding a safe spot or building a nest.</li><li><strong>Making sounds</strong> might involve roaring, chirping, or growling.</li><li><strong>Moving</strong> might involve walking, flying, or swimming.</li></ul><p>Instead of dealing with each behavior separately, we can use a <strong>Facade</strong> to provide a simplified interface for interacting with an animal’s behaviors.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// Subsystem 1: Eating Behavior<br>type EatingBehavior struct{}<br><br>func (e *EatingBehavior) Eat() {<br> fmt.Println(&quot;The animal is eating...&quot;)<br>}<br><br>// Subsystem 2: Sleeping Behavior<br>type SleepingBehavior struct{}<br><br>func (s *SleepingBehavior) Sleep() {<br> fmt.Println(&quot;The animal is sleeping...&quot;)<br>}<br><br>// Subsystem 3: Sound Behavior<br>type SoundBehavior struct{}<br><br>func (s *SoundBehavior) MakeSound() {<br> fmt.Println(&quot;The animal is making a sound...&quot;)<br>}<br><br>// Subsystem 4: Movement Behavior<br>type MovementBehavior struct{}<br><br>func (m *MovementBehavior) Move() {<br> fmt.Println(&quot;The animal is moving...&quot;)<br>}<br><br>// Facade: Animal Behavior System<br>type AnimalBehaviorFacade struct {<br> eating   *EatingBehavior<br> sleeping *SleepingBehavior<br> sound    *SoundBehavior<br> movement *MovementBehavior<br>}<br><br>func NewAnimalBehaviorFacade() *AnimalBehaviorFacade {<br> return &amp;AnimalBehaviorFacade{<br>  eating:   &amp;EatingBehavior{},<br>  sleeping: &amp;SleepingBehavior{},<br>  sound:    &amp;SoundBehavior{},<br>  movement: &amp;MovementBehavior{},<br> }<br>}<br><br>// Simplified interface for interacting with animal behaviors<br>func (f *AnimalBehaviorFacade) PerformDailyRoutine() {<br> fmt.Println(&quot;Starting the animal&#39;s daily routine...&quot;)<br> f.eating.Eat()<br> f.sleeping.Sleep()<br> f.sound.MakeSound()<br> f.movement.Move()<br> fmt.Println(&quot;Daily routine completed.&quot;)<br>}<br><br>func main() {<br> // Using the Facade to interact with animal behaviors<br> animalFacade := NewAnimalBehaviorFacade()<br> animalFacade.PerformDailyRoutine()<br>}</pre><h4>Explanation</h4><ol><li><strong>Subsystem</strong> — contains EatingBehavior, SleepingBehavior, SoundBehavior, and MovementBehavior. Each of them represents a specific behavior of the animal.</li><li><strong>Facade</strong> — AnimalBehaviorFacade provides a simplified interface for interacting with the animal’s behaviors. It encapsulates the complexity of the subsystems and provides a single method (PerformDailyRoutine) to execute a sequence of behaviors.</li><li><strong>Client Code</strong> — The main function demonstrates how to use the Facade to interact with the animal&#39;s behaviors without needing to call each subsystem individually.</li></ol><h4>Where to Implements</h4><p>The Facade pattern is beneficial in the following scenarios:</p><ol><li><strong>Simplifying a complex system</strong> — When multiple subsystems exist, and you want to provide a straightforward interface.</li><li><strong>Reducing dependencies</strong> — The client interacts only with the facade instead of directly accessing internal components.</li><li><strong>Improving maintainability</strong> — Changing subsystem implementations does not affect the client.</li><li><strong>Encapsulating third-party libraries</strong> — To provide a stable API while allowing changes to the underlying implementation.</li></ol><h3>Flyweight</h3><p>The <strong>Flyweight</strong> pattern is a structural design pattern that minimizes memory usage by sharing common state across multiple objects instead of storing duplicate data. This is useful when creating many similar objects that have shared properties, reduced memory footprint and improving performance.</p><p>In Golang, this pattern is beneficial when dealing with large numbers of objects that have shared attributes, such as rendering systems, caching, or object pooling.</p><h4>Animal Analogy</h4><p>Imagine a simulation of a <strong>forest ecosystem</strong> with thousands of animals. Each animal belongs to a specific <strong>species</strong> (e.g., lion, eagle, bear), and many animals of the same species share common attributes, such as:</p><ul><li><strong>Species name</strong>.</li><li><strong>Natural habitat</strong>.</li><li><strong>Diet type</strong> (e.g., carnivore, herbivore).</li><li><strong>Average lifespan</strong>.</li></ul><p>Instead of storing these shared attributes in every individual animal object, we can use the <strong>Flyweight Pattern</strong> to store them once and reuse them across multiple animals. This reduces memory usage and improves performance.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// Flyweight: Shared attributes for a species<br>type AnimalSpecies struct {<br> name        string<br> habitat     string<br> dietType    string<br> averageLifespan int<br>}<br><br>func (a *AnimalSpecies) Describe() string {<br> return fmt.Sprintf(&quot;Species: %s, Habitat: %s, Diet: %s, Lifespan: %d years&quot;,<br>  a.name, a.habitat, a.dietType, a.averageLifespan)<br>}<br><br>// Flyweight Factory: Manages shared species objects<br>type AnimalSpeciesFactory struct {<br> speciesPool map[string]*AnimalSpecies<br>}<br><br>func NewAnimalSpeciesFactory() *AnimalSpeciesFactory {<br> return &amp;AnimalSpeciesFactory{<br>  speciesPool: make(map[string]*AnimalSpecies),<br> }<br>}<br><br>func (f *AnimalSpeciesFactory) GetSpecies(name, habitat, dietType string, lifespan int) *AnimalSpecies {<br> key := name + habitat + dietType<br> if species, exists := f.speciesPool[key]; exists {<br>  return species<br> }<br> species := &amp;AnimalSpecies{<br>  name:        name,<br>  habitat:     habitat,<br>  dietType:    dietType,<br>  averageLifespan: lifespan,<br> }<br> f.speciesPool[key] = species<br> return species<br>}<br><br>// Individual Animal: Contains unique and shared attributes<br>type Animal struct {<br> name    string<br> species *AnimalSpecies<br>}<br><br>func (a *Animal) Describe() string {<br> return fmt.Sprintf(&quot;Animal: %s, %s&quot;, a.name, a.species.Describe())<br>}<br><br>func main() {<br> // Create a flyweight factory<br> speciesFactory := NewAnimalSpeciesFactory()<br><br> // Create animals with shared species attributes<br> lionSpecies := speciesFactory.GetSpecies(&quot;Lion&quot;, &quot;Savanna&quot;, &quot;Carnivore&quot;, 15)<br> eagleSpecies := speciesFactory.GetSpecies(&quot;Eagle&quot;, &quot;Mountains&quot;, &quot;Carnivore&quot;, 20)<br> bearSpecies := speciesFactory.GetSpecies(&quot;Bear&quot;, &quot;Forest&quot;, &quot;Omnivore&quot;, 25)<br><br> // Create individual animals<br> simba := &amp;Animal{name: &quot;Simba&quot;, species: lionSpecies}<br> eddy := &amp;Animal{name: &quot;Eddy&quot;, species: eagleSpecies}<br> baloo := &amp;Animal{name: &quot;Baloo&quot;, species: bearSpecies}<br><br> // Display animal details<br> fmt.Println(simba.Describe()) // Output: Animal: Simba, Species: Lion, Habitat: Savanna, Diet: Carnivore, Lifespan: 15 years<br> fmt.Println(eddy.Describe())  // Output: Animal: Eddy, Species: Eagle, Habitat: Mountains, Diet: Carnivore, Lifespan: 20 years<br> fmt.Println(baloo.Describe()) // Output: Animal: Baloo, Species: Bear, Habitat: Forest, Diet: Omnivore, Lifespan: 25 years<br><br> // Verify that species are shared<br> anotherLion := &amp;Animal{name: &quot;Mufasa&quot;, species: lionSpecies}<br> fmt.Println(anotherLion.Describe()) // Output: Animal: Mufasa, Species: Lion, Habitat: Savanna, Diet: Carnivore, Lifespan: 15 years<br>}</pre><h4>Explanation</h4><ol><li><strong>Flyweight (AnimalSpecies)</strong>: Represents the shared attributes of a species (e.g., name, habitat, diet type, lifespan). These attributes are common to all animals of the same species and are stored once to save memory.</li><li><strong>Flyweight Factory (AnimalSpeciesFactory)</strong>: Manages a pool of shared species objects. Ensures that each species is created only once and reused across multiple animals.</li><li><strong>Individual Animal</strong>: Represents an individual animal with unique attributes (e.g., name) and a reference to the shared species attributes.</li><li><strong>Client Code</strong>: The main function demonstrates how to create animals with shared species attributes using the Flyweight Pattern. It ensures that species attributes are reused across multiple animals, reducing memory usage.</li></ol><h4>Where to Implements</h4><p>The Flyweight pattern is useful in scenarios where:</p><ol><li><strong>A large number of similar objects are created</strong> — Helps save memory by avoiding redundancy.</li><li><strong>Objects have intrinsic (shared) and extrinsic (unique) states</strong> — Intrinsic states are stored in the flyweight object, while extrinsic states are passed at runtime.</li><li><strong>Performance optimization is required</strong> — Helps improve efficiency by reducing object creation overhead.</li><li><strong>Managing resources efficiently</strong> — Used in game development, GUI elements, or caching systems.</li></ol><h3>Proxy</h3><p>The <strong>Proxy</strong> pattern is a structural design pattern that acts as an intermediary between a client and a real object. It is used to control access, add functionality, or optimize performance without modifying the actual object.</p><p>In Golang, the Proxy pattern is beneficial when dealing with lazy initialization, access control, logging, caching, and network proxies.</p><h4>Animal Analogy</h4><p>Imagine a <strong>wildlife sanctuary</strong> where certain animals are protected and require special permissions to interact with. For example:</p><ul><li>A <strong>lion</strong> is a protected animal, and only authorized personnel (e.g., a lioness) can interact with it.</li><li>Instead of allowing direct access to the lion, we use a <strong>Proxy</strong> (e.g., a guardian) to control access and add additional behavior, such as logging or security checks.</li></ul><p>The <strong>Proxy Pattern</strong> can be used to create a guardian that acts as an intermediary between the client (e.g., a visitor) and the real animal (e.g., the lion).</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// Subject: Animal interface<br>type Animal interface {<br> Speak() string<br>}<br><br>// RealSubject: Lion represents the real animal<br>type Lion struct {<br> name string<br>}<br><br>func (l *Lion) Speak() string {<br> return fmt.Sprintf(&quot;%s the Lion says Roar!&quot;, l.name)<br>}<br><br>// Proxy: LionGuardian controls access to the lion<br>type LionGuardian struct {<br> lion       *Lion<br> authorized bool<br>}<br><br>func NewLionGuardian(authorized bool) *LionGuardian {<br> return &amp;LionGuardian{<br>  lion:       &amp;Lion{name: &quot;Simba&quot;},<br>  authorized: authorized,<br> }<br>}<br><br>func (g *LionGuardian) Speak() string {<br> if g.authorized {<br>  fmt.Println(&quot;Access granted to interact with the lion.&quot;)<br>  return g.lion.Speak()<br> }<br> fmt.Println(&quot;Access denied. You are not authorized to interact with the lion.&quot;)<br> return &quot;&quot;<br>}<br><br>func main() {<br> // Unauthorized visitor<br> unauthorizedVisitor := NewLionGuardian(false)<br> fmt.Println(unauthorizedVisitor.Speak()) // Output: Access denied. You are not authorized to interact with the lion.<br><br> // Authorized zookeeper<br> authorizedZookeeper := NewLionGuardian(true)<br> fmt.Println(authorizedZookeeper.Speak()) // Output: Access granted to interact with the lion. Simba the Lion says Roar!<br>}</pre><h4>Explanation</h4><ol><li><strong>Subject (Animal Interface)</strong>: Represents the common behavior of all animals (e.g., Speak method).</li><li><strong>RealSubject (Lion)</strong>: Represents the real animal (e.g., a lion) that the client wants to interact with.</li><li><strong>Proxy (LionGuardian)</strong>: Acts as a surrogate or placeholder for the lion and controls access to the lion by checking if the client is authorized. Also adds additional behavior, such as logging access attempts.</li><li><strong>Client Code</strong>: The main function demonstrates how the proxy controls access to the lion. Unauthorized visitors are denied access, while authorized zookeepers are allowed to interact with the lion.</li></ol><h4>Where to Implements</h4><p>The Proxy pattern is useful in the following scenarios:</p><ol><li><strong>Access Control</strong> — Restrict access to certain objects (e.g., authentication, permissions).</li><li><strong>Lazy Initialization</strong> — Delay object creation until it is actually needed.</li><li><strong>Logging and Monitoring</strong> — Add extra behavior like logging before and after function calls.</li><li><strong>Remote Proxy</strong> — Provide a local representation of an object that exists in a different location (e.g., network or database).</li><li><strong>Caching</strong> — Store results from expensive operations and return cached results when possible.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df2945d1e7f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Singleton to Factory: A Deep Dive into Creational Design Patterns]]></title>
            <link>https://medium.com/@prawiraa.rivan/from-singleton-to-factory-a-deep-dive-into-creational-design-patterns-e174f424daa7?source=rss-82176cae42df------2</link>
            <guid isPermaLink="false">https://medium.com/p/e174f424daa7</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[creational-design-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Rivan Prawira]]></dc:creator>
            <pubDate>Thu, 27 Feb 2025 01:17:12 GMT</pubDate>
            <atom:updated>2025-02-27T01:17:12.579Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*An2cayMkkTzdWbqE3Tru2g.png" /><figcaption>source: Pinterest</figcaption></figure><p>In software development, the way objects are created can significantly impact the maintainability, scalability, and flexibility of an application. Creational design patterns provide efficient solutions for object instantiation by offering mechanisms to create objects in a controlled and optimized manner. Instead of directly instantiating objects using the new keyword, these patterns abstract the object creation process to promote loose coupling and reusability.</p><p>There are several types of creational design patterns, including <strong>Singleton, Prototype, Builder, Abstract Factory,</strong> and<strong> Factory Method.</strong> Each pattern serves a specific purpose, such as ensuring a single instance of a class, simplifying complex object creation, or improving performance by reusing existing instances. By applying creational design patterns, developers can enhance code organization and maintainability, leading to more scalable software architectures.</p><h4>Singleton</h4><p>The Singleton pattern is a creational design pattern that ensures a class has only <strong>one</strong> instance and provides a global access point to that instance. This is useful when you need a single shared resource, such as a configuration manager, database connection, or a unique entity in your application.</p><p><strong>Animal Analogy</strong></p><p>Imagine we have a <strong>Ruler of the Forest </strong>who governs all the creatures in the wild. There should only be one Ruler<strong> </strong>stands above all. If there create multiple Rulers, the forest might fall into chaos with conflicting each Ruler and the followers.</p><p>The <strong>Singleton pattern</strong> ensures that only one <strong>Ruler of the Forest</strong> exists throughout the program, maintaining harmony and order in the wilderness.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;sync&quot;<br>)<br><br>// Ruler struct (Singleton)<br>type RulerOfForest struct {<br> name string<br>}<br><br>// Singleton instance and sync.Once to ensure thread safety<br>var instance *RulerOfForest<br>var once sync.Once<br><br>// GetRuleOfForest returns the single instance of RulerOfForest<br>func GetRulerOfForest(name string) *RulerOfForest {<br> once.Do(func() {<br>  instance = &amp;RulerOfForest{name: name}<br> })<br> return instance<br>}<br><br>// Announce method for RulerOfForest<br>func (zd *RulerOfForest) Announce() {<br> fmt.Println(&quot;I am the Ruler of Forest, my name is&quot;, zd.name)<br>}<br><br>func main() {<br> // First instance<br> ruler1 := GetRulerOfForest(&quot;Lion&quot;)<br> ruler1.Announce() // Output: I am the Ruler of Forest, my name is Lion<br><br> // Trying to create another instance<br> Ruler2 := GetRulerOfForest(&quot;Eagle&quot;)<br> ruler2.Announce() // Output: I am the Ruler of Forest, my name is Lion (still Lion!)<br><br> // Check if both instances are the same<br> fmt.Println(ruler1 == ruler2) // Output: true (both refer to the same instance)<br>}</pre><p><strong>How It Works</strong></p><ol><li>var instance *RulerOfForest → Stores the single instance.</li><li>sync.Once → Ensures the instance is created only once, even in multi-threaded programs.</li><li>GetRulerOfForest(name string) → Creates an instance only if it does not exist and returns the same instance every time.</li><li>When we call GetRulerOfForest(&quot;Eagle&quot;) after GetRulerOfForest(&quot;Lion&quot;), it does NOT create a new instance, so the name remains &quot;Lion&quot;.</li></ol><p>In real-world applications, the Singleton pattern is often used to manage system-wide resources efficiently. For example,</p><ul><li><strong>Database connections</strong>, maintaining a single instance prevents multiple redundant connections, reducing resource consumption and ensuring data consistency.</li><li><strong>Logging services</strong>, having a single logger instance ensures that all parts of the application write logs in a centralized and structured manner, making debugging and monitoring more efficient.</li><li><strong>Configuration management</strong>, where a Singleton instance stores application-wide settings, such as environment variables and API keys, ensuring that all components access the same configuration without inconsistencies. By using the Singleton pattern in these scenarios, developers can maintain efficiency, avoid conflicts, and ensure better resource management across an application.</li></ul><h4>Prototype</h4><p>The Prototype pattern is a creational design pattern that allows objects to be cloned rather than created from scratch. This is useful when object creation is expensive or complex, and we need multiple similar copies with slight modifications. Instead of instantiating new objects, we duplicate an existing one, ensuring efficiency and consistency.</p><p><strong>Animal Analogy</strong></p><p>Imagine a Forest where we have different types of animals. Instead of manually collect data each animal with its characteristics (name, species, typeOfFood, and livingPlace), we can create a “prototype” animal and clone it whenever needed. This approach saves time and ensures consistency in animal attributes.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br>)<br><br>// Animal interface with Clone and GetInfo methods<br>type Animal interface {<br> Clone() Animal<br> GetInfo() string<br>}<br><br>// Concrete struct for a specific type of Animal<br>type ForestAnimal struct {<br> name       string<br> species    string<br> typeOfFood string<br> livingPlace string<br>}<br><br>// Clone method to create a copy of the ForestAnimal<br>func (f *ForestAnimal) Clone() Animal {<br> return &amp;ForestAnimal{<br>  name:       f.name,<br>  species:    f.species,<br>  typeOfFood: f.typeOfFood,<br>  livingPlace: f.livingPlace,<br> }<br>}<br><br>// GetInfo method to display ForestAnimal details<br>func (f *ForestAnimal) GetInfo() string {<br> return fmt.Sprintf(&quot;Name: %s, Species: %s, Type of Food: %s, Living Place: %s&quot;, f.name, f.species, f.typeOfFood, f.livingPlace)<br>}<br><br>func main() {<br> // Creating the prototype ForestAnimal<br> firstBear := &amp;ForestAnimal{<br>  name:       &quot;Baloo&quot;,<br>  species:    &quot;Bear&quot;,<br>  typeOfFood: &quot;Omnivore&quot;,<br>  livingPlace: &quot;Cave&quot;,<br> }<br> fmt.Println(originalBear.GetInfo()) // Output: Name: Baloo, Species: Bear, Type of Food: Omnivore, Living Place: Cave<br><br> // Cloning the ForestAnimal to create a new one<br> secondBear := firstBear.Clone().(*ForestAnimal)<br> secondBear.name = &quot;Yogi&quot; // Modifying the clone&#39;s name<br><br> fmt.Println(secondBear.GetInfo())    // Output: Name: Yogi, Species: Bear, Type of Food: Omnivore, Living Place: Cave<br> fmt.Println(firstBear.GetInfo())  // Output: Name: Baloo, Species: Bear, Type of Food: Omnivore, Living Place: Cave<br>}</pre><p><strong>How It Works</strong></p><ol><li><strong>Animal Interface</strong>: Defines the Clone and GetInfo methods that all animals must implement.</li><li><strong>ForestAnimal Struct</strong>: Represents an animal in the forest with attributes name, species, typeOfFood, and livingPlace.</li><li><strong>Clone Method</strong>: Creates a deep copy of the ForestAnimal object.</li><li><strong>GetInfo Method</strong>: Returns a formatted string with the animal’s details.</li><li><strong>Main Function</strong>: Creates a prototype ForestAnimal (e.g., a bear named &quot;Baloo&quot;). Baloo”). Clones the prototype and modifies the clone’s name to “Yogi”. Prints the details of both the original and cloned animals.</li></ol><p>This approach offers several key advantages, making it a powerful tool in scenarios where object creation is resource-intensive or requires consistency. Below, we’ll explore its benefits in more detail and elaborate on its use cases.</p><ul><li><strong>Efficiency: </strong>Constructing a new object often involves complex initialization logic, database queries, or resource allocation. By cloning an existing object, you bypass these costly operations, saving time and computational resources.</li><li><strong>Consistency: </strong>When you clone an object, the new instance inherits the state and properties of the original. This ensures consistency across multiple instances, which is especially useful when working with complex objects that require precise configurations.</li><li><strong>Flexibility: </strong>Once an object is cloned, you can customize the copy independently. This flexibility is useful when you need multiple variations of an object without altering the prototype.</li></ul><h4>Builder</h4><p>The Builder pattern is a creational design pattern used to construct complex objects step by step. Instead of creating an object with a long list of parameters, the Builder pattern provides a structured way to configure and instantiate objects with flexibility and readability.</p><p><strong>Animal Analogy</strong></p><p>Imagine we want to classify animal inside the Forest, and we need to get data in various animals with different attributes such as name, species, type of food, and living place. Instead of using a long constructor with multiple parameters, which can be confusing, we use the <strong>Builder pattern</strong> to classify animal step by step in a readable and flexible manner.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br>)<br><br>// Animal struct representing an animal in the forest<br>type Animal struct {<br> name       string<br> species    string<br> typeOfFood string<br> livingPlace string<br>}<br><br>// AnimalBuilder struct to construct Animal objects<br>type AnimalBuilder struct {<br> animal Animal<br>}<br><br>// NewAnimalBuilder creates a new instance of AnimalBuilder<br>func NewAnimalBuilder() *AnimalBuilder {<br> return &amp;AnimalBuilder{}<br>}<br><br>// SetName sets the name of the animal<br>func (b *AnimalBuilder) SetName(name string) *AnimalBuilder {<br> b.animal.name = name<br> return b<br>}<br><br>// SetSpecies sets the species of the animal<br>func (b *AnimalBuilder) SetSpecies(species string) *AnimalBuilder {<br> b.animal.species = species<br> return b<br>}<br><br>// SetTypeOfFood sets the type of food the animal eats<br>func (b *AnimalBuilder) SetTypeOfFood(typeOfFood string) *AnimalBuilder {<br> b.animal.typeOfFood = typeOfFood<br> return b<br>}<br><br>// SetLivingPlace sets the living place of the animal<br>func (b *AnimalBuilder) SetLivingPlace(livingPlace string) *AnimalBuilder {<br> b.animal.livingPlace = livingPlace<br> return b<br>}<br><br>// Build finalizes the object construction<br>func (b *AnimalBuilder) Build() Animal {<br> return b.animal<br>}<br><br>func main() {<br> // Creating an animal using the Builder pattern<br> bear := NewAnimalBuilder().<br>  SetName(&quot;Baloo&quot;).<br>  SetSpecies(&quot;Bear&quot;).<br>  SetTypeOfFood(&quot;Omnivore&quot;).<br>  SetLivingPlace(&quot;Cave&quot;).<br>  Build()<br><br> // Creating another animal<br> deer := NewAnimalBuilder().<br>  SetName(&quot;Bambi&quot;).<br>  SetSpecies(&quot;Deer&quot;).<br>  SetTypeOfFood(&quot;Herbivore&quot;).<br>  SetLivingPlace(&quot;Meadow&quot;).<br>  Build()<br><br> // Displaying the created animals<br> fmt.Printf(&quot;Animal: %s, Species: %s, Type of Food: %s, Living Place: %s\n&quot;, bear.name, bear.species, bear.typeOfFood, bear.livingPlace)<br> fmt.Printf(&quot;Animal: %s, Species: %s, Type of Food: %s, Living Place: %s\n&quot;, deer.name, deer.species, deer.typeOfFood, deer.livingPlace)<br>}</pre><p><strong>How It Works</strong></p><ol><li><strong>Animal Struct</strong>: Represents an animal in the forest with attributes name, species, typeOfFood, and livingPlace.</li><li><strong>AnimalBuilder Struct</strong>: Helps in constructing the Animal object step by step.</li><li><strong>Set Methods</strong>: Each method sets a specific attribute of the Animal and returns the builder itself, allowing for method chaining.</li><li><strong>Build Method</strong>: Finalizes the construction and returns the Animal object.</li><li><strong>Main Function</strong>: Demonstrates how to use the builder to create different animals with specific attributes.</li></ol><p>Instead of relying on large, unwieldy constructors or multiple overloaded methods, the Builder Pattern provides a clear, step-by-step approach to object creation. Below, we’ll explore its key benefits and elaborate on why it’s widely used in various scenarios.</p><ul><li><strong>Improves Readability: </strong>When an object requires numerous parameters for initialization, traditional constructors can become cluttered and hard to read. The Builder Pattern replaces this with a fluent, method-chaining approach, making the code more intuitive and easier to understand.</li><li><strong>Flexible Object Construction: </strong>With the Builder Pattern, you can set only the attributes you need, in any order, without being constrained by the sequence of parameters in a constructor. This flexibility simplifies object creation, especially when dealing with optional or default values.</li><li><strong>Extensibility: </strong>If you need to add new configuration options to an object, the Builder Pattern allows you to do so without breaking existing code. This makes the pattern highly adaptable to changing requirements.</li></ul><h4>Abstract Factory</h4><p>The Abstract Factory Pattern is used when a system needs to create families of related objects without specifying their concrete implementations. Instead of directly instantiating objects, the pattern provides a factory interface that subclasses implement to produce various related objects.</p><p><strong>Animal Analogy</strong></p><p>Imagine a forest ecosystem where there are different types of animals and plants. These organisms can be categorized into families, such as:</p><ol><li><strong>Mammals</strong>: Lions, Bears, Deer</li><li><strong>Birds</strong>: Eagles, Parrots, Owls</li><li><strong>Plants</strong>: Trees, Shrubs, Flowers</li></ol><p>Each family has its own set of characteristics and behaviors. The <strong>Abstract Factory Pattern</strong> can be used to create families of related objects (e.g., mammals, birds, or plants) without specifying their concrete types.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// Animal interface represents an animal in the forest<br>type Animal interface {<br> Speak() string<br>}<br><br>// Plant interface represents a plant in the forest<br>type Plant interface {<br> Grow() string<br>}<br><br>// AbstractFactory interface for creating families of related objects<br>type AbstractFactory interface {<br> CreateAnimal() Animal<br> CreatePlant() Plant<br>}<br><br>// MammalFactory creates mammals and their associated plants<br>type MammalFactory struct{}<br><br>func (m *MammalFactory) CreateAnimal() Animal {<br> return &amp;Lion{name: &quot;Simba&quot;}<br>}<br><br>func (m *MammalFactory) CreatePlant() Plant {<br> return &amp;Tree{name: &quot;Oak&quot;}<br>}<br><br>// BirdFactory creates birds and their associated plants<br>type BirdFactory struct{}<br><br>func (b *BirdFactory) CreateAnimal() Animal {<br> return &amp;Eagle{name: &quot;Eddy&quot;}<br>}<br><br>func (b *BirdFactory) CreatePlant() Plant {<br> return &amp;Shrub{name: &quot;Berry Bush&quot;}<br>}<br><br>// Lion is a concrete mammal<br>type Lion struct {<br> name string<br>}<br><br>func (l *Lion) Speak() string {<br> return fmt.Sprintf(&quot;%s the Lion says Roar!&quot;, l.name)<br>}<br><br>// Eagle is a concrete bird<br>type Eagle struct {<br> name string<br>}<br><br>func (e *Eagle) Speak() string {<br> return fmt.Sprintf(&quot;%s the Eagle says Screech!&quot;, e.name)<br>}<br><br>// Tree is a concrete plant<br>type Tree struct {<br> name string<br>}<br><br>func (t *Tree) Grow() string {<br> return fmt.Sprintf(&quot;%s Tree is growing tall!&quot;, t.name)<br>}<br><br>// Shrub is a concrete plant<br>type Shrub struct {<br> name string<br>}<br><br>func (s *Shrub) Grow() string {<br> return fmt.Sprintf(&quot;%s Shrub is growing berries!&quot;, s.name)<br>}<br><br>func main() {<br> // Create a Mammal family<br> mammalFactory := &amp;MammalFactory{}<br> lion := mammalFactory.CreateAnimal()<br> tree := mammalFactory.CreatePlant()<br><br> fmt.Println(lion.Speak()) // Output: Simba the Lion says Roar!<br> fmt.Println(tree.Grow())  // Output: Oak Tree is growing tall!<br><br> // Create a Bird family<br> birdFactory := &amp;BirdFactory{}<br> eagle := birdFactory.CreateAnimal()<br> shrub := birdFactory.CreatePlant()<br><br> fmt.Println(eagle.Speak()) // Output: Eddy the Eagle says Screech!<br> fmt.Println(shrub.Grow())  // Output: Berry Bush Shrub is growing berries!<br>}</pre><p><strong>How It Works</strong></p><p><strong>1. Abstract Factory (</strong><strong>AbstractFactory)</strong>:</p><ul><li>Defines an interface for creating families of related objects (e.g., CreateAnimal and CreatePlant).</li><li>Each concrete factory (e.g., MammalFactory, BirdFactory) implements this interface to create specific types of animals and plants.</li></ul><p><strong>2. Concrete Factories</strong>:</p><ul><li><strong>MammalFactory</strong>: Creates mammals (e.g., Lion) and their associated plants (e.g., Tree).</li><li><strong>BirdFactory</strong>: Creates birds (e.g., Eagle) and their associated plants (e.g., Shrub).</li></ul><p><strong>3. Products:</strong></p><ul><li><strong>Animals</strong>: Lion and Eagle are concrete animals that implement the Animal interface.</li><li><strong>Plants</strong>: Tree and Shrub are concrete plants that implement the Plant interface.</li></ul><p><strong>4. Client Code</strong>:</p><ul><li>The main function demonstrates how to use the abstract factory to create families of related objects (e.g., mammals or birds) without knowing their concrete types.</li></ul><p>The Abstract Factory Pattern is a creational design pattern that provides an interface for creating families of related or dependent objects without specifying their concrete classes. It encapsulates object creation logic, promotes consistency, and makes systems more adaptable to change. Below, we’ll explore its key benefits</p><ul><li><strong>Encapsulates Object Creation</strong>: The Abstract Factory Pattern hides the details of object creation, allowing the client code to work with abstract interfaces rather than concrete implementations. This separation of concerns makes the code cleaner and easier to maintain.</li><li><strong>Easily Expandable</strong>: <strong>Easily Expandable</strong>: The pattern adheres to the Open/Closed Principle, meaning you can introduce new types of objects or families without altering the existing codebase. This makes the system highly scalable.</li><li><strong>Ensures Consistency: </strong>The Abstract Factory Pattern ensures that the objects created by a factory are compatible and belong to the same family. This prevents mismatches and maintains consistency across the system.</li></ul><h4>Factory Method</h4><p>The Factory Method Pattern is used when a class wants to delegate the instantiation of objects to its subclasses. Instead of calling the new keyword directly to create objects, the factory method allows a class to call a method that determines which object to instantiate.</p><p><strong>Animal Analogy</strong></p><p>In a forest, different types of wild animals (e.g., lions, eagles, bears) exist in their natural habitats. Each animal is created by nature (the factory) in a way that suits its environment. For example:</p><ul><li><strong>Lions</strong> are created in the savanna.</li><li><strong>Eagles</strong> are created in the mountains.</li><li><strong>Bears</strong> are created in the woods.</li></ul><p>The <strong>Factory Method Pattern</strong> can be used to model how these animals are created in their respective environments without exposing the creation logic.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>// Animal interface represents a wild animal in the forest<br>type Animal interface {<br> Speak() string<br> Live() string<br>}<br><br>// AnimalFactory interface defines the factory method<br>type AnimalFactory interface {<br> CreateAnimal() Animal<br>}<br><br>// LionFactory creates lions in the savanna<br>type LionFactory struct{}<br><br>func (l *LionFactory) CreateAnimal() Animal {<br> return &amp;Lion{name: &quot;Simba&quot;, habitat: &quot;Savanna&quot;}<br>}<br><br>// EagleFactory creates eagles in the mountains<br>type EagleFactory struct{}<br><br>func (e *EagleFactory) CreateAnimal() Animal {<br> return &amp;Eagle{name: &quot;Eddy&quot;, habitat: &quot;Mountains&quot;}<br>}<br><br>// BearFactory creates bears in the woods<br>type BearFactory struct{}<br><br>func (b *BearFactory) CreateAnimal() Animal {<br> return &amp;Bear{name: &quot;Baloo&quot;, habitat: &quot;Woods&quot;}<br>}<br><br>// Lion is a concrete wild animal<br>type Lion struct {<br> name    string<br> habitat string<br>}<br><br>func (l *Lion) Speak() string {<br> return fmt.Sprintf(&quot;%s the Lion says Roar!&quot;, l.name)<br>}<br><br>func (l *Lion) Live() string {<br> return fmt.Sprintf(&quot;%s lives in the %s.&quot;, l.name, l.habitat)<br>}<br><br>// Eagle is a concrete wild animal<br>type Eagle struct {<br> name    string<br> habitat string<br>}<br><br>func (e *Eagle) Speak() string {<br> return fmt.Sprintf(&quot;%s the Eagle says Screech!&quot;, e.name)<br>}<br><br>func (e *Eagle) Live() string {<br> return fmt.Sprintf(&quot;%s lives in the %s.&quot;, e.name, e.habitat)<br>}<br><br>// Bear is a concrete wild animal<br>type Bear struct {<br> name    string<br> habitat string<br>}<br><br>func (b *Bear) Speak() string {<br> return fmt.Sprintf(&quot;%s the Bear says Growl!&quot;, b.name)<br>}<br><br>func (b *Bear) Live() string {<br> return fmt.Sprintf(&quot;%s lives in the %s.&quot;, b.name, b.habitat)<br>}<br><br>func main() {<br> // Creating a Lion in the Savanna<br> lionFactory := &amp;LionFactory{}<br> lion := lionFactory.CreateAnimal()<br> fmt.Println(lion.Speak()) // Output: Simba the Lion says Roar!<br> fmt.Println(lion.Live())  // Output: Simba lives in the Savanna.<br><br> // Creating an Eagle in the Mountains<br> eagleFactory := &amp;EagleFactory{}<br> eagle := eagleFactory.CreateAnimal()<br> fmt.Println(eagle.Speak()) // Output: Eddy the Eagle says Screech!<br> fmt.Println(eagle.Live())  // Output: Eddy lives in the Mountains.<br><br> // Creating a Bear in the Woods<br> bearFactory := &amp;BearFactory{}<br> bear := bearFactory.CreateAnimal()<br> fmt.Println(bear.Speak()) // Output: Baloo the Bear says Growl!<br> fmt.Println(bear.Live())  // Output: Baloo lives in the Woods.<br>}</pre><p><strong>How It Works</strong></p><p><strong>1. Animal Interface</strong>:</p><ul><li>Represents the common behavior of all wild animals (e.g., Speak and Live methods).</li></ul><p><strong>2. Concrete Animals</strong>:</p><ul><li><strong>Lion</strong>, <strong>Eagle</strong>, and <strong>Bear</strong> are concrete implementations of the Animal interface.</li><li>Each animal has a name and a habitat that describes where it lives.</li></ul><p><strong>3. AnimalFactory Interface</strong>:</p><ul><li>Defines the factory method CreateAnimal that all concrete factories must implement.</li></ul><p><strong>4. Concrete Factories</strong>:</p><ul><li><strong>LionFactory</strong>, <strong>EagleFactory</strong>, and <strong>BearFactory</strong> are responsible for creating specific types of animals in their natural habitats.</li><li>Each factory implements the CreateAnimal method to return an instance of the corresponding animal.</li></ul><p><strong>5. Client Code</strong>:</p><ul><li>The main function demonstrates how to use the factory method to create wild animals in their respective habitats without knowing their concrete types.</li></ul><p>The Factory Method Pattern simplifies object creation by encapsulating the instantiation process, preventing the main code from handling object construction directly. Below, we explore its key benefits and why it is widely used in various scenarios.</p><ul><li><strong>Encapsulation: </strong>The main code does not need to know how specific objects, such as animals, are instantiated. This abstraction keeps the codebase clean and maintainable.</li><li><strong>Flexibility: </strong>Adding new types, like Giraffe or Tiger, is straightforward — simply create a new factory without modifying existing code. This makes the system easily extendable.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e174f424daa7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning Golang: Implementing Structs, Pointer, Interfaces, and Goroutine in Code]]></title>
            <link>https://medium.com/@prawiraa.rivan/learning-golang-implementing-structs-pointer-interfaces-and-goroutine-in-code-7f95af106943?source=rss-82176cae42df------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f95af106943</guid>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Rivan Prawira]]></dc:creator>
            <pubDate>Mon, 24 Feb 2025 06:50:41 GMT</pubDate>
            <atom:updated>2025-02-24T06:50:41.090Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N-U9pixLu_3Pug62asJMtg.png" /><figcaption>source: Pinterest</figcaption></figure><p>After understanding Go’s basic syntax, variables, and control structures, the next step is to explore more advanced features that unlock the full potential of the language. While foundational knowledge allows you to write simple programs, mastering Go’s deeper concepts is essential for building scalable, maintainable, and high-performance applications.</p><p>Go is designed with efficiency and simplicity in mind, offering powerful features that streamline development without the complexities often found in other languages. By moving beyond the basics, developers can leverage Go’s unique strengths, such as memory-efficient data structures, robust concurrency support, and an interface-driven design that promotes code reusability.</p><p>These advanced concepts not only improve the way programs are structured but also enhance performance, reduce resource consumption, and enable seamless integration with modern software architectures, such as microservices and cloud-based applications. Mastering these capabilities ensures that Go developers can write clean, efficient, and scalable code suitable for a wide range of applications.</p><p>In this section, we’ll dive into four key concepts:</p><ul><li><strong>Structs</strong> — Custom data types that group related fields, similar to classes in OOP.</li><li><strong>Pointers</strong> — Memory references that allow efficient data manipulation.</li><li><strong>Interfaces</strong> — Abstractions that enable polymorphism and flexible function implementation.</li><li><strong>Goroutines</strong> — Lightweight threads for handling concurrent execution.</li></ul><p>Mastering these concepts will help you write more structured, efficient, and scalable Go programs. Let’s explore each in detail.</p><h4>Structs</h4><p>A struct in Go is a custom data type that allows you to group related fields together into a single entity. Instead of managing multiple separate variables, a struct helps organize data in a meaningful way.</p><p>For example, consider an employee who has a firstName, lastName, and age. Instead of handling these values separately, you can define a struct called Employee to group them:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>type Employee struct {<br>    firstName string<br>    lastName  string<br>    age       int<br>}<br><br>func main() {<br>    emp := Employee{<br>        firstName: &quot;John&quot;,<br>        lastName:  &quot;Doe&quot;,<br>        age:       30,<br>    }<br><br>    fmt.Println(&quot;Employee:&quot;, emp)  // Employee: {John Doe 30}<br>    fmt.Println(&quot;Employee Age:&quot;, emp.age)  // Employee Age: 30<br>}</pre><p>In this example, the Employee struct groups the three properties together, making it easier to work with and manage related data as a single unit. In Go, the dot (.) operator is used to access individual fields of a struct. Once you have created a struct instance, you can use the dot operator to read or modify its fields.</p><p>In Go, struct fields that share the same type can be grouped together on a single line, followed by the types name. This makes the struct definition more concise and readable.</p><pre>type Employee struct {<br>    firstName, lastName string<br>    age                 int<br>}</pre><ul><li>firstName and lastName are both string types, so they are declared on the same line.</li><li>age remains on a separate line since it has a different type (int).</li></ul><p>This approach improves readability while maintaining functionality.</p><p>When a struct is declared but not explicitly initialized, its fields are automatically assigned their <strong>zero values</strong> by default. This ensures that uninitialized fields do not contain random or garbage data.</p><p><strong>Default Zero Values for Struct Fields</strong></p><ul><li>Numeric types (int, float64) → 0</li><li>Boolean (bool) → false</li><li>String (string) → &quot;&quot; (empty string)</li><li>Pointers, slices, maps, channels, interfaces, and functions → nil</li></ul><h4>Pointers</h4><p>In the Go programming language, a pointer is a special type of variable that stores the memory address of another variable rather than holding an actual value. This allows Go programs to reference and manipulate data efficiently without creating unnecessary copies. Since pointers provide direct access to memory locations, they can be used to modify the value of a variable indirectly, making them an essential tool for optimizing performance in certain scenarios.</p><p><strong>How Pointers Work in Go</strong></p><p>Every variable in Go is stored in memory, and each memory location has a unique address. A pointer does not store an actual value but instead holds the memory address of another variable, allowing access to the value stored at that address. The memory addresses in Go are typically represented in hexadecimal format, such as 0xFFAAF.</p><p>To work with pointers in Go, two key operators are commonly used:</p><ol><li><strong>The </strong><strong>&amp; Operator (Address-of Operator)</strong><br>This operator is used to obtain the memory address of a variable. Instead of returning the actual value of the variable, it provides the location where the value is stored in memory.</li><li><strong>The </strong><strong>* Operator (Dereferencing Operator)</strong><br>This operator is used to access the value stored at the memory address that a pointer holds. By dereferencing a pointer, Go allows reading or modifying the value of the original variable indirectly.</li></ol><p>In Go, a pointer is declared by specifying the data type it points to, prefixed with an asterisk (*). However, when declaring a pointer, it does not automatically store an address; it must be assigned a valid memory address from an existing variable.</p><p>For example, consider the following Go program that demonstrates how pointers work:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    var number int = 42       // A regular integer variable<br>    var ptr *int = &amp;number    // A pointer variable storing the address of &#39;number&#39;<br><br>    fmt.Println(&quot;Value of number:&quot;, number)          // Value of number: 42<br>    fmt.Println(&quot;Memory Address of number:&quot;, &amp;number) // Memory Address of number: 0xc00008c098<br>    fmt.Println(&quot;Value stored in ptr:&quot;, ptr)        // Value stored in ptr: 0xc00008c098<br>    fmt.Println(&quot;Value at ptr (dereferencing):&quot;, *ptr) // Value at ptr (dereferencing): 42<br>}</pre><p>In this example, the pointer ptr is assigned the memory address of the variable number using the &amp; operator. When the pointer is printed, it displays the memory address rather than the value. However, by using the * operator to dereference the pointer, the value stored at that address can be accessed.</p><p>One of the key advantages of pointers is their ability to modify the original variable by changing the value stored at the memory address. Since pointers reference an existing memory location, any modification made through the pointer is reflected in the original variable.</p><p>Consider the following example:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    var num int = 10<br>    var ptr *int = &amp;num   // Pointer stores the address of num<br><br>    fmt.Println(&quot;Before modification, num:&quot;, num) // Before modification, num: 10<br><br>    *ptr = 100 // Modifying the value at the memory address<br><br>    fmt.Println(&quot;After modification, num:&quot;, num) // After modification, num: 100<br>}</pre><p>In this case, the pointer ptr is used to change the value of num by assigning a new value to *ptr. Since ptr directly references the memory address of num, the change is reflected immediately.</p><p><strong>Pointers and Zero Values in Go</strong></p><p>When a pointer is declared without being assigned a valid memory address, it is automatically initialized with the <strong>zero value</strong> for pointers, which is nil. A nil pointer does not point to any valid memory location. Attempting to dereference a nil pointer will result in a runtime error.</p><p>For instance:</p><pre>var ptr *int<br>fmt.Println(ptr) // &lt;nil&gt;</pre><p>Before using a pointer, it is essential to ensure that it has been assigned a valid address to avoid unexpected behavior.</p><h4>Interfaces</h4><p>In programming, an interface is a contract that defines a set of functions that must be implemented by any type that satisfies the contract. This concept allows for abstraction and polymorphism, enabling flexible and scalable software design. The Go programming language provides robust support for interfaces, distinguishing itself with an implicit implementation approach rather than explicit declarations.</p><p>Unlike many other languages where a type must explicitly declare that it implements an interface, Go follows an implicit approach. If a type has all the methods required by an interface, it is automatically considered to implement that interface. This allows for greater flexibility and reduces boilerplate code.</p><p><strong>Defining an Interface in Go</strong></p><p>An interface in Go is declared using the interface keyword and typically consists of a set of method signatures. Any type that implements these methods automatically satisfies the interface.</p><p>For example, consider an interface named Shape:</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;math&quot;<br>)<br><br>// Define an interface<br>type Shape interface {<br>    Area() float64<br>}<br><br>// Define a struct<br>type Circle struct {<br>    Radius float64<br>}<br><br>// Implement the Area method for Circle<br>func (c Circle) Area() float64 {<br>    return math.Pi * c.Radius * c.Radius<br>}<br><br>// Define another struct<br>type Rectangle struct {<br>    Width, Height float64<br>}<br><br>// Implement the Area method for Rectangle<br>func (r Rectangle) Area() float64 {<br>    return r.Width * r.Height<br>}<br><br>func main() {<br>    var s Shape<br><br>    c := Circle{Radius: 5}<br>    r := Rectangle{Width: 4, Height: 6}<br><br>    s = c<br>    fmt.Println(&quot;Circle Area:&quot;, s.Area())<br><br>    s = r<br>    fmt.Println(&quot;Rectangle Area:&quot;, s.Area())<br>}</pre><p><strong>Key Takeaways from the Example</strong></p><ol><li><strong>Implicit Implementation:</strong> The Circle and Rectangle structs do not explicitly state that they implement Shape, yet they are automatically considered to do so because they have the required Area() method.</li><li><strong>Polymorphism in Go:</strong> The variable s of type Shape can hold both Circle and Rectangle objects, demonstrating polymorphism.</li><li><strong>Flexibility:</strong> This approach allows for adding new types that implement the Shape interface without modifying existing code, improving scalability.</li></ol><p><strong>Empty Interfaces and Their Usage</strong></p><p>Go also supports an empty interface (interface{}<strong>)</strong>, which can hold values of any type. This is useful in scenarios where a function needs to accept arbitrary data types.</p><pre>func PrintValue(value interface{}) {<br>    fmt.Println(value)<br>}<br><br>func main() {<br>    PrintValue(42)<br>    PrintValue(&quot;Hello, Go!&quot;)<br>    PrintValue([]int{1, 2, 3})<br>}</pre><p>Interfaces in Go provide a powerful way to implement polymorphism without the need for explicit declarations. They enable flexible, modular, and scalable code by allowing different types to adhere to a common contract without tightly coupling them to a specific implementation. By leveraging Go’s interface system effectively, developers can create cleaner and more maintainable code.</p><h4>Goroutine &amp; Channels</h4><p>Go is designed with concurrency in mind, allowing developers to efficiently manage multiple tasks running in parallel. Two fundamental features that enable this are <strong>goroutines</strong> and <strong>channels</strong>.</p><p>A goroutine is Go’s way of running functions concurrently without blocking the rest of the program. Think of it as a lightweight version of a thread, but more efficient.</p><p>Unlike traditional threads, which consume significant memory and processing power, goroutines are much more lightweight. You can spawn thousands of them without major performance issues.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;time&quot;<br>)<br><br>func sayHello() {<br> fmt.Println(&quot;Hello, Goroutine!&quot;)<br>}<br><br>func main() {<br> go sayHello() // Run sayHello() as a goroutine<br> fmt.Println(&quot;Main function continues...&quot;)<br> time.Sleep(time.Second) // Give the goroutine time to finish<br>}</pre><p><strong>What Happens Here?</strong></p><ol><li>The sayHello() function is started as a goroutine using go sayHello().</li><li>The main function does not wait for sayHello() to complete. Instead, it moves on and prints &quot;Main function continues...&quot;.</li><li>If we don’t add time.Sleep(time.Second), the program might exit before sayHello() runs. This happens because the main function doesn’t wait for goroutines by default.</li></ol><p>In real-world applications, instead of using time.Sleep(), we use synchronization mechanisms like sync.WaitGroup, which I’ll explain later.</p><p>Since goroutines run independently, we need a way for them to communicate safely. Instead of using shared memory (which leads to race conditions), Go provides channels, which act as pipes for passing data between goroutines.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br> messages := make(chan string) // Create a channel for strings<br><br> // Start a goroutine to send data into the channel<br> go func() {<br>  messages &lt;- &quot;Hello from Goroutine!&quot;<br> }()<br><br> // Receive data from the channel in the main function<br> msg := &lt;-messages<br> fmt.Println(msg)<br>}</pre><p><strong>What’s Happening Here?</strong></p><ol><li>make(chan string) creates a channel that holds string values.</li><li>The goroutine sends &quot;Hello from Goroutine!&quot; into the channel using messages &lt;- &quot;Hello from Goroutine!&quot;.</li><li>The main function waits until it receives a message from the channel (msg := &lt;-messages).</li><li>Only after receiving the message does the program proceed and print it.</li></ol><p>The key thing to note is that channels provide synchronization — the main function won’t move forward until it gets a value from the channel.</p><p>By default, channels are unbuffered, meaning they block the sender until there’s a receiver ready. However, we can create buffered channels that hold multiple values before blocking.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br> messages := make(chan string, 2) // Buffered channel with capacity of 2<br><br> messages &lt;- &quot;Message 1&quot; // Won’t block<br> messages &lt;- &quot;Message 2&quot; // Won’t block<br><br> fmt.Println(&lt;-messages) // Receives &quot;Message 1&quot;<br> fmt.Println(&lt;-messages) // Receives &quot;Message 2&quot;<br>}</pre><p><strong>What’s Different Here?</strong></p><ul><li>Unlike the previous example, this channel stores up to 2 messages before it blocks.</li><li>If we tried to send a third message without receiving one first, the program would block until there’s space.</li></ul><p>Buffered channels are useful for scenarios where producers send data faster than consumers process it.</p><p>In some cases, we may have multiple channels, and we don’t know which one will send data first. Go provides the select statement to handle this dynamically.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;time&quot;<br>)<br><br>func main() {<br> ch1 := make(chan string)<br> ch2 := make(chan string)<br><br> go func() {<br>  time.Sleep(2 * time.Second)<br>  ch1 &lt;- &quot;Data from channel 1&quot;<br> }()<br><br> go func() {<br>  time.Sleep(1 * time.Second)<br>  ch2 &lt;- &quot;Data from channel 2&quot;<br> }()<br><br> select {<br> case msg1 := &lt;-ch1:<br>  fmt.Println(msg1)<br> case msg2 := &lt;-ch2:<br>  fmt.Println(msg2)<br> }<br>}</pre><p><strong>What’s Happening?</strong></p><ol><li>Two goroutines send data to separate channels (ch1 and ch2) after different delays.</li><li>The select statement waits for the first available message.</li><li>Since ch2 sends its message after 1 second and ch1 after 2 seconds, the program prints &quot;Data from channel 2&quot; first.</li></ol><p>This is useful when dealing with multiple network requests, sensor data, or asynchronous processing, where responses arrive at different times.</p><p>Sometimes, we need to wait for multiple goroutines to complete before the program exits. Instead of using time.Sleep(), we can use sync.WaitGroup, which tracks active goroutines and waits for them to finish.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;sync&quot;<br> &quot;time&quot;<br>)<br><br>func worker(id int, wg *sync.WaitGroup) {<br> defer wg.Done() // Decrease counter when goroutine finishes<br> fmt.Printf(&quot;Worker %d started\n&quot;, id)<br> time.Sleep(time.Second)<br> fmt.Printf(&quot;Worker %d finished\n&quot;, id)<br>}<br><br>func main() {<br> var wg sync.WaitGroup<br><br> for i := 1; i &lt;= 3; i++ {<br>  wg.Add(1)          // Increase counter for each goroutine<br>  go worker(i, &amp;wg)  // Start worker goroutines<br> }<br><br> wg.Wait() // Wait for all workers to finish<br> fmt.Println(&quot;All workers done!&quot;)<br>}</pre><p><strong>Explanation:</strong></p><ul><li>sync.WaitGroup is a counter that keeps track of running goroutines.</li><li>wg.Add(1) is called before starting each goroutine.</li><li>Each goroutine calls wg.Done() when it finishes, decreasing the counter.</li><li>wg.Wait() blocks the main function until all goroutines complete.</li></ul><p>This approach ensures that all background tasks finish before the program exits.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f95af106943" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go for Beginners: Importing Local Files and 3rd Party Library]]></title>
            <link>https://medium.com/@prawiraa.rivan/go-for-beginners-importing-local-files-and-3rd-party-library-bbfa298be40f?source=rss-82176cae42df------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbfa298be40f</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <dc:creator><![CDATA[Rivan Prawira]]></dc:creator>
            <pubDate>Mon, 24 Feb 2025 02:34:27 GMT</pubDate>
            <atom:updated>2025-02-24T02:34:27.831Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZYYDcgSb-VV9MOUfJhCIOg.png" /><figcaption>source from Pinterest</figcaption></figure><p>In Go, a package is a group of source code files located within the same directory that are compiled together. These packages help organize code efficiently, making it more modular and easier to manage.</p><p>One of the primary benefits of using packages is the ability to export and import code between them. This allows developers to reuse functions, structures, and other components across different parts of a project, reducing redundancy and improving maintainability.</p><p>For those who are just starting with Go, understanding how to import local packages can be challenging. This guide aims to provide clear instructions on how to do so effectively.</p><h4>What is a Go Package?</h4><p>In the Go programming language, a package is a way to organize and manage source code efficiently. A package is essentially a collection of Go source files located in the same directory that are compiled together. This modular structure allows developers to reuse code, maintain a clean project structure, and prevent unnecessary repetition.</p><pre>Go project<br><br>go-project<br>  |___function<br>        |___function.go<br>  |___main.go</pre><p>Suppose the project directory is named <strong>go-project</strong>. Within this project, there are one additional directory: <strong>function</strong>.</p><p>In Go, each directory functions as a package, meaning all files contained within a directory automatically belong to that package.</p><p>The project’s root directory is always designated as the <strong>main package</strong>. Therefore, in this example, the main.go file is part of the <strong>main package</strong> by default.</p><pre>main.go<br><br>package main</pre><p>In the example, function.go is assigned to <strong>function package.</strong></p><pre>function/function.go<br><br>package function</pre><p>All exported code within a Go package becomes instantly accessible upon importing the package.</p><p>This eliminates the need to import individual files — simply importing the package grants access to all of its exported functions, variables, and types.</p><h4>How to Call Function and Variable in Package from Local Files?</h4><p>Continuing with the previously mentioned directory structure, let’s add some code to the function.go file that can be exported.</p><p>In Go, variables and functions can be made accessible outside their package by capitalizing the first letter of their identifier. This ensures they are recognized as exported entities and can be used in other packages upon import.</p><pre>function/function.go<br><br>package function<br><br>//Private visibility<br>var test1 = &quot;only inside file&quot;<br>func greet1(){<br>  return &quot;Hello&quot;<br>}<br><br>//Public visibility<br>var Test2 = &quot;can be access outside&quot;<br>func Greet2(){<br>  return &quot;hello world!&quot;<br>}</pre><p>In the given example, the variable test1 and the function greet() are considered private because their identifier names start with a lowercase letter. In Go, only identifiers that begin with an uppercase letter are exported and accessible outside their package.</p><p>In the main.go file located at the root of the project, the function package will be imported to access its exported functions or variables. The greet function from the function package will then be called, and its output will be printed to the terminal.</p><pre>main.go<br><br>package main<br><br>import (<br>  &quot;fmt&quot;<br>  &quot;go-project/function&quot;<br>)<br><br>func main(){<br>  fmt.Println(function.greet1())  //Get error<br>  fmt.Println(function.Greet2())  //Output: hello world!<br>}</pre><p>When importing a package in Go, you should start with your project module name and specify the directory where the package is located.</p><p>To summarize the concept of exported code, any file inside a Go package remains accessible as long as the package is imported. This means that if you create multiple files within the function package, all exported functions, variables, or types across those files will be available when the package is imported. To call the functions, variables, or types it starts with the package name followed by dot.</p><pre>//How to call var Test2<br>function.Test2<br>//How to call function Greet2<br>function.Greet2()</pre><h4>How to Import 3rd Party Library?</h4><p>Go is widely recognized for its robust standard library, which provides essential tools for handling strings, numbers, files, and networking. However, when dealing with more complex or specialized tasks, third-party libraries become invaluable.</p><p>Libraries in Go are essentially collections of pre-written code designed to simplify development and speed up the coding process. The Go community has contributed thousands of useful packages for various purposes, including database management, web development, and much more. By leveraging these packages, developers can save significant time and effort, avoiding the need to build everything from scratch.</p><p><strong>First</strong>, you must install the desired library using the go get command. This command fetches and adds the package to your project’s dependencies.</p><p>For example, if you want to install a package for making HTTP requests, you would run:</p><pre>go get github.com/example/http-client</pre><p>This ensures that the package is available in your Go module and ready to be imported into your code.</p><p>To use the installed library in your Go program, you need to import it. For example, if the library provides a function DownloadFile(url string) to download a file from a given URL, you can import and use it like this:</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;github.com/example/http-client&quot;<br>)<br><br>func main() {<br>    url := &quot;https://example.com/file.zip&quot;<br>    err := http_client.DownloadFile(url)<br>    <br>    if err != nil {<br>        fmt.Println(&quot;Error downloading file:&quot;, err)<br>        return<br>    }<br>    <br>    fmt.Println(&quot;File downloaded successfully!&quot;)<br>}</pre><p>This allows you to access all the exported functions and variables from the package, making it easy to integrate third-party functionality into your project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbfa298be40f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Go: Understanding Basic Syntax]]></title>
            <link>https://medium.com/@prawiraa.rivan/getting-started-with-go-understanding-basic-syntax-4d30e1172ba2?source=rss-82176cae42df------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d30e1172ba2</guid>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[go-language-tutorial]]></category>
            <category><![CDATA[go-language]]></category>
            <dc:creator><![CDATA[Rivan Prawira]]></dc:creator>
            <pubDate>Thu, 20 Feb 2025 07:17:50 GMT</pubDate>
            <atom:updated>2025-02-20T07:17:50.745Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*mHFaDCedF9lZLIao9eC_Sw.jpeg" /><figcaption>Image from Pinterest</figcaption></figure><p>Go is a powerful and efficient programming language known for its simplicity and performance, making it ideal for web services, cloud computing, and system programming. Before diving into Go development, it’s crucial to understand its basic syntax and how variables function.</p><p>To build a solid foundation in Go, we’ll explore several key concepts, including:</p><ol><li><strong>Variables &amp; Data Types</strong> (string, int, float, bool, array, slice, map)</li><li><strong>Conditional Statements</strong> (if, switch) for decision-making</li><li><strong>Looping Mechanisms</strong> (for, range) along with statement like break and continue</li><li><strong>Functions &amp; Parameters</strong> for structuring reusable code</li></ol><p>This article will introduce these core concepts to help you get started.</p><h4>Variables &amp; Data Types</h4><p>In Go, variables can be declared using two methods: with an explicit type or without specifying the type (using type inference).</p><p><strong>First Method: Declaring Variables with an Explicit Type</strong></p><p>The first method involves explicitly stating the variable’s type using the var keyword. This method is particularly useful when declaring package-level variables or when you want to ensure type consistency throughout your code.</p><pre>var name string = &quot;John&quot;<br>var age int = 25 </pre><p>In this approach:</p><ul><li>The variable name is explicitly declared as a string, meaning it can only store text values.</li><li>age is defined as an int, restricting it to whole numbers.</li></ul><p>This method ensures clarity and prevents unintended type mismatches, making the code more readable ad predictable. However, it requires slightly more typing compared to the shorthand method.</p><p><strong>Second Method: Declaring Variables Using Type Inference</strong></p><p>The second method allows Go to declare variables without explicitly specifying their types using the:= shorthand operator. The compiler automatically infers the type based on the assigned value. This method is often used within functions to make the code simpler.</p><pre>message := &quot;Hello, John&quot;<br>age := 12<br>isOld := true</pre><p>Here, Go automatically assigns the following types:</p><ul><li>&quot;Hello, john&quot; is recognized as a string</li><li>12 is inferred as an int</li><li>true is assigned as a bool</li></ul><p>This method is popular in function scopes and optimizes code shortness, making the code more readable and cleaner. However, it necessitates instant value assignment and cannot be utilized at the package level.</p><p><strong>Declaring Multiple Variables</strong></p><p>Besides that, Go also supports multiple variable declarations simultaneously by listing the variables separated by commas (,). Additionally, values can be assigned to these variables at the same time.</p><pre>var firstName, lastName string <br>fistName, lastName = &quot;John&quot;, &quot;Doe&quot;</pre><p>Values can also be assigned simultaneously during declaration by listing each variable’s value in order, separated by commas (,).</p><pre>var firstName, lastName string = &quot;John&quot;, &quot;Doe&quot;</pre><p>To make things easier, type inference technique can also be used to declare multiple variables.</p><pre>firstName, lastName := &quot;John&quot;, &quot;Doe&quot;</pre><p>To add the advantage of type inference technique, it also can declare multiple variables with different type.</p><pre>name, age := &quot;John&quot;, 25</pre><p><strong>Underscore (</strong><strong>_) Variable</strong></p><p>In Go language, there is a unique rule rarely found in other languages: every declared variable must be used. If a variable is declared but not utilized, the compiler will produce an error, preventing the program from running. This is where the underscore variable is used. The underscore (_) is a reserved variable in Go that can be used to store unused values. It acts as a &quot;trash bin&quot; for discarding data that is not needed.</p><pre>_ = &quot;Trash&quot;<br>name, _ := &quot;John&quot;, &quot;Doe&quot;</pre><p>From the example above, the variable name has value John, while value Doe contained in underscore variable, indicates the value is not used. Underscore variable also predefined, so it can use = directly without need do define first.</p><p><strong>Non-Decimal Numeric Data Type</strong></p><p>Go provides several types of non-decimal (non-floating point) numeric data. Generally, there are two main categories to be aware of:</p><ul><li>uint : A data type for positive whole numbers (natural numbers).</li><li>int : A data type for both positive and negative whole numbers (integers).</li></ul><p>These two types are further divided into several subtypes based on their value range, as detailed below.</p><ul><li>uint8 — Range from 0 to 255</li><li>uint16 — Range from 0 to 65535</li><li>uint32 — Range from 0 to 4294967295</li><li>uint64 — Range from 0 to 18446744073709551615</li><li>uint — Same with uint32 oruint64 depends on value</li><li>byte — Same with uint8</li><li>int8 — Range from -128 to 128</li><li>int16 — Range from -32768 to 32767</li><li>int32 — Range from -2147483648 to 2147483647</li><li>int64 — Range from -9223372036854775808 to 9223372036854775807</li><li>int — Same with int32 or int64 depends on value</li><li>rune — Same with int32</li></ul><pre>var num1 uint8 = 77<br><br>fmt.Printf(&quot;Result: %d\n&quot;, num1) //Output: Result: 77</pre><p>Variable num1 has a type uint8 with value 77. The string format %d used to format Non-Decimal Numeric Data Type.</p><p><strong>Decimal Numeric Data Type</strong></p><p>There are two main decimal numeric data types in Go: float32 and float64. The primary difference between them lies in the range and precision of decimal values they can store. For more details, you can refer to the <a href="https://www.h-schmidt.net/FloatConverter/IEEE754.html">IEEE specifications</a>.</p><pre>var dec =12.34<br><br>fmt.Printf(&quot;Result: %f\n&quot;, dec) //Output: Result: 12.340000<br>fmt.Printf(&quot;Result: %.3f\n&quot;, dec) //Output: Result: 12.340</pre><p>Variable dec has a type float32 with value 12.340000. The string format %f used to format Decimal Numeric Data Type into string, the decimal digits that will be generated are 6 digits. The generated decimal digits can be controlled using %nf with n symbolized decimal digits.</p><p><strong>Boolean</strong></p><p>The bool data type in Go has only two possible values: true and false. It is commonly used in conditional statements and loops to control program flow.</p><pre>var isDone bool = true<br>fmt.Printf(&quot;Done? %t \n&quot;, isDone) //Output: Done? true</pre><p>The string format %tused to format Boolean data type in fmt.Printf() function.</p><p><strong>String</strong></p><p>A distinct characteristic of the string data type is that its value is enclosed in double quotes (&quot;). For example:</p><pre>var message string = &quot;Hello!&quot;<br>fmt.Printf(&quot;message: %s \n&quot;, message) //Output: message: Hello!</pre><p>Besides using double quotes, strings can also be declared using backticks (`). The advantage of using backticks is that all characters within the string are interpreted literally, meaning escape sequences like \n, double quotes, single quotes, and even newlines are preserved as part of the string.</p><pre>var message string = &#39;Hello my name &quot;John&quot;.<br>I live in Canada.<br>nice to see you&#39;<br><br>fmt.Printf(message)<br><br>//Output<br>Hello my name &quot;John&quot;.<br>I live in Canada<br>nice to see you</pre><p><strong>Array</strong></p><p>An array is a collection of data elements of the same type, stored within a single variable. Arrays have a fixed capacity that is determined at the time of creation, meaning the number of elements stored cannot exceed the allocated size.</p><p>Each element in an array has a default zero value based on its data type. For example, an int array initializes elements to 0, while a bool array initializes them to false.</p><p>Every array element is accessed using an index, which represents its position. The index starts from 0, meaning the first element is at index 0, the second at 1, and so on. For example, usage of an array:</p><pre>var names [3]string<br>names[0] = &quot;Ara&quot;<br>names[1] = &quot;2&quot;<br>names [2] = &quot;too&quot;<br><br>fmt.Println(names[0], names[1], names [2]) //Output: Ara 2 too</pre><p>Array elements can be initialized at the time of variable declaration by enclosing the values in curly braces {} after specifying the data type. Each element is separated by a comma (,).</p><pre>var names = [3]string{&quot;Ara&quot;, &quot;2&quot;, &quot;too&quot;}<br><br>fmt.Prinln(names) //Output: [Ara 2 too]</pre><p>When declaring an array with predefined values, the size can be omitted by replacing it with three dots (...). This allows Go to automatically determine the array&#39;s length based on the number of elements provided.</p><pre>var names = [...]string{&quot;Ara&quot;, &quot;2&quot;, &quot;too&quot;}<br><br>fmt.Prinln(names) //Output: [Ara 2 too]</pre><p><strong>Slice</strong></p><p>A slice is a reference to elements of an array. It can be created independently or derived from an existing array or another slice. Since slices are reference types, any modifications made to a slice’s elements will also affect other slices that share the same memory address.</p><p>Creating a slice is similar to creating an array, but without specifying the number of elements during declaration. Accessing slice elements follows the same approach as arrays. Here’s an example of slice creation:</p><pre>var names = []string{&quot;Ara&quot;, &quot;2&quot;, &quot;too&quot;}<br><br>fmt.Println(names[0]) //Output: Ara</pre><p><strong>Map</strong></p><p>A <strong>map</strong> in Go is an associative data type that stores key-value pairs. Each value in a map is associated with a unique key, which serves as an identifier for accessing the stored data.</p><p>Unlike slices, which use numeric indices, maps allow keys to be of any data type, providing flexibility in data organization and retrieval. Applying a map in Go is straightforward. You define it using the map keyword followed by the key and value types. The following example illustrates how to declare and use a map in Go.</p><pre>var city map[string]int<br>city = map[string]int{}<br><br>city[&quot;New York&quot;] = 100<br><br>fmt.Println(&quot;New York&quot;, city[&quot;New York&quot;]) //Outout: New York 100<br>fmt.Println(&quot;Indiana&quot;, city[&quot;Indiana&quot;]) //Outout: Indiana 0</pre><p>The city variable is declared as a map where the key type is string and the value type is int. The syntax map[string]int represents a map with string keys and integer values.</p><p>By default, an uninitialized map has a zero value of nil, meaning it cannot store data until it is explicitly initialized. To avoid runtime errors, maps should be initialized using map[string]int{} before adding elements.</p><p>To add an item to a map, use the syntax:<br>city[&quot;New York&quot;] = 100<br>This assigns the value 100to the key &quot;New York&quot;.</p><p>To access a value from the map, use:<br>city[&quot;New York&quot;]</p><p>Map values are overwritten if the same key is assigned a new value, meaning the old data is replaced.</p><h4><strong>Conditional Statements</strong></h4><p>The implementation of if-else in Go is similar to other programming languages, with one key difference: parentheses around conditions are not required. Below is an example of an if-else conditional statement with three conditions:</p><pre>var point = 7<br><br>if point == 10 {<br>  fmt.Println(&quot;Perfect!&quot;)<br>} else if point &gt; 5 {<br>  fmt.Println(&quot;Pass&quot;)<br>} else {<br>  fmt.Println(&quot;Failed&quot;)<br>}</pre><p>Among the three conditions, the one that is satisfied is if point &gt; 5, since the value of the point variable is indeed greater than 5. As a result, the block of code directly under this condition (enclosed in curly braces) will be executed, producing &quot;Pass&quot; as the output.</p><p>In Go, writing an if-else statement begins with the if keyword, followed by the condition and the block of code to execute if the condition is met. If the condition is not satisfied, the else block (if present) will be executed. When handling multiple conditions, the else if statement should be used.</p><p>In another case, besides if-else there is switch. A switch statement in Go is a conditional selection that focuses on a single variable and evaluates its value against multiple possible cases. A simple example is determining whether the value of variable x is 1, 2, 3, or something else.</p><pre>var point = 6<br><br>switch point {<br>case 8:<br>  fmt.Println(&quot;Perfect&quot;)<br>case 7, 9, 5:<br>  fmt.Println(&quot;Not Bad&quot;)<br>default:<br>  fmt.Println(&quot;Ok&quot;)<br><br>//Output<br>Ok</pre><p>In the code above, no condition or case is met because the value of the point variable remains 6. When this happens, the default block is executed. Essentially, default serves the same role as else in an if-else statement.</p><p>It’s important to note that switch in Go differs from other programming languages. In Go, once a case is matched, execution does not continue to the next case, even if there is no break keyword. This behavior is the opposite of traditional switch statements in other languages, where execution continues to the next case unless explicitly stopped with break.</p><p>But there is the opposite, The fallthrough keyword in Go is used to force the execution to continue to the next case, regardless of whether its condition is met. This means that even if the next case would normally evaluate to false, it will still be executed as if it were true.</p><pre>var point = 6<br><br>switch {<br>case point == 8:<br>    fmt.Println(&quot;perfect&quot;)<br>case (point &lt; 8) &amp;&amp; (point &gt; 3):<br>    fmt.Println(&quot;awesome&quot;)<br>    fallthrough<br>case point &lt; 5:<br>    fmt.Println(&quot;you need to learn more&quot;)<br>default:<br>    {<br>        fmt.Println(&quot;not bad&quot;)<br>        fmt.Println(&quot;you need to learn more&quot;)<br>    }<br>}<br><br>//Output<br>awesome<br>you need to learn more </pre><h4><strong>Looping Mechanisms</strong></h4><p>Looping is the process of repeatedly executing a block of code as long as the specified condition is met. Typically, a variable is used for iteration or as a marker to determine when the loop should stop.</p><p>In Go, the only looping keyword available is for. However, despite having just one keyword, its functionality combines the capabilities of for, foreach, and while loops found in other programming languages.</p><p>There are several standard ways to use the for loop in Go. The first method involves defining a loop counter along with its condition directly after the for keyword. Observe and try the following code example:</p><pre>for i := 0; i &lt; 5; i++ {<br>    fmt.Println(&quot;Timer&quot;, i)<br>}<br><br>//Output<br>Timer 0<br>Timer 1<br>Timer 2<br>Timer 3<br>Timer 4 </pre><p>The second method is by writing only the condition after the for keyword. The loop counter&#39;s declaration and iteration are not included after for, only the loop condition. This concept is similar to the while loop in other programming languages.</p><pre>var i = 0<br><br>for i &lt; 5 {<br>    fmt.Println(&quot;Timer&quot;, i)<br>    i++<br>}<br><br>//Output<br>Timer 0<br>Timer 1<br>Timer 2<br>Timer 3<br>Timer 4</pre><p>The third method is writing for without any condition. This results in an infinite loop (equivalent to for true). To stop the loop, the break keyword must be used.</p><pre>var i = 0<br><br>for {<br>    fmt.Println(&quot;Timer&quot;, i)<br><br>    i++<br>    if i == 5 {<br>        break<br>    }<br>}<br><br>//Output<br>Timer 0<br>Timer 1<br>Timer 2<br>Timer 3<br>Timer 4</pre><p>The fourth method is looping using a combination of the for keyword and range. This approach is commonly used to iterate over composite data types such as strings, arrays, slices, and maps.</p><pre>var name = &quot;John&quot;<br>for i, v := range name{<br>  fmt.Println(&quot;Index=&quot;, i, &quot;Value=&quot;, v)<br>}<br>//Output<br>Index= 0 Value= J<br>Index= 1 Value= o<br>Index= 2 Value= h<br>Index= 3 Value= n<br><br><br>var num= []int{1,2,3}<br>for _, v:= range num{<br>  fmt.Println(&quot;Number=&quot;, v)<br>}<br>//Output<br>Number= 1<br>Number= 2<br>Number= 3<br><br><br>var date = map[string]int {&#39;Jan&#39; = 1, &#39;Feb&#39; = 2}<br>for i, v := range date{<br>  fmt.Println(&quot;Month=&quot;, i, &quot;Date=&quot;, v)<br>}<br>//Output<br>Month= Jan Date= 1<br>Month= Feb Date= 2 </pre><p>The break keyword is used to forcibly terminate a loop, while continue is used to skip the current iteration and proceed to the next one.</p><p>Below is an example demonstrating the use of continue and break. In this example, both keywords are utilized to display even numbers in sequential order that are greater than 0 and less than or equal to 8.</p><pre>for i := 1; i &lt;= 10; i++ {<br>    if i % 2 == 1 {<br>        continue<br>    }<br><br>    if i &gt; 8 {<br>        break<br>    }<br><br>    fmt.Println(&quot;Angka&quot;, i)<br>}</pre><p>The code above will be easier to understand if explained step by step. Here’s the breakdown:</p><ol><li>A loop runs from 1 to 10 with i as the iteration variable.</li><li>If i is an odd number (determined by i % 2 resulting in 1), the loop will skip the current iteration and move to the next one.</li><li>If i is greater than 8, the loop will terminate.</li><li>The value of i is displayed.</li></ol><h4><strong>Functions &amp; Parameters</strong></h4><p>In Go, the main() function serves as the entry point of a program and runs automatically when executed. Besides main(), we can define custom functions using the func keyword, followed by the function name, parentheses (which may include parameters), and curly braces {} to enclose the function body. Parameters are optional, allowing functions to have none, one, or multiple parameters depending on the requirements.</p><p>For better understanding, please review and try implementing the following example code of a function:</p><pre>package main<br><br>import &quot;fmt&quot;<br>import &quot;strings&quot;<br><br>func main() {<br>    var names = []string{&quot;John&quot;, &quot;Doe&quot;}<br>    printMessage(&quot;Hello&quot;, names)<br>}<br><br>func printMessage(message string, arr []string) {<br>    var nameString = strings.Join(arr, &quot; &quot;)<br>    fmt.Println(message, nameString)<br>}<br><br>//Output<br>Hello John Doe</pre><p>In the given code, a function named printMessage() is defined with two parameters: a string message and a slice of strings arr.</p><p>Within the main() function, this function is invoked by passing two arguments:</p><ul><li>The first argument, &quot;Hello&quot;, is assigned to the message parameter.</li><li>The second argument, a string slice named names, is stored in the arr parameter.</li></ul><p>Inside printMessage(), the arr slice is merged into a single string using spaces as separators. This is achieved through the strings.Join() function from the strings package.</p><p><strong>Variadic Function</strong></p><p>Go supports the concept of variadic functions, which allow a function to accept an unlimited number of arguments of the same data type.</p><p>Variadic parameters behave similarly to slices, where all provided values are stored within a single variable. Accessing individual elements in these parameters is also done using an index, just like with slices.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    var avg = calculate(2, 4, 3, 5, 4, 3, 3, 5, 5, 3)<br>    var msg = fmt.Sprintf(&quot;Mean : %.2f&quot;, avg)<br>    fmt.Println(msg)<br>}<br><br>func calculate(numbers ...int) float64 {<br>    var total int = 0<br>    for _, number := range numbers {<br>        total += number<br>    }<br><br>    var avg = float64(total) / float64(len(numbers))<br>    return avg<br>}<br><br>//Output<br>Mean : 3.70</pre><p>In the calculate() function, the numbers parameter is declared with three dots (...), indicating that it is a variadic parameter of type int.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d30e1172ba2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the MVC Pattern for Clean Code Architecture]]></title>
            <link>https://medium.com/@prawiraa.rivan/understanding-the-mvc-pattern-for-clean-code-architecture-0f37e55aa817?source=rss-82176cae42df------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f37e55aa817</guid>
            <category><![CDATA[software-design-patterns]]></category>
            <category><![CDATA[model-view-controller]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Rivan Prawira]]></dc:creator>
            <pubDate>Wed, 19 Feb 2025 04:35:48 GMT</pubDate>
            <atom:updated>2025-02-19T04:35:48.479Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LMBrhFKAIdGYDSJQN6K9Rw.png" /></figure><p>In the world of software development, writing clean, maintainable, and scalable code is a constant challenge, especially as applications grow in complexity. One of the most effective ways to tackle this challenge is by adopting a structured architectural pattern like <strong>Model-View-Controller (MVC). </strong>It’s helping you break it into smaller, easier-to-manage pieces. In this article, we’ll break down what MVC is, why it’s so useful, and how you can use it to write cleaner, more organized code.</p><h4>Definition of The Model-View-Controller (MVC) Pattern</h4><p>The <strong>Model-View-Controller (MVC)</strong> pattern is a widely used architectural design in software development that helps organize code into three distinct components: <strong>Model</strong>, <strong>View</strong>, and <strong>Controller</strong>. Each component has a specific role, ensuring a clear separation of concern and making applications easier to manage, maintain, and scale.</p><ol><li><strong>Model</strong>: The Model represents the application’s data and business logic. It handles tasks like retrieving data from a database, processing it, and enforcing rules or validations. Essentially, the Model is the backbone of the application, managing all the information and operations behind the scenes.</li><li><strong>View</strong>: The view is responsible for the user interface (UI). It takes the data from the Model and displays it in a user-interactive format, like a desktop application, mobile app screen, or webpage. The View only shows the information provided by the Model and it does not manage logic.</li><li><strong>Controller</strong>: The controller serves as a middleman between the Model and the View. After processing user input (such as a button click or form submission), it modifies the Model or View as necessary. The controller ensures that the Model and View stay in sync without directly interacting with each other.</li></ol><p>The core concept of MVC is separation of concerns — each component focuses on a specific task, reducing complexity and making the codebase more modular. To make it simpler we can assume our application is a restaurant. The Model is the kitchen provide food based on menu; the View is the menu that displays food option to order; the Controller is the waiters that deliver the menu to the kitchen and vice versa.</p><h4>Advantage of The Model-View-Controller (MVC) Pattern</h4><p>The Model-View-Controller (MVC) pattern is a widely recognized approach for structuring software applications due to its effectiveness. By separating concerns into distinct components, MVC enhances modularity, making development more efficient, manageable, and scalable. Below are the key benefits of implementing the MVC pattern.</p><ol><li><strong>Separation of Concern</strong>: One of the most significant advantages of MVC is its ability to separate an application into three distinct components: the <strong>Model</strong>, the <strong>View</strong>, and the <strong>Controller</strong>. Each component has a specific responsibility, which ensures that the codebase remains organized and easy to manage. The separation allows developers to focus on one aspect of the application at a time, reducing complexity and making it easier to debug and maintain the code.</li><li><strong>Improved Maintainability</strong>: Because MVC enforces a clear structure, it becomes much easier to maintain and update the application over time. This structure lowers the possibility of creating issues and strengthens the codebase by ensuring that modifications made to one area of the application don’t unintentionally affect other areas.</li><li><strong>Reusability of Component</strong>s: MVC encourages code reuse, which can help save time and effort during development. For example, the same Model can frequently be applied to different View or even different application. In the same manner, controllers can be made to perform standard functions like data validation or user authentication and then utilized across the application. Because the same logic is implemented consistently throughout the application, this reusability not only expedites development but also guarantees consistency.</li><li><strong>Easier Collaboration Among Teams</strong>: In larger project, multiple developers often work on different parts of the application simultaneously. MVC’s separation makes it easier for teams to collaborate without stepping on each other’s toes. For example, frontend developers can focus on <strong>View</strong>, while backend developer work on <strong>Model</strong> and <strong>Controller</strong>. This division of assignment allows teams to work in parallel, speeding up the development process and reducing some conflict.</li><li><strong>Scalability</strong>: Keeping the codebase clean and organized becomes more crucial as applications get bigger and more complicated. Applications can be scaled more easily with MVC pattern, whether you’re supporting an expanding user base, integrating with third-party services, or adding new features. You can expand or change one aspect of the application without affecting the others because each component is independent. This scalability is especially crucial for long-term initiatives that require gradual change.</li></ol><h4>Implementation of The Model-View-Controller (MVC) Pattern</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qehVzXPkHR4Bl3NW5LLJkQ.png" /><figcaption>Illustration How MVC Works</figcaption></figure><p>To give you a better understanding about how Model-View-Controller (MVC) works. Let’s look at the interaction between the key components — User, Controller, Model, and View — through the example of how this design handles a request from a server. Imagine a User initiates a request, and the process unfolds as follows:</p><ul><li><strong>User Send the Request to Controller</strong>: When a user clicks a button or visits a URL, the request goes to the Controller. The Controller’s job is to decide what to do next. It doesn’t handle data or visuals — it just directs the request. It can be imagined as you’re in cafe and tell the waiter to order coffee — the waiter is the same as Controller.</li></ul><pre>User --&gt; Controller: handleRequest()</pre><ul><li><strong>Controllers Consult the Model</strong>: The Controller asks the Model for data. The Model is responsible for all the data-related tasks, like reading from database or API. The Controller doesn’t care how the data is fetched and only need the result. This is similar to how a waiter, after taking an order from customer, simply passes it to chef in the kitchen and waits for the order to be prepared — the chef is the same as Model.</li></ul><pre>Controller --&gt; Model: data = getData()</pre><ul><li><strong>Model Retrieves Data</strong>: The Model fetches the data. For example, it might query a database to get a list of cats. The Model does not format or display data — it only processes and returns raw data to the Controller. This is just like how a chef only focuses on making the coffee, open the fridge, grabs the coffee beans, grinding the beans, and brewing it without worrying about how it will be served.</li></ul><pre>Model --&gt; Database: data = fetchData()<br>Model --&gt; Controller: return data</pre><ul><li><strong>Controller Passes Data to View</strong>: Once the Model provides the requested data, the Controller sends it to the View. The Controller’s role here is merely to facilitate the connection between the Model and the View — it does not modify or process the data itself. This is similar to how a waiter takes the coffee from the chef and hands it over to barista orplatting staff who responsible for plating or decorating it before it is served.</li></ul><pre>Controller --&gt; View: formattedData: formatData(data)</pre><ul><li><strong>View Sends Formatted Data to Controller</strong>: The View takes the raw data received from the Controller and formats it into a user-friendly interface, such as rendering a web page or displaying a list of cats in an application. The View does not handle any business logic — it only presents the information in an understandable and visually appealing way. This is similar to a barista or platting staff who arranges the coffee nicely before it reaches the customer.</li></ul><pre>View --&gt; Controller: return formattedData</pre><ul><li><strong>Controller Sends the Response to User</strong>: Finally, the Controller takes the formatted output from the View and delivers it to the User. This could be in the form of an HTML page, a JSON response, or any other presentation layer. At this point, the user can see the list of cats on their screen. Continuing with our cafe analogy, the waiter (Controller) now brings the beautifully prepared coffee (View) to the customer (User), completing the process.</li></ul><pre>Controller --&gt; User: sendResponse(formattedData)</pre><h4>Summary of The Model-View-Controller (MVC) Pattern</h4><p>The Model-View-Controller (MVC) Pattern organizes code into three interconnected components for development and maintainability.</p><ul><li><strong>Model</strong>: Manages data and business logic (e.g., database interactions, data validation).</li><li><strong>View</strong>: Handles UI/display (e.g., web pages, mobile app interfaces).</li><li><strong>Controller</strong>: Acts as an intermediary, processing user input (e.g., button clicks or form submissions), updating the Model, and refreshing the View.</li></ul><p>The MVC pattern enhances software development by separating concerns, improving maintainability, and enabling component reusability. Its modular structure allows teams to collaborate efficiently, with frontend, backend, and design specialists working in parallel. Additionally, MVC supports scalability, making it ideal for growing applications like e-commerce platforms and social media apps.</p><p>To further understand how each component interacts, we use an analogy to relate the Model-View-Controller (MVC) pattern to a restaurant system:</p><ul><li><strong>Waiter (Controller):</strong> Takes orders from customers, delivers them to the kitchen, and serves the final dish but does not cook or arrange the food.</li><li><strong>Chef (Model):</strong> Prepares the food based on the order but does not interact with customers or handle presentation.</li><li><strong>Plating Staff (View):</strong> Arranges and decorates the dish before it is served but does not cook or take orders.</li></ul><p>Just like in MVC, each role has a specific task, ensuring efficiency and separation of concerns.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f37e55aa817" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>