Constructors vs Factory Methods [closed]












151















When modelling classes, what is the preferred way of initializing:




  1. Constructors, or

  2. Factory Methods


And what would be the considerations for using either of them?



In certain situations, I prefer having a factory method which returns null if the object cannot be constructed. This makes the code neat. I can simply check if the returned value is not null before taking alternative action, in contrast with throwing an exception from the constructor. (I personally don't like exceptions)



Say, I have a constructor on a class which expects an id value. The constructor uses this value to populate the class from the database. In the case where a record with the specified id does not exist, the constructor throws a RecordNotFoundException. In this case I will have to enclose the construction of all such classes within a try..catch block.



In contrast to this I can have a static factory method on those classes which will return null if the record is not found.



Which approach is better in this case, constructor or factory method?










share|improve this question















closed as primarily opinion-based by Samuel Liew Nov 30 '18 at 13:11


Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.























    151















    When modelling classes, what is the preferred way of initializing:




    1. Constructors, or

    2. Factory Methods


    And what would be the considerations for using either of them?



    In certain situations, I prefer having a factory method which returns null if the object cannot be constructed. This makes the code neat. I can simply check if the returned value is not null before taking alternative action, in contrast with throwing an exception from the constructor. (I personally don't like exceptions)



    Say, I have a constructor on a class which expects an id value. The constructor uses this value to populate the class from the database. In the case where a record with the specified id does not exist, the constructor throws a RecordNotFoundException. In this case I will have to enclose the construction of all such classes within a try..catch block.



    In contrast to this I can have a static factory method on those classes which will return null if the record is not found.



    Which approach is better in this case, constructor or factory method?










    share|improve this question















    closed as primarily opinion-based by Samuel Liew Nov 30 '18 at 13:11


    Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.





















      151












      151








      151


      60






      When modelling classes, what is the preferred way of initializing:




      1. Constructors, or

      2. Factory Methods


      And what would be the considerations for using either of them?



      In certain situations, I prefer having a factory method which returns null if the object cannot be constructed. This makes the code neat. I can simply check if the returned value is not null before taking alternative action, in contrast with throwing an exception from the constructor. (I personally don't like exceptions)



      Say, I have a constructor on a class which expects an id value. The constructor uses this value to populate the class from the database. In the case where a record with the specified id does not exist, the constructor throws a RecordNotFoundException. In this case I will have to enclose the construction of all such classes within a try..catch block.



      In contrast to this I can have a static factory method on those classes which will return null if the record is not found.



      Which approach is better in this case, constructor or factory method?










      share|improve this question
















      When modelling classes, what is the preferred way of initializing:




      1. Constructors, or

      2. Factory Methods


      And what would be the considerations for using either of them?



      In certain situations, I prefer having a factory method which returns null if the object cannot be constructed. This makes the code neat. I can simply check if the returned value is not null before taking alternative action, in contrast with throwing an exception from the constructor. (I personally don't like exceptions)



      Say, I have a constructor on a class which expects an id value. The constructor uses this value to populate the class from the database. In the case where a record with the specified id does not exist, the constructor throws a RecordNotFoundException. In this case I will have to enclose the construction of all such classes within a try..catch block.



      In contrast to this I can have a static factory method on those classes which will return null if the record is not found.



      Which approach is better in this case, constructor or factory method?







      oop ooad






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 27 '15 at 17:06









      Hannele

      5,67043660




      5,67043660










      asked Mar 10 '09 at 4:38









      Hemanshu BhojakHemanshu Bhojak

      7,949133956




      7,949133956




      closed as primarily opinion-based by Samuel Liew Nov 30 '18 at 13:11


      Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.









      closed as primarily opinion-based by Samuel Liew Nov 30 '18 at 13:11


      Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.


























          10 Answers
          10






          active

          oldest

          votes


















          60














          From page 108 of Design Patterns: Elements of Reusable Object-Oriented Software by Gamma, Helm, Johnson, and Vlissides.



          Use the Factory Method pattern when




          • a class can't anticipate the class of objects it must create

          • a class wants its subclasses to specify the objects it creates

          • classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate






          share|improve this answer





















          • 19





            Static factory method is different from GoF design pattern - Factory Method Pattern. stackoverflow.com/questions/929021/…

            – Sree Rama
            Dec 15 '13 at 11:59











          • Please do not compare with Factory method pattern of GoF design patterns.

            – Sree Rama
            Dec 16 '13 at 5:51






          • 99





            this explains me nothing

            – Sushant
            Apr 23 '14 at 2:26











          • @Sushant, why is it so?

            – PaulD
            Oct 1 '14 at 16:31











          • OP was asking about static factory method.

            – iCrus
            May 22 '16 at 16:22



















          173














          Ask yourself what they are and why do we have them. They both are there to create instance of an object.



          ElementarySchool school = new ElementarySchool();
          ElementarySchool school = SchoolFactory.Construct(); // new ElementarySchool() inside


          No difference so far. Now imagine that we have various school types and we want to switch from using ElementarySchool to HighSchool (which is derived from an ElementarySchool or implements the same interface ISchool as the ElementarySchool). The code change would be:



          HighSchool school = new HighSchool();
          HighSchool school = SchoolFactory.Construct(); // new HighSchool() inside


          In case of an interface we would have:



          ISchool school = new HighSchool();
          ISchool school = SchoolFactory.Construct(); // new HighSchool() inside


          Now if you have this code in multiple places you can see that using factory method might be pretty cheap because once you change the factory method you are done (if we use the second example with interfaces).



          And this is the main difference and advantage. When you start dealing with a complex class hierarchies and you want to dynamically create an instance of a class from such a hierarchy you get the following code. Factory methods might then take a parameter that tells the method what concrete instance to instantiate. Let's say you have a MyStudent class and you need to instantiate corresponding ISchool object so that your student is a member of that school.



          ISchool school = SchoolFactory.ConstructForStudent(myStudent);


          Now you have one place in your app that contains business logic that determines what ISchool object to instantiate for different IStudent objects.



          So - for simple classes (value objects, etc.) constructor is just fine (you don't want to overengineer your application) but for complex class hierarchies factory method is a preferred way.



          This way you follow the first design principle from the gang of four book "Program to an interface, not an implementation".






          share|improve this answer





















          • 1





            Even when you think it's a simple class, there is a chance someone needs to extend your simple class, so factory method is still better. E.g. you may start with ElementarySchool but later someone (including yourself) may extend it with PrivateElementarySchool and PublicElementarySchool.

            – jack
            Aug 8 '16 at 14:21








          • 9





            this should be the accepted answer

            – am05mhz
            Sep 8 '16 at 2:41






          • 1





            @David, good answer, but can you expand on an example where each interface implementation may require different parameters for construction. Here's a silly example: IFood sandwich = new Sandwich(Cheese chz, Meat meat); and IFood soup = new Soup(Broth broth, Vegetable veg); How can factory and or builder help here?

            – Brian Vanover
            Nov 9 '16 at 19:48








          • 1





            I just read three other explanations on the purpose of factory usage, and this is the one that finally had it "click" for me. Thank you!

            – Daniel Peirano
            Feb 25 '17 at 23:05











          • Why this is not accepted answer?

            – Tomas
            Dec 4 '18 at 19:05



















          63














          You need to read (if you have access to) Effective Java 2 Item 1: Consider static factory methods instead of constructors.



          Static factory methods advantages:




          1. They have names.

          2. They are not required to create a new object each time they are invoked.

          3. They can return an object of any subtype of their return type.

          4. They reduce verbosity of creating parameterized type instances.


          Static factory methods disadvantages:




          1. When providing only static factory methods, classes without public or protected constructors cannot be subclassed.

          2. They are not readily distinguishable from other static methods






          share|improve this answer



















          • 4





            This seems to me rather a severe bug in Java, then a general OOD problem. There are numerous OO languages that don't even have constructors, yet subclassing works just fine.

            – Jörg W Mittag
            Mar 10 '09 at 16:12






          • 1





            @cherouvim why mostly code is written using Constructors if ( factory methods are better than Constructors. ( Item-1 ) ) Effective java

            – Asif Mushtaq
            May 26 '16 at 18:40











          • Good points. It's Java specific though. A case can be made for a language feature that makes factory methods distinguishable from other static methods.

            – OCDev
            Aug 6 '16 at 13:02



















          23














          By default, constructors should be preferred, because they are simpler to understand and write. However, if you specifically need to decouple the construction niceties of an object from its semantic meaning as understood by the client code, you'd be better off using factories.



          The difference between constructors and factories is analogous to, say, a variable and a pointer to a variable. There's another level of indirection, which is a disadvantage; but there's another level of flexibility too, which is an advantage. So while making a choice, you'd be well advised to do this cost versus benefit analysis.






          share|improve this answer



















          • 14





            So, (TDD style) you would start with constructors as the simplest way of getting the job done. And then refactor to factories once you start getting code smells (like repeated conditional logic determining which constructor to call)?

            – AndyM
            Mar 11 '10 at 17:02













          • Absolutely @ AndyM

            – Frederick The Fool
            Feb 1 '13 at 9:34



















          11














          A cite from "Effective Java", 2nd ed., Item 1: Consider static factory methods instead of constructors, p. 5:



          "Note that a static factory method is not the same as the Factory Method pattern
          from Design Patterns
          [Gamma95, p. 107]. The static factory method described in
          this item has no direct equivalent in Design Patterns."






          share|improve this answer































            11














            Use a factory only when you need extra control with object creation, in a way that couldn't be done with constructors.



            Factories have the possibility of caching for example.



            Another way to use factories is in a scenario where you do not know the type you want to construct. Often you see this type of usage in plugin factory scenarios, where each plugin must derive from a baseclass or implement some kind of interface. The factory creates instances of classes that derive from the baseclass or that implement the interface.






            share|improve this answer

































              7














              A concrete example from a CAD/CAM application.



              A cutting path would be made by using a constructor. It is a series of lines and arcs defining a path to cut. While the series of lines and arcs can be different and have different coordinates it easily handled by passing a list into a constructor.



              A shape would be would be made by using a factory. Because while there is a shape class each shape would be setup differently depending on what type of shape it is. We don't know what shape we are going to be initializing until the user makes a selection.






              share|improve this answer































                3















                Say, I have a constructor on a class which expects an id value. The constructor uses this value to populate the class from the database.




                This process should definitely be outside a constructor.




                1. Constructor should not access database.


                2. The task and the reason for a constructor is to initialize data members and to establish class invariant using values passed into constructor.


                3. For everything else a better approach is to use static factory method or in more complex cases a separate factory or builder class.



                Some constructor guide lines from Microsoft:




                Do minimal work in the constructor. Constructors should not do much work other than to capture the constructor parameters. The cost of any other processing should be delayed until required.




                And




                Consider using a static factory method instead of a constructor if the semantics of the desired operation do not map directly to the construction of a new instance.







                share|improve this answer































                  3














                  In addition to "effective java" (as mentioned in another answer), another classic book also suggests:




                  Prefer static factory methods (with names that describe the arguments) to overloaded constructors.




                  Eg. don't write



                  Complex complex = new Complex(23.0);


                  but instead write



                  Complex complex = Complex.fromRealNumber(23.0);


                  The book goes as far as to suggest making the Complex(float) constructor private, to force the user to call the static factory method.






                  share|improve this answer





















                  • 1





                    Reading that part of the book brought me here

                    – Purple Haze
                    Nov 23 '18 at 16:43











                  • @Bayrem: me too, I was re-reading it recently and thought I should add it to the answers.

                    – blue_note
                    Nov 23 '18 at 16:47



















                  0














                  Sometimes you have to check/calculate some values/conditions while creating an object. And if it can throw an Exception - constructro is very bad way. So you need to do something like this:



                  var value = new Instance(1, 2).init()
                  public function init() {
                  try {
                  doSome()
                  }
                  catch (e) {
                  soAnotherSome()
                  }
                  }


                  Where all additional calculations are in init(). But only you as developer realy know about this init(). And of course, after months you just forget about it.
                  But if you have a factory - just do all you need in one method with hiding this init() from direct call - so no problems. With this approach is no problems with falling on creation and memory leaking.



                  Someone told you about caching. It's good. But you also have to remember about Flyweight pattern which is nice to use with Factory way.






                  share|improve this answer






























                    10 Answers
                    10






                    active

                    oldest

                    votes








                    10 Answers
                    10






                    active

                    oldest

                    votes









                    active

                    oldest

                    votes






                    active

                    oldest

                    votes









                    60














                    From page 108 of Design Patterns: Elements of Reusable Object-Oriented Software by Gamma, Helm, Johnson, and Vlissides.



                    Use the Factory Method pattern when




                    • a class can't anticipate the class of objects it must create

                    • a class wants its subclasses to specify the objects it creates

                    • classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate






                    share|improve this answer





















                    • 19





                      Static factory method is different from GoF design pattern - Factory Method Pattern. stackoverflow.com/questions/929021/…

                      – Sree Rama
                      Dec 15 '13 at 11:59











                    • Please do not compare with Factory method pattern of GoF design patterns.

                      – Sree Rama
                      Dec 16 '13 at 5:51






                    • 99





                      this explains me nothing

                      – Sushant
                      Apr 23 '14 at 2:26











                    • @Sushant, why is it so?

                      – PaulD
                      Oct 1 '14 at 16:31











                    • OP was asking about static factory method.

                      – iCrus
                      May 22 '16 at 16:22
















                    60














                    From page 108 of Design Patterns: Elements of Reusable Object-Oriented Software by Gamma, Helm, Johnson, and Vlissides.



                    Use the Factory Method pattern when




                    • a class can't anticipate the class of objects it must create

                    • a class wants its subclasses to specify the objects it creates

                    • classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate






                    share|improve this answer





















                    • 19





                      Static factory method is different from GoF design pattern - Factory Method Pattern. stackoverflow.com/questions/929021/…

                      – Sree Rama
                      Dec 15 '13 at 11:59











                    • Please do not compare with Factory method pattern of GoF design patterns.

                      – Sree Rama
                      Dec 16 '13 at 5:51






                    • 99





                      this explains me nothing

                      – Sushant
                      Apr 23 '14 at 2:26











                    • @Sushant, why is it so?

                      – PaulD
                      Oct 1 '14 at 16:31











                    • OP was asking about static factory method.

                      – iCrus
                      May 22 '16 at 16:22














                    60












                    60








                    60







                    From page 108 of Design Patterns: Elements of Reusable Object-Oriented Software by Gamma, Helm, Johnson, and Vlissides.



                    Use the Factory Method pattern when




                    • a class can't anticipate the class of objects it must create

                    • a class wants its subclasses to specify the objects it creates

                    • classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate






                    share|improve this answer















                    From page 108 of Design Patterns: Elements of Reusable Object-Oriented Software by Gamma, Helm, Johnson, and Vlissides.



                    Use the Factory Method pattern when




                    • a class can't anticipate the class of objects it must create

                    • a class wants its subclasses to specify the objects it creates

                    • classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Apr 27 '12 at 12:36









                    reevesy

                    3,14612121




                    3,14612121










                    answered Mar 10 '09 at 4:43









                    GlennGlenn

                    6,33332436




                    6,33332436








                    • 19





                      Static factory method is different from GoF design pattern - Factory Method Pattern. stackoverflow.com/questions/929021/…

                      – Sree Rama
                      Dec 15 '13 at 11:59











                    • Please do not compare with Factory method pattern of GoF design patterns.

                      – Sree Rama
                      Dec 16 '13 at 5:51






                    • 99





                      this explains me nothing

                      – Sushant
                      Apr 23 '14 at 2:26











                    • @Sushant, why is it so?

                      – PaulD
                      Oct 1 '14 at 16:31











                    • OP was asking about static factory method.

                      – iCrus
                      May 22 '16 at 16:22














                    • 19





                      Static factory method is different from GoF design pattern - Factory Method Pattern. stackoverflow.com/questions/929021/…

                      – Sree Rama
                      Dec 15 '13 at 11:59











                    • Please do not compare with Factory method pattern of GoF design patterns.

                      – Sree Rama
                      Dec 16 '13 at 5:51






                    • 99





                      this explains me nothing

                      – Sushant
                      Apr 23 '14 at 2:26











                    • @Sushant, why is it so?

                      – PaulD
                      Oct 1 '14 at 16:31











                    • OP was asking about static factory method.

                      – iCrus
                      May 22 '16 at 16:22








                    19




                    19





                    Static factory method is different from GoF design pattern - Factory Method Pattern. stackoverflow.com/questions/929021/…

                    – Sree Rama
                    Dec 15 '13 at 11:59





                    Static factory method is different from GoF design pattern - Factory Method Pattern. stackoverflow.com/questions/929021/…

                    – Sree Rama
                    Dec 15 '13 at 11:59













                    Please do not compare with Factory method pattern of GoF design patterns.

                    – Sree Rama
                    Dec 16 '13 at 5:51





                    Please do not compare with Factory method pattern of GoF design patterns.

                    – Sree Rama
                    Dec 16 '13 at 5:51




                    99




                    99





                    this explains me nothing

                    – Sushant
                    Apr 23 '14 at 2:26





                    this explains me nothing

                    – Sushant
                    Apr 23 '14 at 2:26













                    @Sushant, why is it so?

                    – PaulD
                    Oct 1 '14 at 16:31





                    @Sushant, why is it so?

                    – PaulD
                    Oct 1 '14 at 16:31













                    OP was asking about static factory method.

                    – iCrus
                    May 22 '16 at 16:22





                    OP was asking about static factory method.

                    – iCrus
                    May 22 '16 at 16:22













                    173














                    Ask yourself what they are and why do we have them. They both are there to create instance of an object.



                    ElementarySchool school = new ElementarySchool();
                    ElementarySchool school = SchoolFactory.Construct(); // new ElementarySchool() inside


                    No difference so far. Now imagine that we have various school types and we want to switch from using ElementarySchool to HighSchool (which is derived from an ElementarySchool or implements the same interface ISchool as the ElementarySchool). The code change would be:



                    HighSchool school = new HighSchool();
                    HighSchool school = SchoolFactory.Construct(); // new HighSchool() inside


                    In case of an interface we would have:



                    ISchool school = new HighSchool();
                    ISchool school = SchoolFactory.Construct(); // new HighSchool() inside


                    Now if you have this code in multiple places you can see that using factory method might be pretty cheap because once you change the factory method you are done (if we use the second example with interfaces).



                    And this is the main difference and advantage. When you start dealing with a complex class hierarchies and you want to dynamically create an instance of a class from such a hierarchy you get the following code. Factory methods might then take a parameter that tells the method what concrete instance to instantiate. Let's say you have a MyStudent class and you need to instantiate corresponding ISchool object so that your student is a member of that school.



                    ISchool school = SchoolFactory.ConstructForStudent(myStudent);


                    Now you have one place in your app that contains business logic that determines what ISchool object to instantiate for different IStudent objects.



                    So - for simple classes (value objects, etc.) constructor is just fine (you don't want to overengineer your application) but for complex class hierarchies factory method is a preferred way.



                    This way you follow the first design principle from the gang of four book "Program to an interface, not an implementation".






                    share|improve this answer





















                    • 1





                      Even when you think it's a simple class, there is a chance someone needs to extend your simple class, so factory method is still better. E.g. you may start with ElementarySchool but later someone (including yourself) may extend it with PrivateElementarySchool and PublicElementarySchool.

                      – jack
                      Aug 8 '16 at 14:21








                    • 9





                      this should be the accepted answer

                      – am05mhz
                      Sep 8 '16 at 2:41






                    • 1





                      @David, good answer, but can you expand on an example where each interface implementation may require different parameters for construction. Here's a silly example: IFood sandwich = new Sandwich(Cheese chz, Meat meat); and IFood soup = new Soup(Broth broth, Vegetable veg); How can factory and or builder help here?

                      – Brian Vanover
                      Nov 9 '16 at 19:48








                    • 1





                      I just read three other explanations on the purpose of factory usage, and this is the one that finally had it "click" for me. Thank you!

                      – Daniel Peirano
                      Feb 25 '17 at 23:05











                    • Why this is not accepted answer?

                      – Tomas
                      Dec 4 '18 at 19:05
















                    173














                    Ask yourself what they are and why do we have them. They both are there to create instance of an object.



                    ElementarySchool school = new ElementarySchool();
                    ElementarySchool school = SchoolFactory.Construct(); // new ElementarySchool() inside


                    No difference so far. Now imagine that we have various school types and we want to switch from using ElementarySchool to HighSchool (which is derived from an ElementarySchool or implements the same interface ISchool as the ElementarySchool). The code change would be:



                    HighSchool school = new HighSchool();
                    HighSchool school = SchoolFactory.Construct(); // new HighSchool() inside


                    In case of an interface we would have:



                    ISchool school = new HighSchool();
                    ISchool school = SchoolFactory.Construct(); // new HighSchool() inside


                    Now if you have this code in multiple places you can see that using factory method might be pretty cheap because once you change the factory method you are done (if we use the second example with interfaces).



                    And this is the main difference and advantage. When you start dealing with a complex class hierarchies and you want to dynamically create an instance of a class from such a hierarchy you get the following code. Factory methods might then take a parameter that tells the method what concrete instance to instantiate. Let's say you have a MyStudent class and you need to instantiate corresponding ISchool object so that your student is a member of that school.



                    ISchool school = SchoolFactory.ConstructForStudent(myStudent);


                    Now you have one place in your app that contains business logic that determines what ISchool object to instantiate for different IStudent objects.



                    So - for simple classes (value objects, etc.) constructor is just fine (you don't want to overengineer your application) but for complex class hierarchies factory method is a preferred way.



                    This way you follow the first design principle from the gang of four book "Program to an interface, not an implementation".






                    share|improve this answer





















                    • 1





                      Even when you think it's a simple class, there is a chance someone needs to extend your simple class, so factory method is still better. E.g. you may start with ElementarySchool but later someone (including yourself) may extend it with PrivateElementarySchool and PublicElementarySchool.

                      – jack
                      Aug 8 '16 at 14:21








                    • 9





                      this should be the accepted answer

                      – am05mhz
                      Sep 8 '16 at 2:41






                    • 1





                      @David, good answer, but can you expand on an example where each interface implementation may require different parameters for construction. Here's a silly example: IFood sandwich = new Sandwich(Cheese chz, Meat meat); and IFood soup = new Soup(Broth broth, Vegetable veg); How can factory and or builder help here?

                      – Brian Vanover
                      Nov 9 '16 at 19:48








                    • 1





                      I just read three other explanations on the purpose of factory usage, and this is the one that finally had it "click" for me. Thank you!

                      – Daniel Peirano
                      Feb 25 '17 at 23:05











                    • Why this is not accepted answer?

                      – Tomas
                      Dec 4 '18 at 19:05














                    173












                    173








                    173







                    Ask yourself what they are and why do we have them. They both are there to create instance of an object.



                    ElementarySchool school = new ElementarySchool();
                    ElementarySchool school = SchoolFactory.Construct(); // new ElementarySchool() inside


                    No difference so far. Now imagine that we have various school types and we want to switch from using ElementarySchool to HighSchool (which is derived from an ElementarySchool or implements the same interface ISchool as the ElementarySchool). The code change would be:



                    HighSchool school = new HighSchool();
                    HighSchool school = SchoolFactory.Construct(); // new HighSchool() inside


                    In case of an interface we would have:



                    ISchool school = new HighSchool();
                    ISchool school = SchoolFactory.Construct(); // new HighSchool() inside


                    Now if you have this code in multiple places you can see that using factory method might be pretty cheap because once you change the factory method you are done (if we use the second example with interfaces).



                    And this is the main difference and advantage. When you start dealing with a complex class hierarchies and you want to dynamically create an instance of a class from such a hierarchy you get the following code. Factory methods might then take a parameter that tells the method what concrete instance to instantiate. Let's say you have a MyStudent class and you need to instantiate corresponding ISchool object so that your student is a member of that school.



                    ISchool school = SchoolFactory.ConstructForStudent(myStudent);


                    Now you have one place in your app that contains business logic that determines what ISchool object to instantiate for different IStudent objects.



                    So - for simple classes (value objects, etc.) constructor is just fine (you don't want to overengineer your application) but for complex class hierarchies factory method is a preferred way.



                    This way you follow the first design principle from the gang of four book "Program to an interface, not an implementation".






                    share|improve this answer















                    Ask yourself what they are and why do we have them. They both are there to create instance of an object.



                    ElementarySchool school = new ElementarySchool();
                    ElementarySchool school = SchoolFactory.Construct(); // new ElementarySchool() inside


                    No difference so far. Now imagine that we have various school types and we want to switch from using ElementarySchool to HighSchool (which is derived from an ElementarySchool or implements the same interface ISchool as the ElementarySchool). The code change would be:



                    HighSchool school = new HighSchool();
                    HighSchool school = SchoolFactory.Construct(); // new HighSchool() inside


                    In case of an interface we would have:



                    ISchool school = new HighSchool();
                    ISchool school = SchoolFactory.Construct(); // new HighSchool() inside


                    Now if you have this code in multiple places you can see that using factory method might be pretty cheap because once you change the factory method you are done (if we use the second example with interfaces).



                    And this is the main difference and advantage. When you start dealing with a complex class hierarchies and you want to dynamically create an instance of a class from such a hierarchy you get the following code. Factory methods might then take a parameter that tells the method what concrete instance to instantiate. Let's say you have a MyStudent class and you need to instantiate corresponding ISchool object so that your student is a member of that school.



                    ISchool school = SchoolFactory.ConstructForStudent(myStudent);


                    Now you have one place in your app that contains business logic that determines what ISchool object to instantiate for different IStudent objects.



                    So - for simple classes (value objects, etc.) constructor is just fine (you don't want to overengineer your application) but for complex class hierarchies factory method is a preferred way.



                    This way you follow the first design principle from the gang of four book "Program to an interface, not an implementation".







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Mar 10 '09 at 5:27

























                    answered Mar 10 '09 at 5:18









                    David PokludaDavid Pokluda

                    8,54252226




                    8,54252226








                    • 1





                      Even when you think it's a simple class, there is a chance someone needs to extend your simple class, so factory method is still better. E.g. you may start with ElementarySchool but later someone (including yourself) may extend it with PrivateElementarySchool and PublicElementarySchool.

                      – jack
                      Aug 8 '16 at 14:21








                    • 9





                      this should be the accepted answer

                      – am05mhz
                      Sep 8 '16 at 2:41






                    • 1





                      @David, good answer, but can you expand on an example where each interface implementation may require different parameters for construction. Here's a silly example: IFood sandwich = new Sandwich(Cheese chz, Meat meat); and IFood soup = new Soup(Broth broth, Vegetable veg); How can factory and or builder help here?

                      – Brian Vanover
                      Nov 9 '16 at 19:48








                    • 1





                      I just read three other explanations on the purpose of factory usage, and this is the one that finally had it "click" for me. Thank you!

                      – Daniel Peirano
                      Feb 25 '17 at 23:05











                    • Why this is not accepted answer?

                      – Tomas
                      Dec 4 '18 at 19:05














                    • 1





                      Even when you think it's a simple class, there is a chance someone needs to extend your simple class, so factory method is still better. E.g. you may start with ElementarySchool but later someone (including yourself) may extend it with PrivateElementarySchool and PublicElementarySchool.

                      – jack
                      Aug 8 '16 at 14:21








                    • 9





                      this should be the accepted answer

                      – am05mhz
                      Sep 8 '16 at 2:41






                    • 1





                      @David, good answer, but can you expand on an example where each interface implementation may require different parameters for construction. Here's a silly example: IFood sandwich = new Sandwich(Cheese chz, Meat meat); and IFood soup = new Soup(Broth broth, Vegetable veg); How can factory and or builder help here?

                      – Brian Vanover
                      Nov 9 '16 at 19:48








                    • 1





                      I just read three other explanations on the purpose of factory usage, and this is the one that finally had it "click" for me. Thank you!

                      – Daniel Peirano
                      Feb 25 '17 at 23:05











                    • Why this is not accepted answer?

                      – Tomas
                      Dec 4 '18 at 19:05








                    1




                    1





                    Even when you think it's a simple class, there is a chance someone needs to extend your simple class, so factory method is still better. E.g. you may start with ElementarySchool but later someone (including yourself) may extend it with PrivateElementarySchool and PublicElementarySchool.

                    – jack
                    Aug 8 '16 at 14:21







                    Even when you think it's a simple class, there is a chance someone needs to extend your simple class, so factory method is still better. E.g. you may start with ElementarySchool but later someone (including yourself) may extend it with PrivateElementarySchool and PublicElementarySchool.

                    – jack
                    Aug 8 '16 at 14:21






                    9




                    9





                    this should be the accepted answer

                    – am05mhz
                    Sep 8 '16 at 2:41





                    this should be the accepted answer

                    – am05mhz
                    Sep 8 '16 at 2:41




                    1




                    1





                    @David, good answer, but can you expand on an example where each interface implementation may require different parameters for construction. Here's a silly example: IFood sandwich = new Sandwich(Cheese chz, Meat meat); and IFood soup = new Soup(Broth broth, Vegetable veg); How can factory and or builder help here?

                    – Brian Vanover
                    Nov 9 '16 at 19:48







                    @David, good answer, but can you expand on an example where each interface implementation may require different parameters for construction. Here's a silly example: IFood sandwich = new Sandwich(Cheese chz, Meat meat); and IFood soup = new Soup(Broth broth, Vegetable veg); How can factory and or builder help here?

                    – Brian Vanover
                    Nov 9 '16 at 19:48






                    1




                    1





                    I just read three other explanations on the purpose of factory usage, and this is the one that finally had it "click" for me. Thank you!

                    – Daniel Peirano
                    Feb 25 '17 at 23:05





                    I just read three other explanations on the purpose of factory usage, and this is the one that finally had it "click" for me. Thank you!

                    – Daniel Peirano
                    Feb 25 '17 at 23:05













                    Why this is not accepted answer?

                    – Tomas
                    Dec 4 '18 at 19:05





                    Why this is not accepted answer?

                    – Tomas
                    Dec 4 '18 at 19:05











                    63














                    You need to read (if you have access to) Effective Java 2 Item 1: Consider static factory methods instead of constructors.



                    Static factory methods advantages:




                    1. They have names.

                    2. They are not required to create a new object each time they are invoked.

                    3. They can return an object of any subtype of their return type.

                    4. They reduce verbosity of creating parameterized type instances.


                    Static factory methods disadvantages:




                    1. When providing only static factory methods, classes without public or protected constructors cannot be subclassed.

                    2. They are not readily distinguishable from other static methods






                    share|improve this answer



















                    • 4





                      This seems to me rather a severe bug in Java, then a general OOD problem. There are numerous OO languages that don't even have constructors, yet subclassing works just fine.

                      – Jörg W Mittag
                      Mar 10 '09 at 16:12






                    • 1





                      @cherouvim why mostly code is written using Constructors if ( factory methods are better than Constructors. ( Item-1 ) ) Effective java

                      – Asif Mushtaq
                      May 26 '16 at 18:40











                    • Good points. It's Java specific though. A case can be made for a language feature that makes factory methods distinguishable from other static methods.

                      – OCDev
                      Aug 6 '16 at 13:02
















                    63














                    You need to read (if you have access to) Effective Java 2 Item 1: Consider static factory methods instead of constructors.



                    Static factory methods advantages:




                    1. They have names.

                    2. They are not required to create a new object each time they are invoked.

                    3. They can return an object of any subtype of their return type.

                    4. They reduce verbosity of creating parameterized type instances.


                    Static factory methods disadvantages:




                    1. When providing only static factory methods, classes without public or protected constructors cannot be subclassed.

                    2. They are not readily distinguishable from other static methods






                    share|improve this answer



















                    • 4





                      This seems to me rather a severe bug in Java, then a general OOD problem. There are numerous OO languages that don't even have constructors, yet subclassing works just fine.

                      – Jörg W Mittag
                      Mar 10 '09 at 16:12






                    • 1





                      @cherouvim why mostly code is written using Constructors if ( factory methods are better than Constructors. ( Item-1 ) ) Effective java

                      – Asif Mushtaq
                      May 26 '16 at 18:40











                    • Good points. It's Java specific though. A case can be made for a language feature that makes factory methods distinguishable from other static methods.

                      – OCDev
                      Aug 6 '16 at 13:02














                    63












                    63








                    63







                    You need to read (if you have access to) Effective Java 2 Item 1: Consider static factory methods instead of constructors.



                    Static factory methods advantages:




                    1. They have names.

                    2. They are not required to create a new object each time they are invoked.

                    3. They can return an object of any subtype of their return type.

                    4. They reduce verbosity of creating parameterized type instances.


                    Static factory methods disadvantages:




                    1. When providing only static factory methods, classes without public or protected constructors cannot be subclassed.

                    2. They are not readily distinguishable from other static methods






                    share|improve this answer













                    You need to read (if you have access to) Effective Java 2 Item 1: Consider static factory methods instead of constructors.



                    Static factory methods advantages:




                    1. They have names.

                    2. They are not required to create a new object each time they are invoked.

                    3. They can return an object of any subtype of their return type.

                    4. They reduce verbosity of creating parameterized type instances.


                    Static factory methods disadvantages:




                    1. When providing only static factory methods, classes without public or protected constructors cannot be subclassed.

                    2. They are not readily distinguishable from other static methods







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 10 '09 at 7:26









                    cherouvimcherouvim

                    26.4k1292136




                    26.4k1292136








                    • 4





                      This seems to me rather a severe bug in Java, then a general OOD problem. There are numerous OO languages that don't even have constructors, yet subclassing works just fine.

                      – Jörg W Mittag
                      Mar 10 '09 at 16:12






                    • 1





                      @cherouvim why mostly code is written using Constructors if ( factory methods are better than Constructors. ( Item-1 ) ) Effective java

                      – Asif Mushtaq
                      May 26 '16 at 18:40











                    • Good points. It's Java specific though. A case can be made for a language feature that makes factory methods distinguishable from other static methods.

                      – OCDev
                      Aug 6 '16 at 13:02














                    • 4





                      This seems to me rather a severe bug in Java, then a general OOD problem. There are numerous OO languages that don't even have constructors, yet subclassing works just fine.

                      – Jörg W Mittag
                      Mar 10 '09 at 16:12






                    • 1





                      @cherouvim why mostly code is written using Constructors if ( factory methods are better than Constructors. ( Item-1 ) ) Effective java

                      – Asif Mushtaq
                      May 26 '16 at 18:40











                    • Good points. It's Java specific though. A case can be made for a language feature that makes factory methods distinguishable from other static methods.

                      – OCDev
                      Aug 6 '16 at 13:02








                    4




                    4





                    This seems to me rather a severe bug in Java, then a general OOD problem. There are numerous OO languages that don't even have constructors, yet subclassing works just fine.

                    – Jörg W Mittag
                    Mar 10 '09 at 16:12





                    This seems to me rather a severe bug in Java, then a general OOD problem. There are numerous OO languages that don't even have constructors, yet subclassing works just fine.

                    – Jörg W Mittag
                    Mar 10 '09 at 16:12




                    1




                    1





                    @cherouvim why mostly code is written using Constructors if ( factory methods are better than Constructors. ( Item-1 ) ) Effective java

                    – Asif Mushtaq
                    May 26 '16 at 18:40





                    @cherouvim why mostly code is written using Constructors if ( factory methods are better than Constructors. ( Item-1 ) ) Effective java

                    – Asif Mushtaq
                    May 26 '16 at 18:40













                    Good points. It's Java specific though. A case can be made for a language feature that makes factory methods distinguishable from other static methods.

                    – OCDev
                    Aug 6 '16 at 13:02





                    Good points. It's Java specific though. A case can be made for a language feature that makes factory methods distinguishable from other static methods.

                    – OCDev
                    Aug 6 '16 at 13:02











                    23














                    By default, constructors should be preferred, because they are simpler to understand and write. However, if you specifically need to decouple the construction niceties of an object from its semantic meaning as understood by the client code, you'd be better off using factories.



                    The difference between constructors and factories is analogous to, say, a variable and a pointer to a variable. There's another level of indirection, which is a disadvantage; but there's another level of flexibility too, which is an advantage. So while making a choice, you'd be well advised to do this cost versus benefit analysis.






                    share|improve this answer



















                    • 14





                      So, (TDD style) you would start with constructors as the simplest way of getting the job done. And then refactor to factories once you start getting code smells (like repeated conditional logic determining which constructor to call)?

                      – AndyM
                      Mar 11 '10 at 17:02













                    • Absolutely @ AndyM

                      – Frederick The Fool
                      Feb 1 '13 at 9:34
















                    23














                    By default, constructors should be preferred, because they are simpler to understand and write. However, if you specifically need to decouple the construction niceties of an object from its semantic meaning as understood by the client code, you'd be better off using factories.



                    The difference between constructors and factories is analogous to, say, a variable and a pointer to a variable. There's another level of indirection, which is a disadvantage; but there's another level of flexibility too, which is an advantage. So while making a choice, you'd be well advised to do this cost versus benefit analysis.






                    share|improve this answer



















                    • 14





                      So, (TDD style) you would start with constructors as the simplest way of getting the job done. And then refactor to factories once you start getting code smells (like repeated conditional logic determining which constructor to call)?

                      – AndyM
                      Mar 11 '10 at 17:02













                    • Absolutely @ AndyM

                      – Frederick The Fool
                      Feb 1 '13 at 9:34














                    23












                    23








                    23







                    By default, constructors should be preferred, because they are simpler to understand and write. However, if you specifically need to decouple the construction niceties of an object from its semantic meaning as understood by the client code, you'd be better off using factories.



                    The difference between constructors and factories is analogous to, say, a variable and a pointer to a variable. There's another level of indirection, which is a disadvantage; but there's another level of flexibility too, which is an advantage. So while making a choice, you'd be well advised to do this cost versus benefit analysis.






                    share|improve this answer













                    By default, constructors should be preferred, because they are simpler to understand and write. However, if you specifically need to decouple the construction niceties of an object from its semantic meaning as understood by the client code, you'd be better off using factories.



                    The difference between constructors and factories is analogous to, say, a variable and a pointer to a variable. There's another level of indirection, which is a disadvantage; but there's another level of flexibility too, which is an advantage. So while making a choice, you'd be well advised to do this cost versus benefit analysis.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 10 '09 at 4:41









                    Frederick The FoolFrederick The Fool

                    18.4k1867104




                    18.4k1867104








                    • 14





                      So, (TDD style) you would start with constructors as the simplest way of getting the job done. And then refactor to factories once you start getting code smells (like repeated conditional logic determining which constructor to call)?

                      – AndyM
                      Mar 11 '10 at 17:02













                    • Absolutely @ AndyM

                      – Frederick The Fool
                      Feb 1 '13 at 9:34














                    • 14





                      So, (TDD style) you would start with constructors as the simplest way of getting the job done. And then refactor to factories once you start getting code smells (like repeated conditional logic determining which constructor to call)?

                      – AndyM
                      Mar 11 '10 at 17:02













                    • Absolutely @ AndyM

                      – Frederick The Fool
                      Feb 1 '13 at 9:34








                    14




                    14





                    So, (TDD style) you would start with constructors as the simplest way of getting the job done. And then refactor to factories once you start getting code smells (like repeated conditional logic determining which constructor to call)?

                    – AndyM
                    Mar 11 '10 at 17:02







                    So, (TDD style) you would start with constructors as the simplest way of getting the job done. And then refactor to factories once you start getting code smells (like repeated conditional logic determining which constructor to call)?

                    – AndyM
                    Mar 11 '10 at 17:02















                    Absolutely @ AndyM

                    – Frederick The Fool
                    Feb 1 '13 at 9:34





                    Absolutely @ AndyM

                    – Frederick The Fool
                    Feb 1 '13 at 9:34











                    11














                    A cite from "Effective Java", 2nd ed., Item 1: Consider static factory methods instead of constructors, p. 5:



                    "Note that a static factory method is not the same as the Factory Method pattern
                    from Design Patterns
                    [Gamma95, p. 107]. The static factory method described in
                    this item has no direct equivalent in Design Patterns."






                    share|improve this answer




























                      11














                      A cite from "Effective Java", 2nd ed., Item 1: Consider static factory methods instead of constructors, p. 5:



                      "Note that a static factory method is not the same as the Factory Method pattern
                      from Design Patterns
                      [Gamma95, p. 107]. The static factory method described in
                      this item has no direct equivalent in Design Patterns."






                      share|improve this answer


























                        11












                        11








                        11







                        A cite from "Effective Java", 2nd ed., Item 1: Consider static factory methods instead of constructors, p. 5:



                        "Note that a static factory method is not the same as the Factory Method pattern
                        from Design Patterns
                        [Gamma95, p. 107]. The static factory method described in
                        this item has no direct equivalent in Design Patterns."






                        share|improve this answer













                        A cite from "Effective Java", 2nd ed., Item 1: Consider static factory methods instead of constructors, p. 5:



                        "Note that a static factory method is not the same as the Factory Method pattern
                        from Design Patterns
                        [Gamma95, p. 107]. The static factory method described in
                        this item has no direct equivalent in Design Patterns."







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Nov 27 '10 at 22:50









                        Eugen LabunEugen Labun

                        1,44311311




                        1,44311311























                            11














                            Use a factory only when you need extra control with object creation, in a way that couldn't be done with constructors.



                            Factories have the possibility of caching for example.



                            Another way to use factories is in a scenario where you do not know the type you want to construct. Often you see this type of usage in plugin factory scenarios, where each plugin must derive from a baseclass or implement some kind of interface. The factory creates instances of classes that derive from the baseclass or that implement the interface.






                            share|improve this answer






























                              11














                              Use a factory only when you need extra control with object creation, in a way that couldn't be done with constructors.



                              Factories have the possibility of caching for example.



                              Another way to use factories is in a scenario where you do not know the type you want to construct. Often you see this type of usage in plugin factory scenarios, where each plugin must derive from a baseclass or implement some kind of interface. The factory creates instances of classes that derive from the baseclass or that implement the interface.






                              share|improve this answer




























                                11












                                11








                                11







                                Use a factory only when you need extra control with object creation, in a way that couldn't be done with constructors.



                                Factories have the possibility of caching for example.



                                Another way to use factories is in a scenario where you do not know the type you want to construct. Often you see this type of usage in plugin factory scenarios, where each plugin must derive from a baseclass or implement some kind of interface. The factory creates instances of classes that derive from the baseclass or that implement the interface.






                                share|improve this answer















                                Use a factory only when you need extra control with object creation, in a way that couldn't be done with constructors.



                                Factories have the possibility of caching for example.



                                Another way to use factories is in a scenario where you do not know the type you want to construct. Often you see this type of usage in plugin factory scenarios, where each plugin must derive from a baseclass or implement some kind of interface. The factory creates instances of classes that derive from the baseclass or that implement the interface.







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Nov 27 '15 at 17:08









                                Hannele

                                5,67043660




                                5,67043660










                                answered Mar 10 '09 at 7:12









                                Patrick PetersPatrick Peters

                                4,69264789




                                4,69264789























                                    7














                                    A concrete example from a CAD/CAM application.



                                    A cutting path would be made by using a constructor. It is a series of lines and arcs defining a path to cut. While the series of lines and arcs can be different and have different coordinates it easily handled by passing a list into a constructor.



                                    A shape would be would be made by using a factory. Because while there is a shape class each shape would be setup differently depending on what type of shape it is. We don't know what shape we are going to be initializing until the user makes a selection.






                                    share|improve this answer




























                                      7














                                      A concrete example from a CAD/CAM application.



                                      A cutting path would be made by using a constructor. It is a series of lines and arcs defining a path to cut. While the series of lines and arcs can be different and have different coordinates it easily handled by passing a list into a constructor.



                                      A shape would be would be made by using a factory. Because while there is a shape class each shape would be setup differently depending on what type of shape it is. We don't know what shape we are going to be initializing until the user makes a selection.






                                      share|improve this answer


























                                        7












                                        7








                                        7







                                        A concrete example from a CAD/CAM application.



                                        A cutting path would be made by using a constructor. It is a series of lines and arcs defining a path to cut. While the series of lines and arcs can be different and have different coordinates it easily handled by passing a list into a constructor.



                                        A shape would be would be made by using a factory. Because while there is a shape class each shape would be setup differently depending on what type of shape it is. We don't know what shape we are going to be initializing until the user makes a selection.






                                        share|improve this answer













                                        A concrete example from a CAD/CAM application.



                                        A cutting path would be made by using a constructor. It is a series of lines and arcs defining a path to cut. While the series of lines and arcs can be different and have different coordinates it easily handled by passing a list into a constructor.



                                        A shape would be would be made by using a factory. Because while there is a shape class each shape would be setup differently depending on what type of shape it is. We don't know what shape we are going to be initializing until the user makes a selection.







                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Mar 10 '09 at 12:30









                                        RS ConleyRS Conley

                                        6,9011534




                                        6,9011534























                                            3















                                            Say, I have a constructor on a class which expects an id value. The constructor uses this value to populate the class from the database.




                                            This process should definitely be outside a constructor.




                                            1. Constructor should not access database.


                                            2. The task and the reason for a constructor is to initialize data members and to establish class invariant using values passed into constructor.


                                            3. For everything else a better approach is to use static factory method or in more complex cases a separate factory or builder class.



                                            Some constructor guide lines from Microsoft:




                                            Do minimal work in the constructor. Constructors should not do much work other than to capture the constructor parameters. The cost of any other processing should be delayed until required.




                                            And




                                            Consider using a static factory method instead of a constructor if the semantics of the desired operation do not map directly to the construction of a new instance.







                                            share|improve this answer




























                                              3















                                              Say, I have a constructor on a class which expects an id value. The constructor uses this value to populate the class from the database.




                                              This process should definitely be outside a constructor.




                                              1. Constructor should not access database.


                                              2. The task and the reason for a constructor is to initialize data members and to establish class invariant using values passed into constructor.


                                              3. For everything else a better approach is to use static factory method or in more complex cases a separate factory or builder class.



                                              Some constructor guide lines from Microsoft:




                                              Do minimal work in the constructor. Constructors should not do much work other than to capture the constructor parameters. The cost of any other processing should be delayed until required.




                                              And




                                              Consider using a static factory method instead of a constructor if the semantics of the desired operation do not map directly to the construction of a new instance.







                                              share|improve this answer


























                                                3












                                                3








                                                3








                                                Say, I have a constructor on a class which expects an id value. The constructor uses this value to populate the class from the database.




                                                This process should definitely be outside a constructor.




                                                1. Constructor should not access database.


                                                2. The task and the reason for a constructor is to initialize data members and to establish class invariant using values passed into constructor.


                                                3. For everything else a better approach is to use static factory method or in more complex cases a separate factory or builder class.



                                                Some constructor guide lines from Microsoft:




                                                Do minimal work in the constructor. Constructors should not do much work other than to capture the constructor parameters. The cost of any other processing should be delayed until required.




                                                And




                                                Consider using a static factory method instead of a constructor if the semantics of the desired operation do not map directly to the construction of a new instance.







                                                share|improve this answer














                                                Say, I have a constructor on a class which expects an id value. The constructor uses this value to populate the class from the database.




                                                This process should definitely be outside a constructor.




                                                1. Constructor should not access database.


                                                2. The task and the reason for a constructor is to initialize data members and to establish class invariant using values passed into constructor.


                                                3. For everything else a better approach is to use static factory method or in more complex cases a separate factory or builder class.



                                                Some constructor guide lines from Microsoft:




                                                Do minimal work in the constructor. Constructors should not do much work other than to capture the constructor parameters. The cost of any other processing should be delayed until required.




                                                And




                                                Consider using a static factory method instead of a constructor if the semantics of the desired operation do not map directly to the construction of a new instance.








                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Sep 22 '15 at 10:17









                                                LightmanLightman

                                                489616




                                                489616























                                                    3














                                                    In addition to "effective java" (as mentioned in another answer), another classic book also suggests:




                                                    Prefer static factory methods (with names that describe the arguments) to overloaded constructors.




                                                    Eg. don't write



                                                    Complex complex = new Complex(23.0);


                                                    but instead write



                                                    Complex complex = Complex.fromRealNumber(23.0);


                                                    The book goes as far as to suggest making the Complex(float) constructor private, to force the user to call the static factory method.






                                                    share|improve this answer





















                                                    • 1





                                                      Reading that part of the book brought me here

                                                      – Purple Haze
                                                      Nov 23 '18 at 16:43











                                                    • @Bayrem: me too, I was re-reading it recently and thought I should add it to the answers.

                                                      – blue_note
                                                      Nov 23 '18 at 16:47
















                                                    3














                                                    In addition to "effective java" (as mentioned in another answer), another classic book also suggests:




                                                    Prefer static factory methods (with names that describe the arguments) to overloaded constructors.




                                                    Eg. don't write



                                                    Complex complex = new Complex(23.0);


                                                    but instead write



                                                    Complex complex = Complex.fromRealNumber(23.0);


                                                    The book goes as far as to suggest making the Complex(float) constructor private, to force the user to call the static factory method.






                                                    share|improve this answer





















                                                    • 1





                                                      Reading that part of the book brought me here

                                                      – Purple Haze
                                                      Nov 23 '18 at 16:43











                                                    • @Bayrem: me too, I was re-reading it recently and thought I should add it to the answers.

                                                      – blue_note
                                                      Nov 23 '18 at 16:47














                                                    3












                                                    3








                                                    3







                                                    In addition to "effective java" (as mentioned in another answer), another classic book also suggests:




                                                    Prefer static factory methods (with names that describe the arguments) to overloaded constructors.




                                                    Eg. don't write



                                                    Complex complex = new Complex(23.0);


                                                    but instead write



                                                    Complex complex = Complex.fromRealNumber(23.0);


                                                    The book goes as far as to suggest making the Complex(float) constructor private, to force the user to call the static factory method.






                                                    share|improve this answer















                                                    In addition to "effective java" (as mentioned in another answer), another classic book also suggests:




                                                    Prefer static factory methods (with names that describe the arguments) to overloaded constructors.




                                                    Eg. don't write



                                                    Complex complex = new Complex(23.0);


                                                    but instead write



                                                    Complex complex = Complex.fromRealNumber(23.0);


                                                    The book goes as far as to suggest making the Complex(float) constructor private, to force the user to call the static factory method.







                                                    share|improve this answer














                                                    share|improve this answer



                                                    share|improve this answer








                                                    edited Nov 23 '18 at 16:46

























                                                    answered Sep 4 '18 at 14:47









                                                    blue_noteblue_note

                                                    11.3k32133




                                                    11.3k32133








                                                    • 1





                                                      Reading that part of the book brought me here

                                                      – Purple Haze
                                                      Nov 23 '18 at 16:43











                                                    • @Bayrem: me too, I was re-reading it recently and thought I should add it to the answers.

                                                      – blue_note
                                                      Nov 23 '18 at 16:47














                                                    • 1





                                                      Reading that part of the book brought me here

                                                      – Purple Haze
                                                      Nov 23 '18 at 16:43











                                                    • @Bayrem: me too, I was re-reading it recently and thought I should add it to the answers.

                                                      – blue_note
                                                      Nov 23 '18 at 16:47








                                                    1




                                                    1





                                                    Reading that part of the book brought me here

                                                    – Purple Haze
                                                    Nov 23 '18 at 16:43





                                                    Reading that part of the book brought me here

                                                    – Purple Haze
                                                    Nov 23 '18 at 16:43













                                                    @Bayrem: me too, I was re-reading it recently and thought I should add it to the answers.

                                                    – blue_note
                                                    Nov 23 '18 at 16:47





                                                    @Bayrem: me too, I was re-reading it recently and thought I should add it to the answers.

                                                    – blue_note
                                                    Nov 23 '18 at 16:47











                                                    0














                                                    Sometimes you have to check/calculate some values/conditions while creating an object. And if it can throw an Exception - constructro is very bad way. So you need to do something like this:



                                                    var value = new Instance(1, 2).init()
                                                    public function init() {
                                                    try {
                                                    doSome()
                                                    }
                                                    catch (e) {
                                                    soAnotherSome()
                                                    }
                                                    }


                                                    Where all additional calculations are in init(). But only you as developer realy know about this init(). And of course, after months you just forget about it.
                                                    But if you have a factory - just do all you need in one method with hiding this init() from direct call - so no problems. With this approach is no problems with falling on creation and memory leaking.



                                                    Someone told you about caching. It's good. But you also have to remember about Flyweight pattern which is nice to use with Factory way.






                                                    share|improve this answer




























                                                      0














                                                      Sometimes you have to check/calculate some values/conditions while creating an object. And if it can throw an Exception - constructro is very bad way. So you need to do something like this:



                                                      var value = new Instance(1, 2).init()
                                                      public function init() {
                                                      try {
                                                      doSome()
                                                      }
                                                      catch (e) {
                                                      soAnotherSome()
                                                      }
                                                      }


                                                      Where all additional calculations are in init(). But only you as developer realy know about this init(). And of course, after months you just forget about it.
                                                      But if you have a factory - just do all you need in one method with hiding this init() from direct call - so no problems. With this approach is no problems with falling on creation and memory leaking.



                                                      Someone told you about caching. It's good. But you also have to remember about Flyweight pattern which is nice to use with Factory way.






                                                      share|improve this answer


























                                                        0












                                                        0








                                                        0







                                                        Sometimes you have to check/calculate some values/conditions while creating an object. And if it can throw an Exception - constructro is very bad way. So you need to do something like this:



                                                        var value = new Instance(1, 2).init()
                                                        public function init() {
                                                        try {
                                                        doSome()
                                                        }
                                                        catch (e) {
                                                        soAnotherSome()
                                                        }
                                                        }


                                                        Where all additional calculations are in init(). But only you as developer realy know about this init(). And of course, after months you just forget about it.
                                                        But if you have a factory - just do all you need in one method with hiding this init() from direct call - so no problems. With this approach is no problems with falling on creation and memory leaking.



                                                        Someone told you about caching. It's good. But you also have to remember about Flyweight pattern which is nice to use with Factory way.






                                                        share|improve this answer













                                                        Sometimes you have to check/calculate some values/conditions while creating an object. And if it can throw an Exception - constructro is very bad way. So you need to do something like this:



                                                        var value = new Instance(1, 2).init()
                                                        public function init() {
                                                        try {
                                                        doSome()
                                                        }
                                                        catch (e) {
                                                        soAnotherSome()
                                                        }
                                                        }


                                                        Where all additional calculations are in init(). But only you as developer realy know about this init(). And of course, after months you just forget about it.
                                                        But if you have a factory - just do all you need in one method with hiding this init() from direct call - so no problems. With this approach is no problems with falling on creation and memory leaking.



                                                        Someone told you about caching. It's good. But you also have to remember about Flyweight pattern which is nice to use with Factory way.







                                                        share|improve this answer












                                                        share|improve this answer



                                                        share|improve this answer










                                                        answered Mar 29 '18 at 14:34









                                                        trashgeneratortrashgenerator

                                                        139215




                                                        139215















                                                            Popular posts from this blog

                                                            404 Error Contact Form 7 ajax form submitting

                                                            How to know if a Active Directory user can login interactively

                                                            TypeError: fit_transform() missing 1 required positional argument: 'X'