-2
\$\begingroup\$

How could I refactor this code to get it more cleaner:

public List<TestDTO> Map(product product)
{
    if (product == null || product.Tests == null || !product.productTests.Any()) return null;

    return product.productTests.Select(x => _productService.Map(x)).ToList();
}

Is it possible to write this more cleaner?

Thanks

Cheers

\$\endgroup\$
4
  • \$\begingroup\$ Is this your real code? \$\endgroup\$ – Heslacher Dec 5 '19 at 13:13
  • \$\begingroup\$ @Heslacher Nop, just playing around \$\endgroup\$ – Roxy'Pro Dec 5 '19 at 13:20
  • \$\begingroup\$ If the code is not real, then the question is off-topic. See codereview.meta.stackexchange.com/questions/3649/… \$\endgroup\$ – Heslacher Dec 5 '19 at 13:31
  • \$\begingroup\$ It might be better to ask questions like this on stackoverflow.com, but search stackoverflow.com first to see if it has already been answered. \$\endgroup\$ – pacmaninbw Dec 5 '19 at 15:44
2
\$\begingroup\$

One solution would be to stop passing null values around everywhere. That would require changes much wider than the scope of this method though.

The biggest thing that can be won here is the ?. operator. If the left hand side is null, the result will be null as well:

product?.productTests?.Select(x => _productService.Map(x))?.ToList();

will remove the need for the first two null checks.

Returning a null instead of an empty list is... questionable, but if you must return null you can check afterwards:

public List<TestDTO> Map(product product)
{
    var list = product?.productTests?.Select(x => _productService.Map(x))?.ToList();
    if (list?.Count == 0) return null;
    return list;
}
\$\endgroup\$
4
  • \$\begingroup\$ isn't this enought ? return product?.productTests?.Select(x => _productService.Map(x)).ToList(); if any of this is null, null will be returned, otherwise data.. \$\endgroup\$ – Roxy'Pro Dec 5 '19 at 13:24
  • \$\begingroup\$ @Roxy'Pro I made a mistake, it should be ?.ToList as well. Note that this is functionally different from your code, which also returns null when product.productTests is empty. \$\endgroup\$ – JAD Dec 5 '19 at 13:42
  • \$\begingroup\$ If list is null, an exception is thrown on if (list.Count == 0) return null;. \$\endgroup\$ – Rick Davin Dec 5 '19 at 17:09
  • \$\begingroup\$ @RickDavin good point. list?.Count it is :) \$\endgroup\$ – JAD Dec 6 '19 at 7:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.