3
moqs
4y

Just askin:
If you have a method which returns a value from an array. What do you prefer in a case when the item is not found?
A)Throw an exception
B)return null
C)return a special value like a null object or some primitive type edge value like Integer.MIN_VALUE

Comments
  • 1
    This is hard to answer, so many outside factors would determine it.
  • 2
    It depends if there is already exception handling in the code. If not, we usually populate a pass-by-reference variable and return true if we found it, do nothing to the variable and return false if we didn't.
  • 2
    I would also say that it depends on what the method is named. What does the name communicate? TryFind(x) would suggest that a failure is to be expected and returning null or a sentinel would be appropriate. Find(x) would suggest to me that I needed to be sure that it would succeed and that an exception should be thrown I the failure case. Most of all though, document well and be consistent.
  • 1
    A custom exception
  • 0
    Also where i work, we use -9 for undefined values
  • 0
    If I'm working with arrays and a functional paradigm, I prefer null so map/filter/reduce can safely and easily be handled.
  • 5
    D) create the item, insert it in the database, return it, and never discuss it again with anyone.
  • 1
    As a Strong Typed language lover I use the exception, cause null is nothing (literally) and it would need an interpretation, like what if the value was really null in your array or your DB, a custom exception is more defensive oriented and better design.
  • 0
    I usually just return false
  • 1
    @linuxxx that may mess things up. What if the value returned is 0 and it gets evaluated as false?
  • 0
    I would return null if it was a private method and something more meaningful if it was public...(an Optional if it is available). I wouldn't go with custom exception, if there is some kind of fuckery going on (that value was definitely supposed to be found) just throw an IllegalStateException
  • 1
    Most important question: what language is this in? For example in Go you could use multiple returns if you're expecting some error condition regularly. In python it's more idiomatic to use a try/except. PHP you'd probably return false. Other languages will have their own opinions on what's right. Even then there's always implementation-specific details.
  • 0
    Use Rust:

    If found, return Ok(element)

    Otherwise, None()
  • 0
    Returning Null and handling it would be my default approach but as others say other factors to consider.

    An exception is appropriate if it the lack of result cannot be handled by the rest of the solution but throwing many exceptions will have a performance impact.
Add Comment