Should I avoid exposing the Lazy<T> class in public API?

旧巷老猫 提交于 2019-12-13 18:14:22

问题


In a design of the public interface of a library, is it legitimate to return an instance of Lazy<T> in a property, if I want lazy initialization? Or is it better to always hide the usage of Lazy<T> by means of encapsulation or other techniques?


回答1:


For the following I'm assumim you mean a Lazy Property.

It depends on the purpose of your interface.

Is it an important detail that the consumer knows that it is lazy ? Or is it just a technical detail which should not change the behavior for the consumer.

It you only have a short delay which must not be handled by the consumer then i would tend to haide the Lazy and only expose T directly.

If the consumer should be aware and may adapt this behavior then i would expose the lazy .

But thiking on this I would in most cases rather expose a method which indicates that the code may have side effects or may take a while.




回答2:


I don't see any reason to directly expose Lazy<T> in the signature. In my use cases, the laziness is an implementation detail.

Don't use this in a property if initialization is long running. In such cases, rather provide a method, considering returning Task<T>.



来源:https://stackoverflow.com/questions/31043096/should-i-avoid-exposing-the-lazyt-class-in-public-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!