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; } 
  • one
    I read somewhere that simply returning null is not good, because I constantly have to add a check for this. But if you want to return an object that is not in the list (because the list is empty, for example), what do you usually do in such situations? It may be necessary to first check for the presence of an object, and then just call a function to return it, or maybe some other way - marked_four

5 answers 5

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.

      • one
        We used to check for null, but now we’ll have to check if the object was returned to us by default :) - KoVadim

      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.

        • In general, yes, at the design stage of the program, it is necessary to clearly understand how some component will behave and why. - Modus