Ranter
Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Comments
-
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.
-
ridecar23828yI 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.
-
If I'm working with arrays and a functional paradigm, I prefer null so map/filter/reduce can safely and easily be handled.
-
fattire1808yD) create the item, insert it in the database, return it, and never discuss it again with anyone.
-
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.
-
@linuxxx that may mess things up. What if the value returned is 0 and it gets evaluated as false?
-
cheke4308yI 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
-
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.
-
LMagnus20638yReturning 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.
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
undefined
code pattern review