1

I would like to know if it's a good or bad practice to return null or throw an exception instead.

I consider that exceptions should be thrown when something truly exceptional happened, but returning null is ugly, and, anyways, a layer above will have to check for null and throw an exception, since getting an Id that doesn't exist isn't allowed in my domain.

How to proceed correctly?

SuperJMN
  • 13,110
  • 16
  • 86
  • 185
  • 2
    There isn't only black or white. See "[NullObject Pattern](https://en.wikipedia.org/wiki/Null_Object_pattern)". – Fildor Sep 21 '17 at 12:10
  • See also https://stackoverflow.com/questions/175532/should-a-retrieval-method-return-null-or-throw-an-exception-when-it-cant-prod which is more general question, but also closed as opion-based. – MakePeaceGreatAgain Sep 21 '17 at 12:11
  • What is the name of the method? – mjwills Sep 21 '17 at 12:17
  • 2
    _"since getting an Id that doesn't exist isn't allowed in my domain"_ - the repo shouldn't need to know about your domain rules. – stuartd Sep 21 '17 at 12:18
  • 1
    You must return [42](https://en.wikipedia.org/wiki/42_(number)#The_Hitchhiker.27s_Guide_to_the_Galaxy). That's the only answer. – Sinatr Sep 21 '17 at 12:26

1 Answers1

1

In my opinion, Null is preferable over throwing an Exception, but that depends on how exceptional this case is, and of course your domain.

A nicer thing to return is a Null object, i.e. an Object that implements the same Interface as the item you are looking up in your repository, but it has behaviour that makes it nicer to work with than just null.

Read up on the Null object pattern, or look it up in Agile Principles, Patterns, and Practices in C#

Fontanka16
  • 1,161
  • 1
  • 9
  • 37
  • 2
    _"Null is preferable over throwing an exception. There is nothing exceptional about not finding the things you are looking for in a repository."_ - Do you work on the same project as OP? If not, you cannot possibly know that. _"since getting an Id that doesn't exist isn't allowed in my domain"_ - So *if* looking up a non-existing id would hint to a coding error or error in some business logic, then throwing an exception would be totally justified (who and where throws it is debatable, though). – Fildor Sep 21 '17 at 12:19
  • 2
    Good point. Of course there are cases that are not exceptional. I will lighten that statement. – Fontanka16 Sep 21 '17 at 12:23