4 ms·
> In Smalltalk, how would how would the consumer be given differing implementations of this "new" method? Classes can simply override that method. The default
by matheusmoreira 7y ago
> In Smalltalk, how would how would the consumer be given differing implementations of this "new" method?
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.
- LgWoodenBadger 7y agoIf my BubbleMachine currently makes SoapBubbles, but I want it to be able to make GumBubbles as well, who, out of those three, is responsible for overriding the “new” method to create GumBubbles instead of SoapBubbles?
- spankalee 7y agoA Bubbles class, which is basically the same as a factory. I don't see a huge difference in practice myself.
- matheusmoreira 7y agoAre these all subclasses of a Bubbles class? I think that'd be the natural place for a custom new method that figures out which subclass to construct based on the parameters. In Java, an interface could have a static method that returns concrete implementations of itself.
- scroot 7y agoIt's even better. If it's just making stuff, you don't even need `BubbleMachine` if you have the `Bubbles` base class. You can add creation method on the class side of `Bubbles` like so: `Bubbles class >> #newGum` ^ GumBubbles new `Bubbles class >> #newSoap` ^ SoapBubbles new The difference here is that the base class still serves as a true base: it will have all the common functionality for various kinds of bubbles