简体   繁体   中英

Why should I separate internal logic of a public asynchronous method into a private method?

I keep seeing code like this in the same class, I cant think of a reason to separate out a sequential private method. Anyone else can give a good reason?

 public Task<List<myObject>> GetObjectsAsync(object param)
    {
        try
        {
            return Task.Run(() => GetObject(param));
        }
        catch (Exception e)
        {
            //log error
        }
    }

and a private sequential method that accompanies it:

private List<myObject> GetObject(object param))
    {
        return _dLayer.GetObject(param));
    }

It's always good to separate logical blocks -- however small they are -- into separate methods. Separation of concerns is as applicable widely -- such as with separate assemblies, namespaces, and classes -- as it is narrowly, as with methods and logical blocks of related behavior. In this way, it becomes clear and natural to see where you can refactor your code into different classes to follow the "S" in SOLID -- single responsibility principle.

Keeping method sizes small is also important as it improves readability and re-useability.

I'm pretty sure this is why the code is written as such in your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM