S
S
Sergey Konovalov2015-09-14 17:07:12
Programming
Sergey Konovalov, 2015-09-14 17:07:12

What to return, Empty collection or null?

Actually the question itself, what is considered the best practice, return Enumerable.Empty() or null? And specify the return type List or IEnumerable?
For example, there is a method that returns a list of addresses, which option would be correct?

public IEnumerable<Adresses> GetAdresses()
        {
            try
            {
                 return dbContext.Adresses.ToList();
            }
            catch (Exception)
            {
                return Enumerable.Empty<Adresses>();
            }
        }

or
public List<Adresses> GetAdresses()
        {
            try
            {
                 return dbContext.Adresses.ToList();
            }
            catch (Exception)
            {
                return null;//или что-нибудь вроде new List<Adresses>
            }
        }

And I would like an explanation.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
Dmitry Kovalsky, 2015-09-14
@zakar1ya

It's better to return an empty list. Business logic, as a rule, checks the collection for the presence of at least some elements (Count/Length>0) or on the basis of (Where().Count/Length>0). Returning NULL will precede these additional checks. checking for NULL. Personally, for what reasons do you want to return NULL?
UPD: There is an alternative - to constantly catch NullReferenceException, but you can use the goto statement with the same success.

V
Vitaliy Orlov, 2015-09-14
@orlov0562

Of course, an empty collection .. you even have a signature about this. In the case of Null, you cannot pass the result further (to the function that takes List<Addresses>) without additional checks. In general, a lot depends on the requirement and context, in the latter case, for example, you can throw the appropriate exception (talking about an empty list), which will be processed further. But, it seems to me more logical to return an empty collection of a given type.

A
Anton Papin, 2015-09-24
@i_light

It's better to return OperationResult in both cases, like this:

public class OperationResult<T>
{
     T Result { get; set; }
     string Message { get; set; }
     bool IsSuccessful { get; set; } // можно заменить на enum с бОльшим количеством вариантов
}

V
Valery Abakumov, 2015-09-24
@Valeriy1991

Good afternoon!
The correct option would be:

public IEnumerable<Adresses> GetAdresses()
        {
            try
            {
                 return dbContext.Adresses.ToList();
            }
            catch (Exception ex)
            {
                // Логируем ошибку - что-то вроде:
                //_loggerService.Error(ex);
                throw;
            }
        }

And outside, for example, you will have a method that, when catching an exception, will issue something conscious to the user:
public ActionResult Addresses()
        {
            try
            {
                 var addressList = _dataService.GetAdresses();
                 return View("_Addresses", addressList);
            }
            catch (Exception ex)
            {
                TempData["Error"] = "Не удалось загрузить список адресов. Попробуйте позже."
                 return View("_Addresses");
            }
        }

In View, I would also advise you to always check for null, because for reasons beyond your control, Model can easily be null. And it is better to handle such situations on the client so that your users do not have a stupor and they do not stop using your web application.
<div>
@if(Model != null && Model.Any())
{
   <div>
       @foreach(var address in Model)
       {
           @*Здесь вывод Ваших адресов*@
       }
   </div>
}
else
{
    <div>
        @TempData["Error"]
    </div>
}
</div>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question