{"id":217,"date":"2020-05-27T00:19:21","date_gmt":"2020-05-27T00:19:21","guid":{"rendered":"https:\/\/www.webagam.com\/?p=217"},"modified":"2020-12-11T00:35:54","modified_gmt":"2020-12-11T00:35:54","slug":"immutable-objects-with-builder-pattern","status":"publish","type":"post","link":"https:\/\/webagam.com\/pages\/2020\/05\/27\/immutable-objects-with-builder-pattern\/","title":{"rendered":"Immutable Objects with Builder Pattern"},"content":{"rendered":"<div id=\"wp_clap_f_217\" class=\"wp_clap_f\"><div class=\"wp_clap_f_container\"><div id=\"wp_clap_f_count_217\" class=\"wp_clap_f_count\">7<\/div> \r\n\t\t\t\t\t\t\t\t\t<div id=\"wp_clap_f_text_217\" class=\"wp_clap_f_text\">\r\n\t\t\t\t\t\t\t\t\t<span onclick=\"ClpJS.clap('https:\/\/webagam.com\/pages\/index.php','217','Clapping','Clapped','7');\">Clap\r\n\t\t\t\t\t\t\t\t\t<\/span>\r\n\t\t\t\t\t\t\t\t\t<\/div><\/div><\/div>\n<p>Builder pattern is useful in creating <strong>Immutable<\/strong> objects in <strong>multiple<\/strong> steps . Typical example in java is<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>String str = new StringBuilder()\n             .append(\"Hi\")\n             .append(\"How are you?\")\n             .toString();<\/code><\/pre>\n\n\n\n<p>As we can see, the above builder helps in creating immutable String in multiple steps.<\/p>\n\n\n\n<p>Java class which has a member variable generally has get and set methods, often called by many names like Plain Old Java Objects (POJO), Model Objects, Value Objects, transfer objects, etc.<\/p>\n\n\n\n<p>Often these classes are used to hold an object at a state with getter and setter methods, like below,<\/p>\n\n\n\n<p><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.webagam;\n\npublic class Employee {\nprivate String id;\nprivate String name;\nprivate String department;\nprivate String organization;\n\npublic String getId() {\n    return id;\n}\npublic void setId(String id) {\n    this.id = id;\n}\npublic String getName() {\n    return name;\n}\npublic void setName(String name) {\n    this.name = name;\n}\npublic String getDepartment() {\n    return department;\n}\npublic void setDepartment(String department) {\n    this.department = department;\n}\npublic String getOrganization() {\n    return organization;\n}\npublic void setOrganization(String organization) {\n    this.organization = organization;\n}\n}<\/code><\/pre>\n\n\n\n<p>Builder pattern helps create an immutable object and below are some techniques used to accomplish builder pattern. <br>Note, whether an object should be immutable or mutable depends on the use cases. <br>The motive here is only to demonstrate some ways to make achieve immutability.<\/p>\n\n\n\n<p>Method 1<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.webagam.simple;\npublic class Employee {\nprivate String id;\nprivate String name;\nprivate String department;\nprivate String organization;\nprivate String email;\n\npublic Employee(String id, String name, String department, String organization, String email) {\n    this.id = id;\n    this.name = name;\n    this.department = department;\n    this.organization = organization;\n    this.email = email;\n}\n\npublic String getId() {\n    return id;\n}\n\npublic String getName() {\n    return name;\n}\n\npublic String getDepartment() {\n    return department;\n}\n\npublic String getOrganization() {\n    return organization;\n}\n\npublic String getEmail() {\n    return email;\n}\n\npublic static void main(String args&#91;]) {\n    String id = \"xyz123\";\n    String name = \"user1\";\n    String department = \"HR\";\n    String organization = \"webagam Comp\";\n    String email = \"user1@webagam.com\";\n\n    Employee emp = new Employee(id, name, organization, department, email);\n}\n}<\/code><\/pre>\n\n\n\n<p>The simplest way to make the above employee immutable is to remove setter methods and make the constructor take all its member as a parameter.<br><br>Advantage:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>Often simple to achieve, i.e. not to have setter method and take all in the constructor.<\/li><\/ol>\n\n\n\n<p>Disadvantage:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>All parameters, even if the user does not intend to set have to be passed or need multiple constructors.<\/li><li>More prone to errors as the variable can be mismatched. In the above, if we look at it carefully it can be noted organization and department are interchanged in creating new Employee object<br>new Employee(id, name, organization, department, email);<\/li><\/ol>\n\n\n\n<p>Method 2:<br>Using traditional inner class for builder.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.webagam.builder1;\n\npublic class Employee {\nprivate String id;\nprivate String name;\nprivate String department;\nprivate String organization;\nprivate String email;\n\nprivate Employee(String id, String name, String department, String organization, String email) {\n    this.id = id;\n    this.name = name;\n    this.department = department;\n    this.organization = organization;\n    this.email = email;\n}\n\npublic String getId() {\n    return id;\n}\n\npublic String getName() {\n    return name;\n}\n\npublic String getDepartment() {\n    return department;\n}\n\npublic String getOrganization() {\n    return organization;\n}\n\npublic String getEmail() {\n    return email;\n}\n\npublic static class Builder {\n\n    private String id;\n    private String name;\n    private String department;\n    private String organization;\n    private String email;\n\n    public Builder withId(String id) {\n        this.id = id;\n        return this;\n    }\n\n    public Builder withName(String name) {\n        this.name = name;\n        return this;\n    }\n\n    public Builder withDepartment(String department) {\n        this.department = department;\n        return this;\n    }\n\n    public Builder withOrganization(String organization) {\n        this.organization = organization;\n        return this;\n    }\n\n    public Builder withEmail(String email) {\n        this.email = email;\n        return this;\n    }\n\n    public Employee build() {\n        return new Employee(id, name, department, organization, email);\n    }\n\n}\n\npublic static void main(String args&#91;]) {\n    String id = \"xyz123\";\n    String name = \"user1\";\n    String department = \"HR\";\n    String organization = \"webagam Comp\";\n    String email = \"user1@webagam.com\";\n    Employee emp = new Employee.Builder()\n                   .withId(id)\n                   .withName(name)\n                   .withDepartment(department)\n                   .withOrganization(organization)\n                   .withEmail(email)\n                   .build();\n\n}\n}<\/code><\/pre>\n\n\n\n<p>This approach works perfectly fine but one of the disadvantages of this is a more boilerplate method as we need to have a corresponding set method.<\/p>\n\n\n\n<p>Method 3:<br>Builder with no member variable and redirecting set method.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.webagam.builder2;\npublic class Employee {\nprivate String id;\nprivate String name;\nprivate String department;\nprivate String organization;\nprivate String email;\n\nprivate void setId(String id) {\n    this.id = id;\n}\n\nprivate void setName(String name) {\n    this.name = name;\n}\n\nprivate void setDepartment(String department) {\n    this.department = department;\n}\n\nprivate void setOrganization(String organization) {\n    this.organization = organization;\n}\n\nprivate void setEmail(String email) {\n    this.email = email;\n}\n\nprivate Employee() {\n\n}\n\npublic String getId() {\n    return id;\n}\n\npublic String getName() {\n    return name;\n}\n\npublic String getDepartment() {\n    return department;\n}\n\npublic String getOrganization() {\n    return organization;\n}\n\npublic String getEmail() {\n    return email;\n}\n\npublic static class Builder {\n    Employee emp = new Employee();\n\n    public Builder withId(String id) {\n        emp.setId(id);\n        return this;\n    }\n\n    public Builder withName(String name) {\n        emp.setName(name);\n        return this;\n    }\n\n    public Builder withDepartment(String department) {\n        emp.setDepartment(department);\n        return this;\n    }\n\n    public Builder withOrganization(String organization) {\n        emp.setOrganization(organization);\n        return this;\n    }\n\n    public Builder withEmail(String email) {\n        emp.setEmail(email);\n        return this;\n    }\n\n    public Employee build() {\n        return emp;\n    }\n\n}\n\npublic static void main(String args&#91;]) {\n    String id = \"xyz123\";\n    String name = \"user1\";\n    String department = \"HR\";\n    String organization = \"webagam Comp\";\n    String email = \"user1@webagam.com\";\nEmployee.Builder builder = new Employee.Builder()    \nEmployee emp = builder\n                   .withId(id)\n                   .withName(name)\n                   .withDepartment(department)\n                   .withOrganization(organization)\n                   .withEmail(email)\n                   .build();\n    \/\/builder.withEmail(ddd@ddd.com); \/\/this will change the emp object.\n}\n}<\/code><\/pre>\n\n\n\n<p>In this approach as you can see, builder class does not have any member variable and it directly sets the value in the actual object.<\/p>\n\n\n\n<p>There are many disadvantages with this approach,<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>As set methods are redirected, this may not be truly immutable because anyone who gets hold of Builder will be able to change an already built object. Hence breaking the use case of immutability.<\/li><li>Typically every call to \u201cbuild()\u201d returns a new instance of the actual object that is being built. Hence any changes done after built will only affect the successive build(), but not in the above case. Hence again breaking the case of immutability.<\/li><\/ol>\n\n\n\n<p>Method 4:<br>Using generics and lambda function to achieve builder,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.webagam.builder3;\nimport java.util.function.Consumer;\npublic class Employee {\nprivate String id;\nprivate String name;\nprivate String department;\nprivate String organization;\nprivate String email;\n\nprivate Employee(String id, String name, String department, String organization, String email) {\n    this.id = id;\n    this.name = name;\n    this.department = department;\n    this.organization = organization;\n    this.email = email;\n}\n\npublic String getId() {\n    return id;\n}\n\npublic String getName() {\n    return name;\n}\n\npublic String getDepartment() {\n    return department;\n}\n\npublic String getOrganization() {\n    return organization;\n}\n\npublic String getEmail() {\n    return email;\n}\n\npublic static class Builder {\n    public String id;\n    public String name;\n    public String department;\n    public String organization;\n    public String email;\n\n    public Builder with(Consumer&lt;Builder&gt; function) {\n        function.accept(this);\n        return this;\n    }\n    public Employee build() {\n        return new Employee(id, name, department, organization, email);\n    }\n\n}\n\npublic static void main(String args&#91;]) {\n    String id = \"xyz123\";\n    String name = \"user1\";\n    String department = \"HR\";\n    String organization = \"webagam Comp\";\n    String email = \"user1@webagam.com\";\n    \/\/1\n    Employee emp1 = new Employee.Builder()\n            .with($ -&gt; {\n                $.id = id;\n                $.name = name;\n                $.organization = organization;\n                $.department = department;\n                $.email = email;\n            }).build();\n    \/\/Uncommenting the below code will result in compilation error. \n\n    \/\/department = \u201cFin\u201d; \n    \/\/2\n    Employee emp2 = new Employee.Builder()\n            .with($ -&gt; {$.id = id;})\n            .with($ -&gt; $.name=name)\n            .with($ -&gt; $.department = department)\n            .build();\n\n}\n}<\/code><\/pre>\n\n\n\n<p>In the above, as you can see we have used a java lambda function to achieve builder.<\/p>\n\n\n\n<p>Advantages:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>There need not be any setter method, hence no boiler plate code.<\/li><li>Code looks clear and can also be chained as shown above.<\/li><\/ol>\n\n\n\n<p>Disadvantages:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>Builder class member variables are public. Personally, I don\u2019t think this should be an issue but it may not be agreeable to the general policy of making everything private.<\/li><li>As we use the lambda function, the variable used in the lambda function should be final or implicitly final.<br>i.e. in the above example, all variables are not changed once they are set, hence java makes it implicitly final.<br>However, uncommenting the \u201cdepartment = fin\u201d code in the above example will result in a compilation error.<\/li><\/ol>\n\n\n\n<p>Method 5:<\/p>\n\n\n\n<p>Method 5 is same as method 4 with an additional builder method which can tackle one of the disadvantage (2nd one) mentioned above.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.webagam.builder4;\nimport java.util.function.BiConsumer;\nimport java.util.function.Consumer;\npublic class Employee {\n\u2026.. \/\/ Omitted for brevity\npublic static class Builder {\n    public String id;\n    public String name;\n    public String department;\n    public String organization;\n    public String email;\n\n    public Builder with(Consumer&lt;Builder&gt; function) {\n        function.accept(this);\n        return this;\n    }\n\n    public &lt;D&gt; Builder with(BiConsumer&lt;Builder, D&gt; function, D value) {\n        function.accept(this, value);\n        return this;\n    }\n\n    public Employee build() {\n        return new Employee(id, name, department, organization, email);\n    }\n\n}\n\npublic static void main(String args&#91;]) {\n    String id = \"xyz123\";\n    String name = \"user1\";\n    String department = \"HR\";\n    String organization = \"webagam Comp\";\n    String email = \"user1@webagam.com\";\n\n    \/\/0\n    Employee emp = new Employee.Builder()\n            .with(($, fname) -&gt; {\n                $.name = fname;\n            }, name)\n            .build();\n    \/\/1\n    Employee emp1 = new Employee.Builder()\n            .with($ -&gt; {\n                $.id = id;\n                $.name = name;\n                $.organization = organization;\n                \/\/$.department = department; \/\/ If uncommented, this will be a compilation error\n                $.email = email;\n            }).build();\n\n    \/\/2\n    Employee emp2 = new Employee.Builder()\n            .with($ -&gt; {$.id = id;})\n            .with($ -&gt; $.name=name)\n            \/\/.with($ -&gt; $.department = department) \n            \/\/if the above line is uncommented, it will be compilation error \n            \/\/as department is changing and not final\n            .build();\n\n    department = \"Finance\";\n    \/\/3\n    Employee emp3 = new Employee.Builder()\n            .with($ -&gt; {$.id = id;})\n            .with($ -&gt; $.name=name)\n            .with( ($,dept) -&gt; {\n                $.department = dept;}, \n                    department)\n            .build();\n}\n}<\/code><\/pre>\n\n\n\n<p>Advantage &amp; dis advantage are similar to method 4, except for the fact that it helps get rid of 2nd dis advantage.<\/p>\n\n\n\n<p>Method 6:<br>Finally, Project Lombok is a good tool to generate getter or setter (or both) not just for builder use case but also for any class.<br>Hence Employee can be with @Getter annotation and Builder can have @Setter annotation.<\/p>\n\n\n\n<p>This do help in getting rid of boiler plate.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.webagam.builder5;\nimport lombok.Data;\nimport lombok.Getter;\nimport lombok.Setter;\n\npublic @Getter class Employee {private String id;\nprivate String name;\nprivate String department;\nprivate String organization;\nprivate String email;\n\nprivate Employee(String id, String name, String department, String organization, String email) {\n    this.id = id;\n    this.name = name;\n    this.department = department;\n    this.organization = organization;\n    this.email = email;\n}\n\n\npublic @Data static class Builder {\n    public String id;\n    public String name;\n    public String department;\n    public String organization;\n    public String email;\n\n    public Employee build() {\n        return new Employee(id, name, department, organization, email);\n    }\n\n}\n}<\/code><\/pre>\n\n\n\n<p>Each of the above methods can be debated to be good or bad, but hope each of them will have a place in different use cases.<\/p>\n<!-- WP-Clap --><div id=\"wp_clap_217\" class=\"wp_clap\"><!-- BEGIN WP-Clap --><h3 class=\"wp_clap_title\" >Clap<\/h3><div id=\"wp_clap_do_217\" class=\"wp_clap_do\"><a href=\"javascript:void(0);\" onclick=\"ClpJS.clap('https:\/\/webagam.com\/pages\/index.php','217','Clapping','Clapped','7');\"><img data-recalc-dims=\"1\" decoding=\"async\" class=\"wp_clap_img\" alt=\"Clap\" src=\"https:\/\/i0.wp.com\/www.webagam.com\/pages\/wp-content\/plugins\/wp-clap\/images\/clap_32x32.gif?w=800\" \/>Clap<\/a><\/div><div class=\"wp_clap_clappers\"><span class=\"wp_clap_single_clapper\"><span class=\"wp_clap_avatar\"><img loading=\"lazy\" decoding=\"async\" alt=\"Claps\" title=\"Claps\" src=\"http:\/\/www.gravatar.com\/avatar.php?gravatar_id=d41d8cd98f00b204e9800998ecf8427e&size=32&default=\" width=\"32\" height=\"32\"\/><\/span><span class=\"wp_clap_name\"><a href=\"\">Claps<\/a><span class=\"wp_clap_frequency\">(6)<\/span><\/span><\/span><span class=\"wp_clap_single_clapper\"><span class=\"wp_clap_avatar\"><img loading=\"lazy\" decoding=\"async\" alt=\"Niranjan R.\" title=\"Niranjan R.\" src=\"http:\/\/www.gravatar.com\/avatar.php?gravatar_id=9afdc4dee4f41346fe2beb8c68c7ad85&size=32&default=\" width=\"32\" height=\"32\"\/><\/span><span class=\"wp_clap_name\"><a href=\"http:\/\/www.webagam.com\">Niranjan R.<\/a><\/span><\/span><div class=\"wp_clap_clear\"><\/div><\/div><!-- END WP-Clap --><\/div>","protected":false},"excerpt":{"rendered":"<div id=\"wp_clap_f_217\" class=\"wp_clap_f\"><div class=\"wp_clap_f_container\"><div id=\"wp_clap_f_count_217\" class=\"wp_clap_f_count\">7<\/div> \r\n\t\t\t\t\t\t\t\t\t<div id=\"wp_clap_f_text_217\" class=\"wp_clap_f_text\">\r\n\t\t\t\t\t\t\t\t\t<span onclick=\"ClpJS.clap('https:\/\/webagam.com\/pages\/index.php','217','Clapping','Clapped','7');\">Clap\r\n\t\t\t\t\t\t\t\t\t<\/span>\r\n\t\t\t\t\t\t\t\t\t<\/div><\/div><\/div><p>7 Clap Builder pattern is useful in creating Immutable objects in multiple steps . Typical example in java is As we can see, the above builder helps in creating immutable String in multiple steps. Java class which has a member variable generally has get and set methods, often called by many names like Plain Old Java Objects (POJO), Model Objects,&hellip; <span class=\"read-more-span\"><a href=\"https:\/\/webagam.com\/pages\/2020\/05\/27\/immutable-objects-with-builder-pattern\/\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;Immutable Objects with Builder Pattern&#8221;<\/span><\/a><\/span><\/p>\n<!-- WP-Clap --><div id=\"wp_clap_217\" class=\"wp_clap\"><!-- BEGIN WP-Clap --><h3 class=\"wp_clap_title\" >Clap<\/h3><div id=\"wp_clap_do_217\" class=\"wp_clap_do\"><a href=\"javascript:void(0);\" onclick=\"ClpJS.clap('https:\/\/webagam.com\/pages\/index.php','217','Clapping','Clapped','7');\"><img decoding=\"async\" class=\"wp_clap_img\" alt=\"Clap\" src=\"http:\/\/www.webagam.com\/pages\/wp-content\/plugins\/wp-clap\/images\/clap_32x32.gif\" \/>Clap<\/a><\/div><div class=\"wp_clap_clappers\"><span class=\"wp_clap_single_clapper\"><span class=\"wp_clap_avatar\"><img loading=\"lazy\" decoding=\"async\" alt=\"Claps\" title=\"Claps\" src=\"http:\/\/www.gravatar.com\/avatar.php?gravatar_id=d41d8cd98f00b204e9800998ecf8427e&size=32&default=\" width=\"32\" height=\"32\"\/><\/span><span class=\"wp_clap_name\"><a href=\"\">Claps<\/a><span class=\"wp_clap_frequency\">(6)<\/span><\/span><\/span><span class=\"wp_clap_single_clapper\"><span class=\"wp_clap_avatar\"><img loading=\"lazy\" decoding=\"async\" alt=\"Niranjan R.\" title=\"Niranjan R.\" src=\"http:\/\/www.gravatar.com\/avatar.php?gravatar_id=9afdc4dee4f41346fe2beb8c68c7ad85&size=32&default=\" width=\"32\" height=\"32\"\/><\/span><span class=\"wp_clap_name\"><a href=\"http:\/\/www.webagam.com\">Niranjan R.<\/a><\/span><\/span><div class=\"wp_clap_clear\"><\/div><\/div><!-- END WP-Clap --><\/div>","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[27,25,18],"tags":[26],"class_list":["post-217","post","type-post","status-publish","format-standard","hentry","category-builder","category-pattern","category-programming","tag-programming-builder-pattern-immutable-lambda"],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/padP6e-3v","_links":{"self":[{"href":"https:\/\/webagam.com\/pages\/wp-json\/wp\/v2\/posts\/217","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/webagam.com\/pages\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/webagam.com\/pages\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/webagam.com\/pages\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/webagam.com\/pages\/wp-json\/wp\/v2\/comments?post=217"}],"version-history":[{"count":24,"href":"https:\/\/webagam.com\/pages\/wp-json\/wp\/v2\/posts\/217\/revisions"}],"predecessor-version":[{"id":290,"href":"https:\/\/webagam.com\/pages\/wp-json\/wp\/v2\/posts\/217\/revisions\/290"}],"wp:attachment":[{"href":"https:\/\/webagam.com\/pages\/wp-json\/wp\/v2\/media?parent=217"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/webagam.com\/pages\/wp-json\/wp\/v2\/categories?post=217"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/webagam.com\/pages\/wp-json\/wp\/v2\/tags?post=217"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}