{"id":15,"date":"2020-07-19T06:30:05","date_gmt":"2020-07-19T06:30:05","guid":{"rendered":"https:\/\/system.camp\/index.php\/2020\/07\/19\/consider-static-factory-methods-instead-of-constructors-when-creating-objects\/"},"modified":"2020-10-06T09:56:51","modified_gmt":"2020-10-06T09:56:51","slug":"consider-static-factory-methods-instead-of-constructors-when-creating-objects","status":"publish","type":"post","link":"https:\/\/system.camp\/tutorial\/consider-static-factory-methods-instead-of-constructors-when-creating-objects\/","title":{"rendered":"Consider static factory methods instead of constructors when creating objects"},"content":{"rendered":"\n
What is the most common way to create an object of a class? Yeah, you probably guessed it right! By using a constructor. But is it always the best way? We\u2019ll find out here!<\/p>\n\n\n\n
Another way to create objects of a class is by using a public static factory method. This method creates an instance of a class and then returns it. Providing a static method has its own set of advantages and disadvantages.<\/p>\n\n\n\n
Let us first discuss the advantages:<\/p>\n\n\n\n
BigInteger<\/code> constructor BigInteger(int, int, Random)<\/code> which is expected to return a prime number. This could be better expressed by using a function name createProbablePrime<\/code>. A class can have only one constructor with a particular signature. Programmers tend to have a workaround where the order of parameters is different for constructors that behave differently. This is a bad practice since the caller class might call the wrong constructor when there are multiple such permutations of the same set of parameters.<\/li>- Another advantage of using static factory methods is that they can cache the objects once created and need not create a new object every single time they are invoked like a constructor. This practice often improves the performance and makes the program light weight to run. This is generally used when dealing with classes where the object creation is a costly affair.<\/li>
- Static factory methods can also return any subtype of their return type. This is something which cannot be achieved by constructors. The return types can also vary as according to the set of parameters provided as input to the factory method which gives great flexibility.<\/li><\/ul>\n\n\n\n
Now let us come to the disadvantages:<\/p>\n\n\n\n
- One of the major disadvantages is that the classes that do not have a public or protected constructor cannot be subclassed further. However, this also propagates the idea of preferring composition over inheritance which is considered a good practice.<\/li>
- Another disadvantage of considering static factory methods is that they are hard to find for the programmer. This can be avoided by using proper naming conventions like
getInstance()<\/code>, valueOf()<\/code> etc.<\/li><\/ul>\n\n\n\nTime for some code probably?<\/p>\n\n\n\n
Consider the Student class given below:<\/p>\n\n\n\n
public class Student {\n private final String name;\n private final String branch;\n private final String yearOfStudy;\n public User(String name, String branch, String yearOfStudy) {\n this.name = name;\n this.branch = branch;\n this.yearOfStudy = yearOfStudy;\n }\n}\n<\/code><\/pre>\n\n\n\nWhen you take a first look there is nothing wrong with the constructor. But when a student takes admission into a university we would want the the yearOfStudy<\/code> to be set as First<\/code>, wouldn\u2019t we? Now this is where the static factory method comes to your rescue.<\/p>\n\n\n\npublic static Student createFreshmanStudent(String name, String branch) {\n return new Student(name, branch, \"First\");\n}\n<\/code><\/pre>\n\n\n\nAnd we can create an object of the Student<\/code> by using the code below,<\/p>\n\n\n\nStudent student = Student.createFreshmanStudent(\u201cJohn Doe\u201d, \u201cComputer Science\u201d);<\/code><\/p>\n\n\n\nThat will be all folks! Until the next time \ud83d\ude42<\/p>\n\n\n\n
Sources:<\/p>\n\n\n\n
- Effective Java by Joshua Bloch<\/li>
- And a Google search obviously!<\/li><\/ul>\n","protected":false},"excerpt":{"rendered":"
What is the most common way to create an object of a class? Yeah, you probably guessed it right! By using a constructor. But is it always the best way? We\u2019ll find out here!<\/p>\n","protected":false},"author":2,"featured_media":109,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0},"categories":[39,40,35],"tags":[11,13,3,12],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/system.camp\/wp-json\/wp\/v2\/posts\/15"}],"collection":[{"href":"https:\/\/system.camp\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/system.camp\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/system.camp\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/system.camp\/wp-json\/wp\/v2\/comments?post=15"}],"version-history":[{"count":3,"href":"https:\/\/system.camp\/wp-json\/wp\/v2\/posts\/15\/revisions"}],"predecessor-version":[{"id":111,"href":"https:\/\/system.camp\/wp-json\/wp\/v2\/posts\/15\/revisions\/111"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/system.camp\/wp-json\/wp\/v2\/media\/109"}],"wp:attachment":[{"href":"https:\/\/system.camp\/wp-json\/wp\/v2\/media?parent=15"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/system.camp\/wp-json\/wp\/v2\/categories?post=15"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/system.camp\/wp-json\/wp\/v2\/tags?post=15"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}