C # Using Lazy.Value right after its declaration

The application for the company has a lot of such code in which I work:

var something = new Lazy<ISomething>(() => (ISomething)SomethingFactory .GetSomething<ISomething>(args)); ISomething sth = something.Value; 

From my understanding of Lazy this is completely pointless, but I'm new to the company and I don't want to argue for no reason. So - does this code make any sense?

+6
source share
4 answers

A code that is actively developing is never static, so one possibility of why they code it this way is to move the assignment to another place in the code later if necessary. However, it sounds like it is happening inside a method, and usually I would expect that Lazy initialization is most often found for fields or properties of a class where it makes sense (because you may not know which method in the class will use it first).

Unfortunately, most likely, it will be more likely a lack of knowledge of how the Lazy function works in C # (or lazy init in general), and maybe they are just trying to use the last "cool function" that they learned about.

I saw strange or strange things that spread in the code in the company, simply because people saw that it was encoded in one direction, and then simply copied it, because they thought that the original person knew what they were doing, and that’s has the meaning. It’s best to ask why it was done that way. In the worst case, you will learn something about your company's procedures or coding methods. Best case, you can complete the training if they say "gee, I don't know."

+4
source

Well, in this case, it makes no sense, of course, because you get the value immediately after creating the object, but perhaps this is done in order to follow the standard or something like that.

At my company, we perform similar operations with registering objects in a Unity container and call Unity to create an instance immediately after its registration.

+1
source

If they do not use something several times in this method, it seems rather useless and slightly less effective than just executing the action immediately. Otherwise, Lazy<T> goes through the Value get and checks to see if this value has yet been implemented, and makes a call to Func . Useful for delayed loading, but it makes no sense if it is just used once per method immediately ..

Lazy<T> however, is usually really useful for properties in the class.

+1
source

It may be useful if in the future the Lazy.Value method is removed from the method, but in any case it can be considered a re-evaluation, and not a better implementation, since the Lazy declaration seemed to have extracted the property in this case.

So, briefly - yes, it is useless.

+1
source

Source: https://habr.com/ru/post/954253/


All Articles