There is a method that returns an object if it is in the list. How to get rid of returning null if objects are not in the list?
Assume:
public SomeObject ReturnSomeObject(){ return (SomeObjectList.Count > 0) ? SomeObjectList[0] : null; }
There is a method that returns an object if it is in the list. How to get rid of returning null if objects are not in the list?
Assume:
public SomeObject ReturnSomeObject(){ return (SomeObjectList.Count > 0) ? SomeObjectList[0] : null; }
If you do not want to return null
, then the most reasonable will be to throw an exception, something like ObjectNotFoundException()
.
Congratulations! You are on the path to discover The option type , which more advanced programming languages (Scala, F #, Ocaml, Haskell, etc.) have been using for a long time. In C #, as well as in Java, there is no such type, but it is easy to do it yourself. First, I recommend that you read my answer to the question " Non-null programming language " in order to understand what type-option is. Then go to the " Option type C # " article, which shows how to implement and use this type in C #.
Return a new object, for example. Or store the default instance in the class field and return it if the list is empty.
You can not just not return, you need to choose what to do instead. Although, it seems to me, there is no space for choice - just throw an exception.
In some situations, it may be appropriate to use the "Null Object" pattern to return a subclass object (or how best to do it in C #) that implements class operations empty - in other words, the NOP implementation. With this pattern, of course, you need to be careful and attract only with full confidence that the benefits will outweigh the complexity of the system.
Source: https://ru.stackoverflow.com/questions/40248/
All Articles