Non-null objects, the Null Object pattern, and T.init
Namespace
rswhite4 at googlemail.com
Fri Jan 17 00:19:58 PST 2014
On Friday, 17 January 2014 at 08:13:05 UTC, Namespace wrote:
> On Friday, 17 January 2014 at 03:02:57 UTC, inout wrote:
>> On Friday, 17 January 2014 at 02:52:15 UTC, bearophile wrote:
>>> deadalnix:
>>>
>>>> Most object don't have a sensible init value. That is just
>>>> hiding the problem under the carpet.
>>>
>>> If there's desire to solve this problem I think that
>>> improving the type system to avoid nulls where they are not
>>> desired is better than having an init object.
>>>
>>> So aren't not-nullable pointers and references a better
>>> solution?
>>>
>>> Bye,
>>> bearophile
>>
>> This! Also, if anything, it's better to turn `init` into a
>> method
>> rather than an object. The following would work all of a
>> sudden:
>>
>> class Foo
>> {
>> Bar bar = new Bar();
>> int i = 42;
>>
>> Foo() {
>> assert(bar !is null);
>> assert(i == 42);
>> }
>>
>> // auto-generated
>> private final void init(Foo foo) {
>>
>> foo.bar = new Bar();
>> foo.i = 42;
>> }
>> }
> That would be indeed a nice solution and would break AFAIK
> nothing. :)
But IMO even better would be something like this:
----
class A {
int id;
this(int id) {
this.id = id;
}
static A init() {
return new A(42);
}
}
A a; /// <-- A a = A.init; --> A a = new A(42);
----
Define your own init method which initialize the object to not
null.
More information about the Digitalmars-d
mailing list