Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Consider this:

public MyClass
{
    private Resource _myResource;

    public Resource MyResource
    {
        get
        {
            if(_myResource == null)
            {
                _myResource = new Resource();
            }

            return _myResource;
        }
    }

    public void UseResource()
    {
        MyResource.DoSomething();
    }
}

Is this a recognised pattern, or possibly an anti-pattern? I've never seen it suggested in any books, but it does come up time and time again in code I see. I think the logic of this is that _myResource is instantiated 'just in time'. To me, it seems a bit smelly. UserResource() is accessing a public property from within the class, and the resource can never really be accessed through the private member - if someone did, _myResource could be null.

Maybe performance reasons may sometimes necessitate, but I would generally favour instantiating in the constructor, or just having an instance of Resource local to the method.

So is this an accepted pattern, or should it be avoided?

share|improve this question
    
There's nothing wrong with this pattern but this particular example is quite a poor example. It would be better to pass an abstract factory into the constructor of the class, and query the factory the first time the resource is needed... –  MattDavey Sep 28 '11 at 12:41
    
@MattDavey: You cannot say that universally. In many cases your suggestion would be just plain overengineering imho. –  Falcon Sep 28 '11 at 12:45
1  
This seems to violate the Single Responsibility Principle. The class is already doing too much by creating and using the resource. Creation should be separated which would also make unit testing easier. –  c_maker Sep 28 '11 at 13:01
    
@c_maker: I strongly disagree! If all you have to do is calling a simple constructor, then you should not put the creation in its own class, for the sake of simplicity. Also, in this generic example, we cannot tell whether the SRP is really violated. It's perfectly fine for a class to create something that it will use. –  Falcon Sep 28 '11 at 13:10
1  
@Falcon A class which is tightly coupled to its resource and calls the constructor directly is not cohesive, and is not unit testable. There's a distinction between consuming a resource, owning the lifetime of a resource and being responsible for constructing a resource... –  MattDavey Sep 28 '11 at 14:18
show 5 more comments

1 Answer

up vote 4 down vote accepted

This is an accepted pattern. It's called lazy initialization, a creational pattern. You usually use this for performance reasons, often combined with other patterns, for example the Proxy Pattern. When resources are heavy and you don't need them right away, then this is a good and clean approach to make sure they're only initialized the first time you need them.

Wikipedia calls it a "tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed".

ORMs for example use this pattern to perform lazy initializations of related entities, so you needn't fetch a whole aggregate object-graph eagerly, but only when you really need to operate on the related entities.


Maybe performance reasons may sometimes necessitate, but I would generally favour instantiating in the constructor, or just having an instance of Resource local to the method.

Sure, this might be a cleaner approach. But if the resources are really costly to instantiate, then lazy initialization is a good way to deal with them. Do you really want to wait a long time for instantiating an object that by itself is lightweight, but occasionally needs a heavy resource?

To me, it seems a bit smelly. UserResource() is accessing a public property from within the class, and the resource can never really be accessed through the private member - if someone did, _myResource could be null.

It looks indeed a bit smelly and if it is used everywhere and not by its purpose then it really stinks. As with all optimizations: Don't optmize if you don't need an optimization. But lazy initialization can be a great benefit to your application when used right. And then its inconspicuous smell is a small price to pay for its worth.

share|improve this answer
    
Cheers for that. So I'll go with the common 'only do it if you can argue a case for it approach', in this case performance reasons. –  Paul T Davies Sep 28 '11 at 15:52
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.