Skip to main content
6 events
when toggle format what by license comment
Oct 23, 2017 at 15:41 comment added user286462 @FilipMilovanović - You read my question, I meant with regards to static factory methods. I wanted to know the why
Oct 23, 2017 at 15:39 comment added Filip Milovanović @S.R. (C.C. @whatsisname): For the record, I actually agree with whatsisname when it comes to when you should use constructors vs factory methods (Principle of least astonishment). My answer and my previous comment were made under the assumption that you are asking specifically if the reasoning behind the advice to avoid static (global) methods/state applies to static factory methods, as I get the impression that you are looking to understand the "why" behind it all.
Oct 23, 2017 at 14:40 comment added whatsisname @S.R.: no, it's not fine. It'll compile and execute, but it violates the Principle of least astonishment. If you want to create an object, you should normally use new.
Oct 23, 2017 at 13:21 comment added Filip Milovanović IMO - yes. As far as I'm aware, it's a relatively common thing to do. Also, there's an advantage of being able to give a more meaningful name to your static factory method (or methods). Now, as the JavaDocs say, this is one way to prevent inheritance, and it's one that generalizes fairly well to other languages. I wouldn't necessarily agree that it's "a more sophisticated approach" compared to marking the class final (or sealed, the C# equivalent).
Oct 23, 2017 at 13:01 comment added user286462 So, it's fine to use a static method as a way of creating and returning an immutable object? As stated in the JavaDocs
Oct 23, 2017 at 11:38 history answered Filip Milovanović CC BY-SA 3.0