<?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 Pravand Katyare on Medium]]></title>
        <description><![CDATA[Stories by Pravand Katyare on Medium]]></description>
        <link>https://medium.com/@katyare.pravand?source=rss-2c1434e17d87------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*6knV__zzhCHY_WRe</url>
            <title>Stories by Pravand Katyare on Medium</title>
            <link>https://medium.com/@katyare.pravand?source=rss-2c1434e17d87------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 22:50:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@katyare.pravand/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[How to implement Adapter Design Pattern in Go]]></title>
            <link>https://towardsdev.com/how-to-implement-adapter-design-pattern-in-go-c79df068373e?source=rss-2c1434e17d87------2</link>
            <guid isPermaLink="false">https://medium.com/p/c79df068373e</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[adapter-design-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[adapter-pattern]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Pravand Katyare]]></dc:creator>
            <pubDate>Fri, 22 Jul 2022 11:12:08 GMT</pubDate>
            <atom:updated>2022-07-29T05:36:20.026Z</atom:updated>
            <content:encoded><![CDATA[<p>To explain it in a really simple way with an example of the <strong>card reader, </strong>it acts as an adapter between the memory card and a laptop. You plug in the memory card into the card reader and then the card reader into the laptop, so that memory card can be read from the laptop.</p><p>The same goes with the code not all the interfaces accept everything, and the inputs to the interfaces needs to be molded as per their input requirements. In such scenarios, <strong>Adapter Design Pattern</strong> works as a mediator between two incompatible interfaces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Am6-F1U9wuLhMZFOJUwZAg.png" /><figcaption>Adapter Design Pattern</figcaption></figure><h3>When To?</h3><p>Adapter Design Pattern can be implemented when you know that the data you have as an output of some function is not compatible with the data that is required for another function/interface as an input.</p><p>It means you need to add an adapter(converter) that can adapt your input data and generate the output that is required for another function/interface.</p><h3>Scenario</h3><p>Let’s take an example of two-person originating from two different countries speaking their native language(i.e. Japanese and Russian) and we are provided to implement the code which will help both of them to communicate.</p><p>So let’s assume we are going to create a translator device that will translate Japanese to Russian and vice versa.</p><h3>How To?</h3><p>First, starting with creating a Language interface, it is what we want to translate.</p><pre>type Language interface {<br>    setSentence(string)<br>    speak()<br>}</pre><p>Not this language interface needs to be implemented into languages which is to be translated, i.e. Japanese and Russian.</p><pre>// Japanese language<br>type Japanese struct {<br>    sentence string<br>}</pre><pre>func (j *Japanese) setSentence(sentence string) {<br>    j.sentence = sentence<br>}</pre><pre>func (j *Japanese) speak() {<br>    fmt.Println(j.sentence)<br>}</pre><pre>// Russian language<br>type Russian struct {<br>    sentence string<br>}</pre><pre>func (r *Russian) setSentence(sentence string) {<br>    r.sentence = sentence<br>}</pre><pre>func (r *Russian) speak() {<br>    fmt.Println(r.sentence)<br>}</pre><p>As the Language the interface is being implemented by both the struct Japanese and Russian, now comes the time to implement the code to translate the language spoken sentences to another language. (Here, their implementation of the Adapter starts.)</p><p>As there is a need to start translating Language, let’s create an interface LanguageTranslater.</p><pre>type LanguageTranslater interface {<br>    translate(sentence string)<br>}</pre><p>LanguageTranslater interface has a translate() the function which takes the sentences spoken and need to be converter to another language and for translating those spoken sentences we need an Adapter.</p><p>So implement an LanguageAdapter struct and also create a constructor function NewLanguageAdapter() which will accept the name of spoken language as an input and return LanguageTranslater interface.</p><p>Also, we need to implement translate() function of LanguageTranslater interface into LanguageAdapter struct.</p><pre>func NewLanguageAdapter(fromLang string) LanguageTranslater {<br>    return &amp;LanguageAdapter{fromLang}<br>}</pre><pre>func (la *LanguageAdapter) translate(sentence string) {<br>    switch la.fromLang {<br>        case JAPANESE:<br>            var jap = &amp;Japanese{}<br>            jap.setSentence(sentence)<br>            translateToRussian(jap)</pre><pre>        case RUSSIAN:<br>            var rus = &amp;Russian{}<br>            rus.setSentence(sentence)<br>            translateToJapanese(rus)<br>    }<br>}</pre><p>Above is the code to identify the language spoken and based on that another language’s instance will be created.</p><p>If the spoken language is Japanese then translateToRussian() will be called and if spoken language is Russian then translateToJapanese() will be called which will have actual code to translate.</p><pre>func translateToRussian(language Language) {</pre><pre>    fmt.Println(&quot;Translating to Russian&quot;)</pre><pre>    // code for translating to Russian</pre><pre>    translatedHello := &quot;Привет!&quot;    // Japanese &quot;Hello&quot; to Russian</pre><pre>    var r = &amp;Russian{}<br>    r.setSentence(translatedHello)<br>    r.speak()<br>}</pre><pre>func translateToJapanese(language Language) {<br>    <br>    fmt.Println(&quot;Translating to Japanese&quot;)<br>    <br>    // code for translating to Japanese<br>    <br>    translatedHello := &quot;こんにちは！&quot;   // Russian &quot;Hello&quot; to Japanese</pre><pre>    var j = &amp;Japanese{}<br>    j.setSentence(translatedHello)<br>    j.speak()<br>}</pre><p>Now let’s implement main() function to translate “Hello” of both Japanese and Russian language into another.</p><pre>const (<br>    JAPANESE = &quot;japanese&quot;<br>    RUSSIAN  = &quot;russian&quot;<br>)</pre><pre>func main() {<br>    fmt.Println(&quot;-------Translate Japanese &#39;Hello&#39; to Russian.-------&quot;)<br>    translater := NewLanguageAdapter(JAPANESE)<br>    translater.translate(&quot;Привет!&quot;)<br>    <br>    fmt.Println(&quot;-------Translate Russian &#39;Hello&#39; to Japanese.-------&quot;)<br>    translater = NewLanguageAdapter(RUSSIAN)<br>    translater.translate(&quot;こんにちは！&quot;)<br>}</pre><p>Above code implementation shows us how the Adapter works as a mediator between two different interface which requires the different input types. In the LanguageAdapter code was implemented to translate one language to another.</p><p>Let’s see all code implementation clubbed into one.</p><pre>import(&quot;fmt&quot;)</pre><pre>const (<br>    JAPANESE = &quot;japanese&quot;<br>    RUSSIAN  = &quot;russian&quot;<br>)</pre><pre>type Language interface {<br>    setSentence(string)<br>    speak()<br>}</pre><pre>type LanguageTranslater interface {<br>    translate(sentence string)<br>}</pre><pre>// Japanese language<br>type Japanese struct {<br>    sentence string<br>}</pre><pre>func (j *Japanese) setSentence(sentence string) {<br>    j.sentence = sentence<br>}</pre><pre>func (j *Japanese) speak() {<br>    fmt.Println(j.sentence)<br>}</pre><pre>// Russian language<br>type Russian struct {<br>    sentence string<br>}</pre><pre>func (r *Russian) setSentence(sentence string) {<br>    r.sentence = sentence<br>}</pre><pre>func (r *Russian) speak() {<br>    fmt.Println(r.sentence)<br>}</pre><pre>func NewLanguageAdapter(fromLang string) LanguageTranslater {<br>    return &amp;LanguageAdapter{fromLang}<br>}</pre><pre>func (la *LanguageAdapter) translate(sentence string) {<br>    switch la.fromLang {<br>        case JAPANESE:<br>            var jap = &amp;Japanese{}<br>            jap.setSentence(sentence)<br>            translateToRussian(jap)</pre><pre>        case RUSSIAN:<br>            var rus = &amp;Russian{}<br>            rus.setSentence(sentence)<br>            translateToJapanese(rus)<br>    }<br>}</pre><pre>func translateToRussian(language Language) {</pre><pre>    fmt.Println(&quot;Translating to Russian&quot;)</pre><pre>    // code for translating to Russian</pre><pre>    translatedHello := &quot;Привет!&quot;    // Japanese &quot;Hello&quot; to Russian</pre><pre>    var r = &amp;Russian{}<br>    r.setSentence(translatedHello)<br>    r.speak()<br>}</pre><pre>func translateToJapanese(language Language) {<br>    <br>    fmt.Println(&quot;Translating to Japanese&quot;)<br>    <br>    // code for translating to Japanese<br>    <br>    translatedHello := &quot;こんにちは！&quot;   // Russian &quot;Hello&quot; to Japanese</pre><pre>    var j = &amp;Japanese{}<br>    j.setSentence(translatedHello)<br>    j.speak()<br>}</pre><pre>func main() {<br>    <br>    fmt.Println(&quot;-------Translate Japanese &#39;Hello&#39; to Russian.-------&quot;)<br>    translater := NewLanguageAdapter(JAPANESE)<br>    translater.translate(&quot;Привет!&quot;)<br>    <br>    <br>    fmt.Println(&quot;-------Translate Russian &#39;Hello&#39; to Japanese.-------&quot;)<br>    translater = NewLanguageAdapter(RUSSIAN)<br>    translater.translate(&quot;こんにちは！&quot;)<br>}</pre><p>Output:</p><pre>-------Translate Japanese &#39;Hello&#39; to Russian.-------<br>Translating to Russian<br>Привет!</pre><pre>-------Translate Russian &#39;Hello&#39; to Japanese.-------<br>Translating to Japanese<br>こんにちは！</pre><h3>Conclusion</h3><p>We saw the implementation of <strong>Adapter Design Pattern</strong> which is easy. you need to determine the API you have and determine the API you need to for the whole thing to work.</p><p>And then create the component which aggregrate the pointer to the adaptee and the whole thing provide the appropriate data.</p><p>Next blog on <strong>Bridge Design Pattern</strong>.</p><p>Happy Coding…!!!</p><h3>More Reads:</h3><blockquote>Factory Design Pattern Series</blockquote><p><a href="https://towardsdev.com/factory-design-pattern-in-go-63a9b423976f">Factory Design Pattern in Go</a></p><blockquote>Builder Design Pattern Series</blockquote><p><a href="https://medium.com/@katyare.pravand/builder-design-pattern-in-go-435bfee371d8">Builder Design Pattern in Go</a></p><blockquote>Singleton Design Pattern Series</blockquote><p><a href="https://medium.com/@katyare.pravand/singleton-design-pattern-in-go-333e15669711">Singleton Design Pattern in Go</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c79df068373e" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/how-to-implement-adapter-design-pattern-in-go-c79df068373e">How to implement Adapter Design Pattern in Go</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Problems with Singletons and How to Avoid Them]]></title>
            <link>https://towardsdev.com/problems-with-singletons-and-how-to-avoid-them-c3efd4d7b193?source=rss-2c1434e17d87------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3efd4d7b193</guid>
            <dc:creator><![CDATA[Pravand Katyare]]></dc:creator>
            <pubDate>Thu, 14 Jul 2022 14:56:21 GMT</pubDate>
            <atom:updated>2022-08-10T08:39:12.774Z</atom:updated>
            <content:encoded><![CDATA[<p>In the last blog, we saw the implementation of Singleton in two different ways(you can see <a href="https://medium.com/@katyare.pravand/singleton-design-pattern-in-go-333e15669711">here</a>). Now in this blog, we’ll explore the problems with the implementation of Singleton and furthermore examine the answer for the issue.</p><p><a href="https://medium.com/@katyare.pravand/singleton-design-pattern-in-go-333e15669711">Singleton Design Pattern in Go</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2kCEtcZgzmfVb-Y-xqn-aQ.png" /><figcaption>Problems with Singletons and How to Avoid Them</figcaption></figure><p>We should initially plunge into the issues with Singleton configuration design and investigate it.</p><p>Let’s see this with the example of reading data from database.</p><pre>type singletonDatabase struct {<br>    db userDB<br>}</pre><pre>func GetDBConnection() *singletonDatabase {      // Singleton<br>    once.Do(func() {<br>        // database connection logic<br>    })<br>    return userDB<br>}</pre><pre>func (sdb *singletonDatabase) GetAllUser() User {<br>    return sdb.Users()          // assume DB method<br>}</pre><pre>func GetUsers(){<br>    return GetAllUser()<br>}</pre><pre>func main() {<br>    users := GetUsers()<br>}</pre><p>Above, the code is written for establishing a database connection and once the connection is established, we are reading the data from database.</p><p>Now as the we are directly getting the Database instance by calling GetDBConnection() function and then retrieving users from database. This means we are <strong>hard-coding</strong> the function to get the users from database.</p><p><strong>The problem will arise when the unit-test are to be implemented. As there will be no probability to pass the mocked object of database. Unit-test case will actually make the database connection each time it gets executed. Here we see tight coupling.</strong></p><p>So the solution to this is <strong>Dependency Inversion Principle. </strong>Let’s explore how that could be done.</p><blockquote>The Dependency Inversion Principle (DIP) states that high level modules should not depend on low level modules; both should depend on abstractions.</blockquote><pre>type Database interface {<br>    GetAllUsers()<br>}</pre><p>Here we created an interface which is having the method GetAllUsers() which will be implemented by the structs.</p><pre>type Database interface {<br>    GetAllUsers()<br>}</pre><pre>type MockedDB struct{}</pre><pre>func GetMockedDB() Database {<br>    return &amp;MockedDB{}<br>}</pre><pre>func (mdb *MockedDB) GetAllUser() {<br>    return mdb.Users()               // assume DB method<br>}</pre><pre>func GetUsers(db Database){<br>    return db.GetAllUsers()<br>}</pre><pre>func main() {<br>    users := GetUsers(MockedDB{})<br>}</pre><p>Here were created a mocked struct which is implementing GetAllUser() function.</p><p>As both the struct are carrying out same Database interface, we have an advantage of passing the object and calling GetAllUser() whichever we want.</p><p>Now as we talked about the unit-test cases, in the earlier case it was only able to call the actual database instance. Once we created an interface and implemented the same methods as of the singletonDatabase struct, MockedDB instance could be passed along-with mocked data.</p><p>Entire code into one</p><pre>type Database interface {<br>    GetAllUsers()<br>}</pre><pre>type singletonDatabase struct {<br>    db userDB<br>}</pre><pre>func GetDBConnection() *singletonDatabase {      // Singleton<br>    once.Do(func() {<br>        // database connection logic<br>    })<br>    return userDB<br>}</pre><pre>func (sdb *singletonDatabase) GetAllUser() User {<br>    return sdb.Users()          // assume DB method<br>}</pre><pre>type MockedDB struct{}</pre><pre>func GetMockedDB() Database {<br>    return &amp;MockedDB{}<br>}</pre><pre>func (mdb *MockedDB) GetAllUser() {<br>    return mdb.Users()               // assume DB method<br>}</pre><pre>func GetUsers(db Database){<br>    return db.GetAllUsers()<br>}</pre><pre>func main() {<br>    dbUsers := GetUsers(singletonDatabase{})<br>    mockedUsers := GetUsers(MockedDB{})<br>}</pre><p>In the above code as you can see, we are able to call the function we by passing the required object into GetUsers() function.</p><p>Instead of depending on Singleton directly in code, you should have an interface and make Singleton depend on it. The reason why it is important is because then you can substitute the implmenter of your interface. You can replace this singleton with some sort of test dummies(MockedDB in our case). Depending on abstraction will get you there.</p><h3>Conclusion</h3><p>We implemented the Singleton Design Pattern in the earlier <a href="https://medium.com/@katyare.pravand/singleton-design-pattern-in-go-333e15669711">blog</a>, using init()and sync.Once (both are thread-safe).</p><blockquote>sync.Once solved the problem of one-time lazy initialization.</blockquote><p>Then investigated issue where one needed to rely upon instance created by constructor function causing tight-coupling.</p><p>Then <strong>Dependency Inversion Principle</strong> came as a savior giving us an advantage over passing and calling the functions we require to. This taught us to <strong>depend over interface and not the concrete types.</strong></p><p>Be careful of implementing Singleton Design Pattern directly into the code.</p><p>Happy Coding…!!!</p><h3><strong>More Reads:</strong></h3><ul><li><a href="https://medium.com/@katyare.pravand/singleton-design-pattern-in-go-333e15669711">Singleton Design Pattern in Go</a></li><li><a href="https://towardsdev.com/factory-design-pattern-in-go-63a9b423976f">Factory Design Pattern in Go</a></li><li><a href="https://medium.com/@katyare.pravand/builder-design-pattern-in-go-435bfee371d8">Builder Design Pattern in Go</a></li><li><a href="https://medium.com/@katyare.pravand/how-to-implement-adapter-design-pattern-in-go-c79df068373e">How to implement Adapter Design Pattern in Go</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*E7kvoCEUCDx6By13.png" /></figure><h4>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author 👇</h4><h4>🚀Developers: Learn and grow by keeping up with what matters, <a href="https://faun.to/8zxxd">JOIN FAUN.</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3efd4d7b193" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/problems-with-singletons-and-how-to-avoid-them-c3efd4d7b193">Problems with Singletons and How to Avoid Them</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Singleton Design Pattern in Go]]></title>
            <link>https://towardsdev.com/singleton-design-pattern-in-go-333e15669711?source=rss-2c1434e17d87------2</link>
            <guid isPermaLink="false">https://medium.com/p/333e15669711</guid>
            <category><![CDATA[singleton]]></category>
            <category><![CDATA[singleton-design-pattern]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Pravand Katyare]]></dc:creator>
            <pubDate>Tue, 12 Jul 2022 11:32:28 GMT</pubDate>
            <atom:updated>2022-08-19T07:09:08.879Z</atom:updated>
            <content:encoded><![CDATA[<p>Singleton is a component which is instantiated only once in the application life-cycle.</p><p>It is used almost in every application built.</p><p>In this blog for Singleton Design Pattern we’ll look into when and how to implement Singleton using Go. We will also take a look into the problem that of singleton pattern consists.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2kCEtcZgzmfVb-Y-xqn-aQ.png" /><figcaption>Singleton Design Pattern</figcaption></figure><h3>When To?</h3><ol><li>Component makes sense to initialized only once.</li><li>Construction call is too expensive.</li><li>Want to prevent from creating any additional copies.</li></ol><h3>Scenario</h3><p>Let’s take the basic scenario where you want to create a connection between your application and the database. In such case you only want a single instances to be created and use the same instance all over the application(connection pooling).</p><p>There are two ways of creating a singleton object into Go.</p><ol><li>init()</li><li>sync.Once</li></ol><p>Both the ways are used based on the requirements.</p><h3>init()</h3><p>It is a package level function which is called while the application is booting up(even before main()) and it is thread safe.</p><p>Let’s have a database connection using init() function.</p><pre>var db *sql.DB</pre><pre>func init() {<br>    cfg := mysql.Config{<br>        User:   os.Getenv(&quot;DBUSER&quot;),<br>        Passwd: os.Getenv(&quot;DBPASS&quot;),<br>        Net:    &quot;tcp&quot;,<br>        Addr:   &quot;127.0.0.1:3306&quot;,<br>        DBName: &quot;recordings&quot;,<br>    }<br>    // Get a database handle.<br>    var err error<br>    db, err = sql.Open(&quot;mysql&quot;, cfg.FormatDSN())<br>    if err != nil {<br>        log.Fatal(err)<br>    }<br><br>    pingErr := db.Ping()<br>    if pingErr != nil {<br>        log.Fatal(pingErr)<br>    }<br>}</pre><pre>// GetDBConnection returns the instance of database for connection pooling<br>func GetDBConnection() *sql.DB {<br>    return db<br>}</pre><pre>func main() {<br>    fmt.Println(&quot;Connected!&quot;)<br>}</pre><p>Here, if you look at the hierarchy of calling the function then you’ll get to see that the init() function has more priority than that of main() function.</p><p>init() function is for fast initialization. So if you want some logic to be executed even before the execution of main() function you can use init() function.</p><h3>sync.Once</h3><p>It’s Go’s inbuilt package providing you functionality of creating an instance only once.</p><p>Let’s have a database connection using sync.Once.</p><pre>var db *sql.DB<br>var once sync.Once</pre><pre>func GetDBConnection() *sql.DB {<br>    once.Do(func() {<br>            cfg := mysql.Config{<br>            User:   os.Getenv(&quot;DBUSER&quot;),<br>            Passwd: os.Getenv(&quot;DBPASS&quot;),<br>            Net:    &quot;tcp&quot;,<br>            Addr:   &quot;127.0.0.1:3306&quot;,<br>            DBName: &quot;recordings&quot;,<br>        }<br>        // Get a database handle.<br>        var err error<br>        db, err = sql.Open(&quot;mysql&quot;, cfg.FormatDSN())<br>        if err != nil {<br>            log.Fatal(err)<br>        }<br><br>        pingErr := db.Ping()<br>        if pingErr != nil {<br>            log.Fatal(pingErr)<br>        } <br>    })<br>    return db<br>}</pre><pre>func main() {<br>    db := GetDBConnection()<br>}</pre><p>In the above implementation, GetDBConnection() is getting called from main(). So here is lazy-loading mechanism where the instance being created when required instead of on boot-up.</p><p>sync.Once internally maintains a flag that once the code is executed then it should not get called again. It is not only for creating instances but also can be used when the code is to be executed only once in the application life-cycle.</p><p>The next blog is the continuation of this explaining problem and solution to <strong>Singleton Design Pattern.</strong></p><p><a href="https://medium.com/@katyare.pravand/problems-with-singletons-and-how-to-avoid-them-c3efd4d7b193">Problems with Singletons and How to Avoid Them</a></p><p>Happy Coding…!!!</p><h3>More Read:</h3><blockquote>Factory Design Pattern Series</blockquote><p><a href="https://towardsdev.com/factory-design-pattern-in-go-63a9b423976f">Factory Design Pattern in Go</a></p><blockquote>Builder Design Pattern Series</blockquote><p><a href="https://medium.com/@katyare.pravand/builder-design-pattern-in-go-435bfee371d8">Builder Design Pattern in Go</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=333e15669711" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/singleton-design-pattern-in-go-333e15669711">Singleton Design Pattern in Go</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prototype Factory Design Pattern in Go]]></title>
            <link>https://towardsdev.com/prototype-factory-design-pattern-in-go-6318f6ea002f?source=rss-2c1434e17d87------2</link>
            <guid isPermaLink="false">https://medium.com/p/6318f6ea002f</guid>
            <category><![CDATA[factory-design-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[factory-pattern]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Pravand Katyare]]></dc:creator>
            <pubDate>Mon, 04 Jul 2022 13:02:52 GMT</pubDate>
            <atom:updated>2022-08-10T08:43:38.752Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous factory pattern blog, we saw different ways to create an object and in this blog we’ll look into how to prototype.</p><p>With the continuation of the factory patterns series adding this as the last blog into this design pattern. Below are the other related blogs which will allow you to understand from the start.</p><ul><li><a href="https://towardsdev.com/factory-design-pattern-in-go-63a9b423976f">Factory Design Pattern in Go</a></li><li><a href="https://towardsdev.com/interface-factory-design-pattern-in-go-3eb6f97f20c4">Interface Factory Design Pattern in Go</a></li><li><a href="https://medium.com/@katyare.pravand/factory-generator-pattern-in-go-ca6e9af12a1b">Factory Generator Pattern in Go</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7s34F7vBMOZHWIwIMAsqmg.png" /><figcaption>Prototype Factory Design Pattern in Go</figcaption></figure><h3>When To?</h3><p>When you have to create a lots of very similar objects where you’ve some default data to be added while creating those objects.</p><h3>Scenario</h3><p>Continuing with the same example of employees as in the earlier blogs where you have to create multiple Employee struct and you have the position and the annual income selected from some table or somewhere.</p><p>So in this case what’s effective is prototype factory in which we have objects configured and the factory function which will operate a return us an particular configured object.</p><p>Let’s understand it with the code implementation by creating an Employee struct</p><pre>type Employee struct {<br>    Name, Position string<br>    Salary int<br>}</pre><p>Suppose we have Engineer and Manager’s object to be created with some configure values and for that first define the constant</p><pre>const(<br>    Engineer = iota<br>    Manager<br>)</pre><p>Now we have some positions defined as constants, let’s dive into creation of objects.</p><pre>func NewEmployee(role int) &amp;Employee {<br>    switch role {<br>    case Engineer:<br>        return &amp;Employee{&quot;&quot;, &quot;Engineer&quot;, 20000}<br>    case Manager:<br>        return &amp;Employee{&quot;&quot;, &quot;Manager&quot;, 30000}<br>    default:<br>        panic(&quot;Not supported&quot;)<br>}</pre><p>Let’s look at the whole implementation and call that from main() function.</p><pre>type Employee struct {<br>    Name, Position string<br>    Salary int<br>}</pre><pre>const(<br>    Engineer = iota<br>    Manager<br>)</pre><pre>func NewEmployee(role int) &amp;Employee {<br>    switch role {<br>    case Engineer:<br>        return &amp;Employee{&quot;&quot;, &quot;Engineer&quot;, 20000}<br>    case Manager:<br>        return &amp;Employee{&quot;&quot;, &quot;Manager&quot;, 30000}<br>    default:<br>        panic(&quot;Not supported&quot;)<br>}</pre><pre>func main() {<br>    // Manager Object<br>    manager := NewEmployee(Manager)<br>    manager.Name = &quot;Bar&quot;</pre><pre>    fmt.Println(manager)<br></pre><pre>    // Engineer Object<br>    engineer := NewEmployee(Engineer)<br>    engineer.Name = &quot;Foo&quot;</pre><pre>    fmt.Println(engineer)</pre><pre>}</pre><p>In the above example you can notice NewEmployee() function is returning the configured Employee object and that is a prototype factory function.</p><p>So whenever NewEmployee()function is called with role as parameter, it will evaluate the role and based on that it will return an object with pre-configured values which could updated and add the remaining data into object.</p><h3>Conclusion</h3><p>In Factory pattern series of blogs we saw how to create an object using ways of factory creation.</p><p>Factory function is basically a helper function for making instances. It is most used object creational pattern which is used mainly when we have a super-class with multiple sub-classes and based on input, we need to return one of the sub-class.</p><p>Next Series of blog on <strong>Singleton Design Pattern</strong>.</p><p>Happy Coding…!!!</p><h3>More Reads:</h3><blockquote>Factory Design Pattern Series</blockquote><p><a href="https://towardsdev.com/factory-design-pattern-in-go-63a9b423976f">Factory Design Pattern in Go</a></p><blockquote>Builder Design Pattern Series</blockquote><ul><li><a href="https://medium.com/@katyare.pravand/builder-design-pattern-in-go-435bfee371d8">Builder Design Pattern in Go</a></li><li><a href="https://medium.com/@katyare.pravand/scheduling-jobs-in-golang-c6173a6959a5">Scheduling Jobs in Golang</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6318f6ea002f" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/prototype-factory-design-pattern-in-go-6318f6ea002f">Prototype Factory Design Pattern in Go</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Factory Generator Pattern in Go]]></title>
            <link>https://towardsdev.com/factory-generator-pattern-in-go-ca6e9af12a1b?source=rss-2c1434e17d87------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca6e9af12a1b</guid>
            <category><![CDATA[golang-design-patterns]]></category>
            <dc:creator><![CDATA[Pravand Katyare]]></dc:creator>
            <pubDate>Thu, 30 Jun 2022 04:03:00 GMT</pubDate>
            <atom:updated>2022-07-27T07:11:38.158Z</atom:updated>
            <content:encoded><![CDATA[<p>Factory Pattern is used for object creation and to which we already had a look in previous blogs.</p><ul><li><a href="https://towardsdev.com/factory-design-pattern-in-go-63a9b423976f">Factory Design Pattern in Go</a></li><li><a href="https://towardsdev.com/interface-factory-design-pattern-in-go-3eb6f97f20c4">Interface Factory Design Pattern in Go</a></li></ul><p>Now in this blog we’ll continue and see a different way to create an object using Factory generator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EMtqByJrY7yg6fEn55pghg.png" /><figcaption>Factory Generator Pattern</figcaption></figure><p>For object creation using generator there are two ways for doing it</p><ol><li>Functional approach</li><li>Structural approach</li></ol><h3>Scenario</h3><p>Continuing with the same example for employees used in previous blogs(mentioned above).</p><p>Now we have to hire employees at multiple positions.</p><h3>Functional Approach</h3><p>In the functional approach we create function that will help into creation object.</p><p>Defining Employee struct</p><pre>type Employee struct {<br>    Name, Position string<br>    Salary         int<br>}</pre><p>Now instead of using constructor function we’ll use factory function.</p><pre>func NewEmployeeFactory(position string, salary int) func(name string) *Employee {<br>    return func(name string) {<br>        return &amp;Employee{name, position, salary}<br>}</pre><p>The above function is a factory function, the return type is different for NewEmployeeFactory.Instead of returning an Object it is returning a function and returning is function is creating an object and returning &amp;Employee{} object.</p><p>How to call such a factory function, let’s have a look</p><pre>func main() {</pre><pre>        engineerFactory := NewEmployeeFactory(&quot;SoftwareEngineer&quot;, 20000)<br>    managerFactory := NewEmployeeFactory(&quot;Manager&quot;, 30000)</pre><pre>    engineer := engineerFactory(&quot;Foo&quot;)<br>    manager := managerFactory(&quot;John&quot;)</pre><pre>    fmt.Println(engineer)<br>    fmt.Println(manager)<br>}</pre><p>In the above code, the Employee object is created by invoking NewEmployeeFactory()a function and passing data to it returns a function with is considered as return type.</p><p>As the function is returned and stored into a variable, that function is also expecting a parameter which in return provides us with the Employee object with all the information that was passed.</p><pre>OUTPUT<br>&amp;{Foo SoftwareEngineer 20000}<br>&amp;{John Manager 30000}</pre><p>In the functional approach, the data once entered cannot be modified later which makes it immutable.</p><h3>Structural Approach</h3><p>In this approach instead of going with creating a factory, function will go forward with creating a struct and use it.</p><pre>type EmployeeFactory struct {<br>    Position string<br>    Salary int<br>}</pre><pre>func (ef *EmployeeFactory) Create(name string) *Employee {<br>    return &amp;Employee{name, ef.Position, ef.Salary}<br>}</pre><pre>func NewEmployeeFactory2(position string, salary int) *EmployeeFactory {<br>    return &amp;EmployeeFactory{position, salary}<br>}</pre><p>The above code looks more structural and easy to understand. Instead of returning a function as a return type(returned in functional approach), the object is being returned from both the functions Create() and NewEmployeeFactory().</p><pre>func main() {<br>    bossFactory := NewEmployeeFactory2(&quot;CEO&quot;, 50000)</pre><pre>    bossFactory.Salary = 60000      // updating data in object</pre><pre>    boss := bossFactory.Create(&quot;Bar&quot;)</pre><pre>    fmt.Println(boss)<br></pre><pre>}</pre><p>This returns us the object while calling each function.</p><pre>OUTPUT<br>&amp;{Bar CEO 60000}</pre><p>In the structural approach, we have an option to update data even after the object is created making the object mutable.</p><p>Here we also have the possibility of using an interface and returning an interface of factories, which gives you more flexibility over the code keeping it loosely coupled.</p><h3>Conclusion</h3><p>Implemented two different approaches to object creation. One was the structural way where code was easy to understand and immutable.</p><p>Another approach was functional in which the code was written was less and needs some experience to understand and write. Here the object is mutable.</p><p>Happy Coding…!!!</p><p>Next blog on Prototype Factory Pattern.</p><h3>More Reading:</h3><ul><li><a href="https://towardsdev.com/interface-factory-design-pattern-in-go-3eb6f97f20c4">Interface Factory Design Pattern in Go</a></li><li><a href="https://towardsdev.com/factory-design-pattern-in-go-63a9b423976f">Factory Design Pattern in Go</a></li><li><a href="https://medium.com/@katyare.pravand/builder-design-pattern-in-go-435bfee371d8">Builder Design Pattern in Go</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca6e9af12a1b" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/factory-generator-pattern-in-go-ca6e9af12a1b">Factory Generator Pattern in Go</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interface Factory Design Pattern in Go]]></title>
            <link>https://towardsdev.com/interface-factory-design-pattern-in-go-3eb6f97f20c4?source=rss-2c1434e17d87------2</link>
            <guid isPermaLink="false">https://medium.com/p/3eb6f97f20c4</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[factory-pattern]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[factory-design-pattern]]></category>
            <dc:creator><![CDATA[Pravand Katyare]]></dc:creator>
            <pubDate>Mon, 27 Jun 2022 07:03:23 GMT</pubDate>
            <atom:updated>2022-07-06T07:19:22.097Z</atom:updated>
            <content:encoded><![CDATA[<p>Factory Design Pattern is one of the best way to create an object and the object is created without exposing creation logic.</p><p>In the last blog over <a href="https://medium.com/@katyare.pravand/factory-design-pattern-in-go-63a9b423976f">Factory Pattern</a>, we saw a simple way to create an object just by passing the information required.</p><p>In this blog, we’ll be looking use interface and implement factory pattern using those interfaces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8h6qMU6ZT4VtBjuqtlWh9g.png" /><figcaption>Interface Factory Design Pattern</figcaption></figure><h3>Scenario?</h3><p>Considering the same example of hiring an employee into a multi-national company. We know that if the company is based in different countries across the globe.</p><p>In this case company should pay the salary based on the local currency of respective countries.</p><p>Let’s first write a code to create an object using factory pattern to pay salary to employees.</p><pre>type employee struct {<br>    Name, Position, Location string<br>    Salary                   int<br>    Currency                 string<br>}</pre><pre>func NewEmployee(name, position, location string) *employee{<br>    return &amp;employee{<br>        Name:     name,<br>        Position: position,<br>        Salary:   20000,<br>        Currency: &quot;USD&quot;,<br>    }<br>}</pre><pre>func (e *employee) PaySalary() {<br>    fmt.Printf(&quot;Pay %s Salary of %s %v.\n&quot;, e.Name, e.Currency, e.Salary)<br>}</pre><p>Above is the basic code that will print the salary of an employee to be paid.</p><p>Now let’s think from a perspective where the employees based across globe. In such scenario we would need to add an interface and that interface will be implement by other objects providing us result base on the locations entered.</p><p>Let’s write interface first and employee struct implementing the method of interface.</p><pre>type Employee interface {<br>    PaySalary()<br>}</pre><pre>type employee struct {<br>    Name, Position, Location string<br>    Salary                   int<br>    Currency                 string<br>}</pre><pre>func NewEmployee(name, position, location string) *employee{<br>    return &amp;employee{<br>        Name:     name,<br>        Position: position,<br>        Salary:   20000,<br>        Currency: &quot;USD&quot;,<br>    }<br>}</pre><pre>func (e *employee) PaySalary() {<br>    fmt.Printf(&quot;Pay %s Salary of %s %v\n&quot;, e.Name, e.Currency, e.Salary)<br>}</pre><p>Above code once called from main function it will print give us the same output as of previous code.</p><p>So to segregate the employees based on the location create struct for employees based on location.</p><pre>// Struct for Employee based in USA and implementing Employee interface</pre><pre>type americanEmployee struct {<br>    *employee<br>}</pre><pre>func (ae *americanEmployee) PaySalary() {<br>    fmt.Printf(&quot;Pay %s Salary of %s %v.\n&quot;, ae.employee.Name,                                     ae.employee.Currency, ae.employee.Salary)<br>}</pre><pre>// Struct for Employee based in USA and implementing Employee interface<br>type indianEmployee struct {<br>    *employee<br>}</pre><pre>func (ie *indianEmployee) PaySalary() {<br>    fmt.Printf(&quot;Pay %s Salary of %s %v.\n&quot;, ie.employee.Name, ie.employee.Currency, ie.employee.Salary)<br>}</pre><pre>// Struct for Employee based in China and implementing Employee interface<br>type chineseEmployee struct {<br>    *employee<br>}</pre><pre>func (ce *chineseEmployee) PaySalary() {<br>    fmt.Printf(&quot;Pay %s Salary of %s %v.\n&quot;, ce.employee.Name, ce.employee.Currency, ce.employee.Salary)<br>}</pre><p>So the structs are created based on the location of employees and it is implementing the interface method PaySalary()</p><p>In order to create object we need to create a constructor function which will provide us object based on the location passed to it.</p><pre>const(<br>    USA   = &quot;USA&quot;<br>    INDIA = &quot;India&quot;<br>    CHINA = &quot;China&quot;<br>)</pre><pre>func NewEmployee(name, position, location string) Employee {</pre><pre>switch location {<br>    case USA:<br>        return &amp;americanEmployee{<br>            &amp;employee{<br>                Name:     name,<br>                Position: position,<br>                Location: USA,<br>                Salary:   20000,<br>                Currency: &quot;USD&quot;,<br>            },<br>        }<br>    case INDIA:<br>        return &amp;indianEmployee{<br>            &amp;employee{<br>                Name:     name,<br>                Position: position,<br>                Location: INDIA,<br>                Salary:   1500000,<br>                Currency: &quot;INR&quot;,<br>            },<br>        }</pre><pre>    case CHINA:<br>        return &amp;chineseEmployee{<br>            &amp;employee{<br>                Name:     name,<br>                Position: position,<br>                Location: CHINA,<br>                Salary:   130000,<br>                Currency: &quot;Chinese Yuan&quot;,<br>            },<br>        }<br>    default:<br>        return &amp;employee{<br>            Name:     name,<br>            Position: position,<br>            Salary:   20000,<br>            Currency: &quot;USD&quot;,<br>        }<br>    }<br>}</pre><p>Three locations are added (i.e. US, India and China) and if we don’t pass any of the location it consider USA as default location. The switch case will evaluate the currency based on the locations passed to it and will return object in Employee interface and once PaySalary() is called it will print the Employee’s name, salary and the currency in which employee’s salary is to be paid.</p><pre>func main() {<br>    emp := NewEmployee(&quot;Foo&quot;, &quot;Software Engineer&quot;, INDIA)<br>    emp.PaySalary()<br>    <br>    emp1 := NewEmployee(&quot;Bar&quot;, &quot;Software Engineer&quot;, USA)<br>    emp1.PaySalary()</pre><pre>    emp2 := NewEmployee(&quot;Chan&quot;, &quot;Software Engineer&quot;, CHINA)<br>    emp2.PaySalary()</pre><pre>    emp3 := NewEmployee(&quot;John&quot;, &quot;Software Engineer&quot;, &quot;&quot;)<br>    emp3.PaySalary()<br>}</pre><p>Output of the above would be</p><pre>Pay Foo Salary of INR 1500000.<br>Pay Boo Salary of USD 20000.<br>Pay Chan Salary of Chinese Yuan 130000.<br>Pay John Salary of USD 20000.</pre><p>Implementing an interface gives you an upper hand where you don’t have to evaluate the object creation and the methods to be called, compiler does it on a run time and provides you with output.</p><p>Taking forward Factory pattern, next topic is <strong>Factory Generator Design Pattern </strong>blog.</p><p>Happy Coding…!!!</p><h3>More Readings:</h3><ul><li><a href="https://medium.com/@katyare.pravand/prototype-factory-design-pattern-in-go-6318f6ea002f">Prototype Factory Design Pattern in Go</a></li><li><a href="https://towardsdev.com/factory-design-pattern-in-go-63a9b423976f">Factory Design Pattern in Go</a></li><li><a href="https://medium.com/@katyare.pravand/builder-design-pattern-in-go-435bfee371d8">Builder Design Pattern in Go</a></li><li><a href="https://towardsdev.com/builder-facets-design-pattern-in-go-35acb992c3d">Builder(Facets) Design Pattern in Go</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3eb6f97f20c4" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/interface-factory-design-pattern-in-go-3eb6f97f20c4">Interface Factory Design Pattern in Go</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Factory Design Pattern in Go]]></title>
            <link>https://towardsdev.com/factory-design-pattern-in-go-63a9b423976f?source=rss-2c1434e17d87------2</link>
            <guid isPermaLink="false">https://medium.com/p/63a9b423976f</guid>
            <category><![CDATA[factory-pattern]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[factory-design-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Pravand Katyare]]></dc:creator>
            <pubDate>Tue, 21 Jun 2022 04:47:51 GMT</pubDate>
            <atom:updated>2022-07-25T20:10:39.788Z</atom:updated>
            <content:encoded><![CDATA[<p>Factory pattern is used for object creation and one of the most used design pattern.</p><p>A closed approach is followed for object creation as it provides a way to hide the logic of how instances are being created.</p><p>This pattern is used when only required information needs to be passed and rest of the details are to be added based on the code template implemented to return the instance.</p><h3>Scenario</h3><p>Let’s consider a scenario of hiring an employee into a multi-national company.</p><pre>struct Employee{ <br>    Name, Position string<br>    Salary int<br>    Currency string<br>}</pre><p>It is taken for granted that an employee will get paid as per company’s standard pay and currency.</p><p>So to create an instance we already have some information by default (i.e standard pay and currency) with us and need some information to be entered.</p><pre>func NewEmployee(_name, _position string) Employee {<br>    return &amp;Employee{<br>        Name: _name,<br>        Position: _position,<br>        Salary: 20000,<br>        Currency: &quot;USD&quot;,<br>    }<br>}</pre><p>Passing the required value to the function and the rest of the default values will be added be the function itself.</p><p>Let’s have a look at the code as whole after including main() function</p><pre>type Employee struct { <br>    Name, Position string<br>    Salary int<br>    Currency string<br>}</pre><pre>func NewEmployee(_name, _position string) *Employee {<br>    return &amp;Employee{<br>        Name: _name,<br>        Position: _position,<br>        Salary: 20000,<br>        Currency: &quot;USD&quot;,<br>    }<br>}</pre><pre>func main() {<br>    emp:= NewEmployee(&quot;Foo Bar&quot;, &quot;Software Engineer&quot;)<br>   <br>    fmt.Println(&quot;Employee: &quot;, emp)<br>}</pre><p>This will return us an instance with all the values</p><pre>Employee:  &amp;{Foo Bar Software Engineer 20000 USD}</pre><p>Factory pattern is object creation pattern mostly used in the frameworks or third-party libraries which requires object creation for further processing, thus it is widely used.</p><p>It can be widely used when the scenarios is to build an SDKs or frameworks which require lots of object creations.</p><p>Go one step ahead implementing Factory pattern by learning how to implement <a href="https://medium.com/@katyare.pravand/interface-factory-design-pattern-in-go-3eb6f97f20c4"><strong>Interface Factory Design Pattern</strong></a>.</p><p><a href="https://towardsdev.com/interface-factory-design-pattern-in-go-3eb6f97f20c4">Interface Factory Design Pattern in Go</a></p><p>Happy Coding…!!!</p><h3>More Readings:</h3><ul><li><a href="https://medium.com/@katyare.pravand/factory-generator-pattern-in-go-ca6e9af12a1b">Factory Generator Pattern in Go</a></li><li><a href="https://towardsdev.com/interface-factory-design-pattern-in-go-3eb6f97f20c4">Interface Factory Design Pattern in Go</a></li><li><a href="https://medium.com/@katyare.pravand/builder-design-pattern-in-go-435bfee371d8">Builder Design Pattern in Go</a></li><li><a href="https://medium.com/@katyare.pravand/scheduling-jobs-in-golang-c6173a6959a5">Scheduling Jobs in Golang</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63a9b423976f" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/factory-design-pattern-in-go-63a9b423976f">Factory Design Pattern in Go</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Builder(Facets) Design Pattern in Go]]></title>
            <link>https://towardsdev.com/builder-facets-design-pattern-in-go-35acb992c3d?source=rss-2c1434e17d87------2</link>
            <guid isPermaLink="false">https://medium.com/p/35acb992c3d</guid>
            <category><![CDATA[builder-design-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[builder-pattern]]></category>
            <dc:creator><![CDATA[Pravand Katyare]]></dc:creator>
            <pubDate>Wed, 15 Jun 2022 12:35:13 GMT</pubDate>
            <atom:updated>2022-06-17T09:43:22.091Z</atom:updated>
            <content:encoded><![CDATA[<p>Builder Pattern is to build complex objects piece-by-piece which you can have a look <a href="https://medium.com/@katyare.pravand/builder-design-pattern-in-go-435bfee371d8">here</a>. In this we’ll go one step ahead to see how to implement Builder pattern when there is more complex instance of a class to be created.</p><p><strong>Note:</strong> To understand Builder Pattern with Facets efficiently, please read earlier blog on <a href="https://medium.com/@katyare.pravand/builder-design-pattern-in-go-435bfee371d8">Builder Pattern</a>.</p><blockquote>Facets means one side of something many-sided. For an example a <strong>polished</strong> <strong>Diamond. </strong>It has many sides, same way consider it for a where multiple builders are needed to build an instance as a whole.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CBr5QZ6JhojnXPerEA2cAQ.png" /><figcaption>Builder(Facets) Design Pattern</figcaption></figure><h3>Scenario</h3><p>Consider a scenario from the earlier <a href="https://medium.com/@katyare.pravand/builder-design-pattern-in-go-435bfee371d8">blog</a>, where user has created a new profile. Now the same user wants to order a product from website.</p><p>At the time of billing new Bill object needs to be built and bill primarily includes two details i.e. User details and Order details.</p><p>So we have to implement two new instances namely User and Order using using Builder Pattern.</p><pre>type Order struct {<br>    ProductName, Address, Phone string<br>    Price                       float32<br>}</pre><pre>type OrderBuilder struct {<br>  *BillBuilder<br>}</pre><pre>func NewOrderBuilder(firstname, lastname string) *OrderBuilder {<br>    return &amp;OrderBuilder{}<br>}</pre><pre>func (ob *OrderBuilder) WhichProduct(productName string) *OrderBuilder {<br>    ob.bill.Order.ProductName = productName<br>    return ob<br>}</pre><pre>func (ob *OrderBuilder) Price(price float32) *OrderBuilder {<br>    ob.bill.Order.Price = price<br>    return ob<br>}</pre><pre>func (ob *OrderBuilder) DeliverAt(address string) *OrderBuilder {<br>    ob.bill.Order.Address = address<br>    return ob<br>}</pre><pre>func (ob *OrderBuilder) ConnectOn(phone string) *OrderBuilder {<br>    ob.bill.Order.Phone = phone<br>    return ob<br>}</pre><p>Instance of an Order struct can be build by implementing OrderBuilder and it provides methods such as WhichProduct(), Price(), DeliverAt() and ConnectOn() to set order details in to Order object.</p><p>As a bill also contains User information also, let’s refer code implemented for User to build instance using UserBuilder. Can have a look at earlier blog <a href="https://medium.com/@katyare.pravand/builder-design-pattern-in-go-435bfee371d8">here</a>.</p><pre>type User struct {<br>    Firstname, Lastname, Address, Phone string<br>}</pre><pre>type UserBuilder struct {<br>    *BillBuilder<br>}</pre><pre>func (ub *UserBuilder) Who(firstname, lastname string) *UserBuilder {<br>    ub.bill.User.Firstname = firstname<br>    ub.bill.User.Lastname = lastname<br>    return ub<br>}</pre><pre>func (ub *UserBuilder) StaysAt(address string) *UserBuilder {<br>    ub.bill.User.Address = address<br>    return ub<br>}</pre><pre>func (ub *UserBuilder) ConnectOn(phone string) *UserBuilder {<br>    ub.bill.User.Phone = phone<br>    return ub<br>}</pre><p>User object can be created using the above implementation where Who(), StaysAt() and ConnectOn() methods will be used to populate object with required User information.</p><p>We have UserBuilder and OrderBuilder implemented to create an instances of User and Order. Now we have to include both the object into one so that the website could generate <strong>Bill</strong>.</p><p>For doing that we need one more builder to create Bill object. Let’s move forward to implement BillBuilder which will accumulate other two builders to create a Bill object as a whole.</p><pre>type Bill struct {<br>    User<br>    Order<br>}</pre><pre>type BillBuilder struct {<br>    bill *Bill<br>}</pre><pre>func NewBillBuilder() *BillBuilder {<br>    return &amp;BillBuilder{&amp;Bill{}}<br>}</pre><pre>func (bb *BillBuilder) SetProfile() *UserBuilder {<br>    return &amp;UserBuilder{bb}<br>}</pre><pre>func (bb *BillBuilder) SetOrder() *OrderBuilder {<br>    return &amp;OrderBuilder{bb}<br>}</pre><pre>func (bb *BillBuilder) Build() *Bill {<br>    return bb.bill<br>}</pre><p>In the above code both the builders are included into single to create a Bill object as a whole.</p><p>Let’s see at the main method to invoke the Builders int the main() function and generate a Bill.</p><pre>func main() {<br>    bill := NewBillBuilder().<br>                SetProfile().<br>                    Who(&quot;Foo&quot;, &quot;Bar&quot;).<br>                    StaysAt(&quot;ABC City&quot;).<br>                    ConnectOn(&quot;0090090090&quot;).<br>                SetOrder().<br>                    WhichProduct(&quot;XYZ Product&quot;).<br>                    Price(999).<br>                    DeliverAt(&quot;ABC City&quot;).<br>                    ConnectOn(&quot;5555555555&quot;)<br>                .Build()<br>    <br>    fmt.Println(&quot;Bill Object: &quot;, *bill)<br>}</pre><p>Here in main() with the provided APIs by the builders we are able to put the details into respective objects and generate the bill which will be provided to customer and further used at the time of shipment to deliver the ordered product.</p><h3>Conclusion</h3><p>In this Builder-Facets Design Pattern, we got to know how to implement Builder pattern when there are multiple instances to be created to build a single parent instance as a whole.</p><p>Here we built multiple objects using builder pattern which are <strong>dimensions(facets)</strong> that will be clubbed into a single parent object.</p><p><strong><em>Happy Coding…!!!</em></strong></p><h3><strong>More Reads:</strong></h3><p><a href="https://medium.com/@katyare.pravand/builder-design-pattern-in-go-435bfee371d8">Builder Design Pattern in Go</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35acb992c3d" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/builder-facets-design-pattern-in-go-35acb992c3d">Builder(Facets) Design Pattern in Go</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Builder Design Pattern in Go]]></title>
            <link>https://towardsdev.com/builder-design-pattern-in-go-435bfee371d8?source=rss-2c1434e17d87------2</link>
            <guid isPermaLink="false">https://medium.com/p/435bfee371d8</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[builder-pattern]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Pravand Katyare]]></dc:creator>
            <pubDate>Mon, 13 Jun 2022 03:42:24 GMT</pubDate>
            <atom:updated>2022-08-02T06:41:19.480Z</atom:updated>
            <content:encoded><![CDATA[<p>Implementing the Builder pattern is to build complex objects piece-by-piece providing more flexibility and readability to the code. In this article, we would learn when and how to implement Builder Pattern to build complex objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T_a0_ExOrSQSCbLJuZydzg.png" /><figcaption>Builder Design Pattern in Go</figcaption></figure><p><strong>Constructor</strong> is also one of the ways to create an object and it does have some cons to which Builder pattern covers up very well to create an object piece-by-piece and provides us with more flexibility in creating objects.</p><p>A generic approach is implemented in the process of constructing an object so that it can be used to create a different representation of the same object.</p><blockquote>The <strong>builder pattern</strong> is a design pattern designed to provide a flexible solution to various object creation problems in object-oriented programming.</blockquote><h3>When to use it?</h3><p>This pattern is to be implemented when:</p><ol><li>There is a need to use the constructor with a long parameter list or multiple constructors with different parameters.</li><li>There is a need to build multiple representations of a same object, i.e. objects of the same class with different characteristics.</li></ol><h3><strong>Scenario</strong></h3><p>Let’s understand the pattern diving into a scenario where you went to create a profile on an E-commerce website.</p><p>Creating your profile for the first time will make you enter some of your details:</p><pre>constructor: User(firstname, lastname, age, phone, address)</pre><p>Now let’s say only firstname and lastname is mandatory.</p><pre>constructor: User(firstname, lastname)</pre><p>Based on different combinations of entries made by user multiple constructors needs to be implemented to instantiate an object, making the code complex and multiple entries of constructor added into a class.</p><h3>How to implement it?</h3><p>Considering the user creating his profile, the code that will be written using the builder pattern would be:</p><pre>type User struct {<br>    Firstname, Lastname, Address, Phone string<br>}</pre><pre>type UserBuilder struct{<br>    User *User<br>}</pre><pre>func NewUserBuilder(firstname, lastname string) *UserBuilder {<br>    return &amp;UserBuilder{<br>        &amp;User{<br>            Firstname: firstname,<br>            Lastname:  lastname,<br>        },<br>    }<br>}</pre><pre>func (ub *UserBuilder) StaysAt(address string) *UserBuilder {<br>    ub.User.Address = address<br>    return ub<br>}</pre><pre>func (ub *UserBuilder) ConnectOn(phone string) *UserBuilder {<br>    ub.User.Phone = phone<br>    return ub<br>}</pre><pre>func (ub *UserBuilder) Build() *User {<br>    return ub.User<br>}</pre><pre>func main() {<br>    ub := NewUserBuilder(&quot;Foo&quot;, &quot;Bar&quot;)</pre><pre>    user := ub.Build()<br>    fmt.Println(&quot;User: &quot;, *user)        // Output 1</pre><pre>    user = ub.<br>            StaysAt(&quot;ABC City&quot;).<br>            ConnectOn(&quot;0090090090&quot;)<br>            .Build()</pre><pre>    fmt.Println(&quot;User: &quot;, *user)        // Output 2<br>}</pre><p>Providing us with output</p><pre>Output 1:- User:  {Foo Bar}<br>Output 2:- User:  {Foo Bar ABC City 0090090090}</pre><p>In Output 1 returns object with mandatory fields firstname and lastname while on the other hand with Output 2 we were able to add few more details to the same object, providing us with flexibility while creating an instance.</p><p>It provides with different set APIs to set properties of an object, in our case it’s StaysAt() and ConnectOn() which are not mandatory but can be used to set properties.</p><p>As the above created User the object does not have setter methods so the object cannot be updated, providing it immutability.</p><h3><strong>Advantages</strong></h3><ol><li>Constructor’s parameters decrease and provide highly readable method calls.</li><li>No need to pass null to optional parameters of the constructor while creating an instance.</li><li>Objects is always instantiated in a complete state.</li><li>Immutable objects are created without complex logic.</li></ol><h3>Disadvantages</h3><ol><li>A number of lines of code increases.</li><li>A separate builder needs to be created for each different Product.</li></ol><p><strong>More deep into Builder Design Pattern taken into another </strong><a href="https://medium.com/@katyare.pravand/builder-facets-design-pattern-in-go-35acb992c3d"><strong>blog</strong></a><strong>. Please Read and follow for more blog.</strong></p><p><strong><em>Happy Coding…!!!</em></strong></p><h3>More Readings:</h3><ul><li><a href="https://towardsdev.com/builder-facets-design-pattern-in-go-35acb992c3d">Builder(Facets) Design Pattern in Go</a></li><li><a href="https://medium.com/@katyare.pravand/scheduling-jobs-in-golang-c6173a6959a5">Scheduling Jobs in Golang</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=435bfee371d8" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/builder-design-pattern-in-go-435bfee371d8">Builder Design Pattern in Go</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scheduling Jobs in Golang]]></title>
            <link>https://towardsdev.com/scheduling-jobs-in-golang-c6173a6959a5?source=rss-2c1434e17d87------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6173a6959a5</guid>
            <category><![CDATA[quartz]]></category>
            <category><![CDATA[cron]]></category>
            <category><![CDATA[go-quartz]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[scheduling]]></category>
            <dc:creator><![CDATA[Pravand Katyare]]></dc:creator>
            <pubDate>Mon, 14 Mar 2022 11:20:02 GMT</pubDate>
            <atom:updated>2022-08-02T06:42:10.974Z</atom:updated>
            <content:encoded><![CDATA[<p>There are enormous use-cases with the requirement of running a job periodically which could be running in the background and execute its custom logic to provide end results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FspS5x3ELW30LJpfOj1rWA.png" /><figcaption>PC Credits: <a href="https://koraygocmen.medium.com/?source=post_page-----c5e8220323e0-----------------------------------">Koray Göçmen</a></figcaption></figure><p>In such scenarios, Cron jobs is the best suitable way to get things done. We’ll walk through the implementation that can be done in Golang.</p><p>We are going to see an implementation of <a href="https://github.com/reugn/go-quartz"><strong>go-quartz</strong></a><strong> </strong>written by <a href="https://github.com/reugn">reugn</a> which is an open-source library to schedule jobs.</p><h3><strong>Why this package :</strong></h3><ul><li>It’s a minimalist library, which means it is not importing any library for it’s execution other than Golang’s internal packages (zero-dependency).</li><li>It provides inbuilt functionality of running two kind of jobs i.e. Shell Job, Curl Job, and Custom Jobs(with our custom logic).</li><li>It also provides a variety of triggers which includes the Simple trigger, Cron trigger, and RunOnce trigger.</li></ul><p><strong>Shell Job</strong></p><p>For running a job basically we first need to initialize <a href="https://github.com/reugn/go-quartz">go-quartz</a> package’s standard scheduler and then start it with sched.Start() . We need provide the cron expression to the scheduler and the command which is needed to be executed as a part of our logic.</p><pre>sched := quartz.NewStdScheduler()<br>sched.Start()    // start scheduler</pre><pre>// creating a trigger with provided cron expression which also checks if the expression is correct or not.<br>cronTrigger, err := quartz.NewCronTrigger(&quot;1/3 * * * * *&quot;)<br>if err != nil {<br>    fmt.Println(err)<br>    return<br>}</pre><pre>shellJob := quartz.NewShellJob(&quot;ls -la&quot;)<br>sched.ScheduleJob(shellJob, cronTrigger)</pre><pre>time.Sleep(time.Second * 10) // not needed if the server is running.<br>fmt.Println(sched.GetJobKeys()) // prints keys associated with job.<br>fmt.Println(shellJob.Result) // prints result of the shell job.<br>sched.Stop()</pre><p><strong>Curl Job</strong></p><p>This is the inbuilt functionality provided by the package in case if there is a requirement of polling some REST API periodically.</p><pre>sched := quartz.NewStdScheduler()<br>sched.Start()</pre><pre>// <br>curlJob, err := quartz.NewCurlJob(http.MethodGet, &quot;https://jsonplaceholder.typicode.com/users/1&quot;, &quot;&quot;, nil)<br>if err != nil {<br>    fmt.Println(err)<br>    return<br>}</pre><pre>sched.ScheduleJob(curlJob, quartz.NewSimpleTrigger(time.Second*7))<br>time.Sleep(time.Second * 10) // not needed if the server is running.<br>fmt.Println(sched.GetJobKeys()) // prints keys associated with job.<br>fmt.Println(curlJob.Response) // prints response receive from API.<br>sched.Stop()</pre><p>If you see quartz.NewSimpleTrigger(time.Second*7), the functionality where one can provide time in terms of second, minutes, hours, etc. to run the job periodically.</p><p><strong>Custom Job</strong></p><p>Custom job is when we have some custom logic that is to be executed periodically. In schedular.go file we have created a scheduler and provided it with the cron expression which will allow it to execute the job after 3 seconds.</p><pre>scheduler.go</pre><pre>sched := quartz.NewStdScheduler()<br>sched.Start()<br>cronTrigger, err := quartz.NewCronTrigger(&quot;1/3 * * * * *&quot;)<br>if err != nil {<br>    fmt.Println(err)<br>    return<br>}</pre><pre>cronJob := CronJob{&quot;Cron job&quot;}<br>sched.ScheduleJob(&amp;cronJob, cronTrigger)</pre><pre>fmt.Println(scheduledJob.TriggerDescription) <br>sched.Stop()</pre><p>Here, we have passed an object of CronJob to sched.ScheduleJob() which executes provided struct and the custom logic provided in Execute() method written in cronJob.go .</p><pre>cronJob.go</pre><pre>// CronJob struct implements quartz package&#39;s <strong>Job</strong> interface{}</pre><pre>type Cronjob struct {<br>    desc string<br>}</pre><pre>func (c *CronJob) Key() int {<br>    return quartz.HashCode(c.instanceID)<br>}</pre><pre>func (c *CronJob) Description() string{<br>    return c.desc<br>}</pre><pre>func (c *CronJob) Execute(){<br>    // Your custom logic<br>}</pre><p>CronJob internally implements the Job interface which is already present in the quartz’s library. When the struct is passed to scheduleJob(), it internally has a logic to call Execute() method of the struct passed to it which will run the custom logic written and provide you with the expected results.</p><p><strong>Conclusion</strong></p><p>As there is no dependencies used by package, there are lesser the chances of security vulerability and also the size of the build decreases.</p><p>Based on the requirement you can choose the type of job whichever fits into your use-case. Happy Scheduling…!</p><p><strong>References<br></strong><a href="https://github.com/reugn/go-quartz">https://github.com/reugn/go-quartz</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6173a6959a5" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/scheduling-jobs-in-golang-c6173a6959a5">Scheduling Jobs in Golang</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>