-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\$ Commented Dec 5, 2019 at 13:13
  • \$\begingroup\$ @Heslacher Nop, just playing around \$\endgroup\$ Commented Dec 5, 2019 at 13:20
  • \$\begingroup\$ If the code is not real, then the question is off-topic. See codereview.meta.stackexchange.com/questions/3649/… \$\endgroup\$ Commented Dec 5, 2019 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\$ Commented Dec 5, 2019 at 15:44

1 Answer 1

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\$ Commented Dec 5, 2019 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\$ Commented Dec 5, 2019 at 13:42
  • \$\begingroup\$ If list is null, an exception is thrown on if (list.Count == 0) return null;. \$\endgroup\$ Commented Dec 5, 2019 at 17:09
  • \$\begingroup\$ @RickDavin good point. list?.Count it is :) \$\endgroup\$ Commented Dec 6, 2019 at 7:07

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.