I want to add a Phobos module with template mixins for common idioms.

Diggory diggsey at googlemail.com
Mon May 20 16:18:57 PDT 2013


On Monday, 20 May 2013 at 22:02:57 UTC, Idan Arye wrote:
> On Monday, 20 May 2013 at 19:15:34 UTC, Dmitry Olshansky wrote:
>> 20-May-2013 22:14, Idan Arye пишет:
>>> 1) It doesn't matter if the object is not ready, because when 
>>> you want
>>> to actually access the object, you need to use `instance()` 
>>> which has
>>> synchronization.
>>
>> Then where you see hasInstance to fit the bill?
>
> `hasInstance()` tells you if an instance is already 
> initialized, without returning it and without risking in 
> initializing it if it isn't already initialized.

Saying what it does is not a use-case.


> If `hasInstance()` returns `true`, you can assume that there is 
> an instance for you to access, because even if the instance is 
> not ready yet, some other thread has entered the 
> synchronization block and the user can't get the instance until 
> that thread finishes the instantiation - so from the thread's 
> point of view, whenever it'll call `instance()` it'll get a 
> ready instance that was not created beacause of it.

It can return true even if the instance has not been initialised 
yet or false if it has because there's no synchronisation on the 
read. Given that in either situation it can return either true or 
false, there's no use for it.

> First and foremost - this is library library code, so it should 
> expose as much interface as possible without exposing or 
> breaking the implementation.

Only if the interface is useful and not likely to promote bad 
code... It's better to give someone multiple tools, each well 
suited for its purpose, than one tool that tries to do everything 
but is not well suited to anything.

>
> Personally, I think `hasInstance()` would be mainly used in the 
> second use case you suggested. It would be useful if you have a 
> long running loop(for example - a game loop) that needs to 
> interact with the singleton instance if it exists, but can't or 
> shouldn't instantiate it.

In the second example you may as well do:
if (getRandomBool()) {
     ...
} else {
     ...
}

It has the exact same guarantees as your code.

So what's the point of 'hasInstance'?



More information about the Digitalmars-d mailing list