3 ms·
An important benefit of static constructor methods is that they allow you to switch class implementations between a final class and an abstract class with priva
by layer8 4y ago
An important benefit of static constructor methods is that they allow you to switch class implementations between a final class and an abstract class with private subclasses, without breaking compatibility. With regular constructors, you are prevented from switching to subclass implementations later. Static constructor methods thus decouple client code more from implementation decisions.
Another benefit is being able to name different constructors differently.
If I were to design a new OO language, I would make it so that constructors always work like that in the first place, from the caller perspective.
- vips7L 4y ago> An important benefit of static constructor methods is that they allow you to switch class implementations between a final class and an abstract class with private subclasses, without breaking compatibility. Is this not what I'm describing? Using one way to construct objects would allow you to change from a concrete class to an interface without breaking client code. I just want the syntax to be the same across interface/abstract/concrete so class construction is uniform and discoverable.
- layer8 4y agoI guess yes, although it now means you always need to start with interface plus class to later have the flexibility, even if you’ll never need it. It is kind of even more verbose. In current Java, you can start with a final class with static constructor methods (which is only slightly verbose), and later switch to having subclasses. It also doesn’t provide the flexibility in naming.
- vips7L 4y agoI don't see how it would be more verbose. // you can start with a final concrete class final class A {} var a = new A(); // and later move to interfaces or abstract types sealed interface A permits B, C { public A() { ... } } var a = new A(); Client code would remain the same with the flexibility to refactor to whatever you want later.
- layer8 4y agoI see, yes, if it is possible to make this binary-compatible in the JVM, that would work. One implication is that `new A()` wouldn't be guaranteed to return a new instance anymore (just as for a static method). Personally I still prefer having the ability to name the constructors. I'd rather have "new" be the default constructor name, with the option of having it be something else (i.e. Path.new(...) vs. Path.somethingElse(...)).