Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Funcs instead of instances in frameworks

When looking at the source code of a couple of projects I found a pattern I can not quite understand. For instance in FubuMVC and Common Service Locator a Func is used when a static provider is changed. Can anyone explain what the benefit is of using:

private static Func<IServiceLocator> currentProvider;
public static IServiceLocator Current
{
   get { return currentProvider(); }
}

public static void SetLocatorProvider(Func<IServiceLocator> newProvider)
{
   currentProvider = newProvider;
}

instead of:

private static IServiceLocator current;
public static IServiceLocator Current
{
   get { return current; }
}

public static void SetLocator(IServiceLocator newInstance)
{
   current = newInstance;
}
like image 688
Ruben Avatar asked Dec 12 '22 15:12

Ruben


1 Answers

The major advantage of the first model over the second is what's called "lazy initialization". In the second example, as soon as SetLocator is called, you must have an IServiceLocator instance loaded in memory and ready to go. If such instances are expensive to create, and/or created along with a bunch of other objects at once (like on app startup), it's a good idea to try to delay actual creation of the object to reduce noticeable delays to the user. Also, if the dependency may not be used by the dependent class (say it's only needed for certain operations, and the class can do other things that don't require the dependency), it would be a waste to instantiate one.

The solution is to provide a "factory method" instead of an actual instance. When the instance is actually needed, the factory method is called, and the instance is created at the last possible moment before it's used. This reduces front-end loading times and avoids creating unneeded dependencies.

like image 165
KeithS Avatar answered Dec 26 '22 00:12

KeithS