{"id":1920,"date":"2014-11-14T06:10:39","date_gmt":"2014-11-14T06:10:39","guid":{"rendered":"http:\/\/www.andygibson.net\/blog\/?p=1920"},"modified":"2014-11-14T10:57:53","modified_gmt":"2014-11-14T10:57:53","slug":"immutability-through-interfaces","status":"publish","type":"post","link":"https:\/\/www.andygibson.net\/old-blog\/programming\/immutability-through-interfaces\/","title":{"rendered":"Immutability Through Interfaces"},"content":{"rendered":"<p>It is often desirable to have immutable objects, objects that cannot be modified once constructed. Typically, an immutable object has fields that are declared as final and are set in the object constructor. There are getters for the fields, but no setters since the values cannot be saved. Once created, the object state doesn&#8217;t change and the objects can be shared across different threads since the state is fixed. There are plenty of caveats to that statement, for example if you have a list, while the list field reference may be final, the list itself may be able to change and have values added and removed which would spoil the immutability. <\/p>\n<p>Achieving this state can often be difficult because we rely on a number of tools and frameworks that may not support immutability such as any framework that builds an object by creating it and then setting values on it. <\/p>\n<p>However, one way around this would be to take a mutable object and make it immutable through interfaces. We do this by creating an interface that represents all the getters for an object, but none of the setters.<!--more--><\/p>\n<p>Given a domain entity of a person with an id, first and last name fields we can define an immutable interface :<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic interface ImmutablePerson {\r\n\tpublic int getId();\r\n\tpublic String getFirstName();\r\n\tpublic String getLastName();\r\n}\r\n<\/pre>\n<p>We can then implement this interface in our person class :<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class PersonEntity implements ImmutablePerson {\r\n\tprivate int id;\r\n\tprivate String firstName;\r\n\tprivate String lastName;\r\n\r\n\tpublic int getId() {\r\n\t\treturn id;\r\n\t}\r\n\r\n\tpublic void setId(int id) {\r\n\t\tthis.id = id;\r\n\t}\r\n\r\n\tpublic String getFirstName() {\r\n\t\treturn firstName;\r\n\t}\r\n\r\n\tpublic void setFirstName(String firstName) {\r\n\t\tthis.firstName = firstName;\r\n\t}\r\n}\r\n<\/pre>\n<p>Our API deals with the <code>PersonEntity<\/code> class internally, but exposes the object as the <code>ImmutablePerson<\/code> only.<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic ImmutablePerson loadPerson(int id) {\r\n\tPersonEntity result = someLoadingMechanism.getPerson(id);\r\n\tresult.setxxxxx(somevalue); \/\/we can change it internally\r\n\treturn result; \/\/once it has been returned it is only accessed as an immutable person\r\n}\r\n<\/pre>\n<p>To return a mutable instance for modification, you can return the <code>PersonEntity<\/code>. Alternatively, you can add a <code>MutablePerson<\/code> interface with just the setters and implement that. Unless you want to keep casting between the Immutable\/Mutable types, the <code>MutablePerson<\/code> interface can extend the <code>ImmutablePerson<\/code> interface so the writable version is also readable.<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic interface MutablePerson extends ImmutablePerson {\r\n\tpublic void setId(int id) {\r\n\tpublic void setFirstName(String firstName);\r\n\tpublic void setLastName(String lastName);\r\n}\r\n<\/pre>\n<p>Granted, someone can easily cast the object to a <code>PersonEntity<\/code> or <code>MutablePerson<\/code> and change the values, but then, you can also <a href=\"http:\/\/stackoverflow.com\/questions\/3301635\/change-private-static-final-field-using-java-reflection\">change static final variables with reflection<\/a> if you wanted to. The ability to cast the object to make it writable only could be an internal-use only feature.<\/p>\n<p>This mechanism can be used to return immutable objects from persistence layers. There are some caveats with certain ORM tools since they use lazy loading mechanisms that would break the immutability. Underneath the interface it is still a mutable object. With some additional code, you could create immutable collections by wrapping the underlying collections in read only collections and returning them to the user.<\/p>\n<p>Some of the JVM benefits of immutability granted upon variables marked as final would not be given to this type of solution since the underlying variables are not final or immutable.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>It is often desirable to have immutable objects, objects that cannot be modified once constructed. Typically, an immutable object has fields that are declared as final and are set in the object constructor. There are getters for the fields, but no setters since the values cannot be saved. Once created, the object state doesn&#8217;t change [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0},"categories":[80],"tags":[111,112,6,113],"_links":{"self":[{"href":"https:\/\/www.andygibson.net\/old-blog\/wp-json\/wp\/v2\/posts\/1920"}],"collection":[{"href":"https:\/\/www.andygibson.net\/old-blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.andygibson.net\/old-blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.andygibson.net\/old-blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.andygibson.net\/old-blog\/wp-json\/wp\/v2\/comments?post=1920"}],"version-history":[{"count":15,"href":"https:\/\/www.andygibson.net\/old-blog\/wp-json\/wp\/v2\/posts\/1920\/revisions"}],"predecessor-version":[{"id":1960,"href":"https:\/\/www.andygibson.net\/old-blog\/wp-json\/wp\/v2\/posts\/1920\/revisions\/1960"}],"wp:attachment":[{"href":"https:\/\/www.andygibson.net\/old-blog\/wp-json\/wp\/v2\/media?parent=1920"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.andygibson.net\/old-blog\/wp-json\/wp\/v2\/categories?post=1920"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.andygibson.net\/old-blog\/wp-json\/wp\/v2\/tags?post=1920"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}