3 ms·
> actors Sorry, I should've been clearer there. I meant constructors. > can you give an example of how an init function is used to do something that an object
by AllegedAlec 7y ago
> actors
Sorry, I should've been clearer there. I meant constructors.
> can you give an example of how an init function is used to do something that an object should already know?
The only way to instantiate a new version of an object in Pharo is with the new message to the class, for example with
aDate := Date new
However, that point does not yet know what its time offset from epoch is, which is absolutely vital when trying to use a date. It needs to be instantiated at construction with that information.
How pharo gets around is by essentially creating class messages which hand you back the instantiated object, such as with
aDate := Date year: 2015 month: 12 day: 31
However, this is just syntactic sugar (as far as I can tell, please someone correct me if I'm wrong) for a class message calling new and setting the properties on the object it just created. It is a fairly clean way to create objects, in general.
However, the method 'new' can still be used (there is no access modifiers in Pharo), so it's still possible to call an object without ensuring it's initialized properly. I have yet to find a good way around this.
- em-bee 7y agooh, i get it, so there was actually only one point: constructors with arguments instead of init functions that wrap around new but don't disable it. and yes i agree, it should be possible to prevent the creation of uninitialized objects.
- tom_mellior 7y ago> it's still possible to call an object without ensuring it's initialized properly. I have yet to find a good way around this. Implement the class's new method with an implementation that just throws an UnsupportedOperation exception?