What is the preferred naming convention for Func method parameters?

后端 未结 3 550
鱼传尺愫
鱼传尺愫 2021-02-07 00:45

I admit that this question is subjective but I am interested in the view of the community. I have a cache class that takes a cache loader function of type Func

相关标签:
3条回答
  • 2021-02-07 00:52

    There are precedents for using a noun in the Framework, e.g.

    Enumerable.Average<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal?> selector)
    
    Enumerable.Count<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
    
    Enumerable.GroupBy<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector)
    
    ConcurrentDictionary<TKey,TValue>.GetOrAdd(TKey key, 
                Func<TKey, TValue> valueFactory);
    

    The noun is often an appropriate verb with an agentive suffix.

    In your example I would use something like loader or possibly valueFactory. I personally don't like cacheLoader because presumably it's the caller rather than the delegate that does the work of inserting in the cache.

    0 讨论(0)
  • 2021-02-07 00:59

    I typically actually use the work delegate in my naming, to make it obvious that this parameter is receiving a delegate. For example, I'd potentially name the above:

    public static class Cache
    {
        public TResult Get<TResult>(string cacheKey, Func<TResult> cacheLoadingDelegate) 
        {
            // Implementation
        }
    }
    

    I do this specifically to avoid confusion from the suggested naming in the question. cacheLoader sounds too much like an object, and loadResult like an object/type (the result itself). I also don't personally like using function or method, as a delegate is not actually a function, but rather a delegate - a type that references a function.

    0 讨论(0)
  • 2021-02-07 01:08

    I like to name it like a method so that when you invoke it, like this:

    loadResult(result);
    

    it looks like an ordinary method call but the casing indicates that it is a variable, so both pieces of information are conveyed.

    You can append a suffix like Method or Delegate or Lambda but those often just make it verbose without adding clarity. It can depend on the situation and your coding standards, and of course your preferences.

    0 讨论(0)
提交回复
热议问题