by matheusmoreira · 7y ago · 0 comments
For example, factories work around the new keyword. The new keyword in Java emits the constructed type into the bytecode, making it a hard ABI dependency. So people invented factories: they hide the new keyword behind methods that return interfaces. In better languages such as Smalltalk, new is just a method that can be overridden.
Singletons work around the fact only objects can implement interfaces. Classes are natural singletons and yet they are second class citizens of most languages. It is not possible to pass the class itself to code expecting some interface. So people are forced to create an object and add complicated boilerplate code to prevent more than one instance from ever being created. In better languages, classes are the same as objects, they can conform to interfaces and be passed around normally.
http://journal.stuffwithstuff.com/2010/09/18/futureproofing-...
http://journal.stuffwithstuff.com/2012/12/19/the-impolitenes...
http://journal.stuffwithstuff.com/2010/08/01/class-in-the-fr...
http://journal.stuffwithstuff.com/2010/12/14/the-trouble-wit...
The flaw in Java is that constructors aren't functions, so you need to wrap them. Wrapping is easy in simple cases but gets annoying fast when you have lots of arguments.
To get around this, you can group arguments using a struct, and sometimes there's a natural way to do it, but that gets annoying in languages without lightweight, easy-to-use structs.
Classes can simply override that method. The default implementation of new is:
^ self basicNew initialize
And basicNew is a method that allocates and returns an instance of the receiver.So a custom implementation can easily change self to some other class, chain more messages or replace initialize with something else, add more logic before an object is returned and so on.
> And wouldn't that just make the "new" method a factory?
Smalltalk actually predates the discovery of object-oriented design patterns by a couple of decades so it's the factory methods that are like the new method. For some reason language designers turned it into a magic keyword and people rediscovered the fact that methods are better.
In Java, an interface could have a static method that returns concrete implementations of itself.
I don't think it is controversial to say those languages are better. A language with limitations that must be constantly worked around must be worse than a language without those problems.
The ABI is also important for performance! You aren’t making this comparison in good faith. You can easily acknowledge the entire trade off rather than just calling one better.