Page 1 of 1

what to return from this function?

Posted: Wed Jan 20, 2010 9:35 pm
by daedalus__
hey im prototyping some functions for working with colors and positions like hex to rgb and calculate a position on an arc and shizz and im wondering what you guys would expect as a return in this situation.

okay so you are going to take a hex rgb value and convert it to integer based rgb:

Code: Select all

 
ohbaby = 'a33445'.toRgb();
 
but oops you threw in an extra character by accident oh noes!

Code: Select all

 
ohnoobaby = 'a334445'.toRgb();
 
what would you expect for a return?

should i throw an exception? return NaN? false? null?

not sure if there is really a right answer but lets say you are debugging this when you didn't write it. what would be least annoying?

Re: what to return from this function?

Posted: Thu Jan 21, 2010 4:54 am
by Jenk
format exception.

Re: what to return from this function?

Posted: Thu Jan 28, 2010 5:57 pm
by André D
I think it depends on a few things, including the language. (Your examples aren't in PHP.) In PHP, I'll usually throw an exception or return NULL. In your specific scenario, I'd probably throw an exception.

You might want to create a custom exception type by extending the base Exception class. You can also use the SPL exceptions, such as the InvalidArgumentException, or maybe the OutOfBoundsException or OutOfRangeException types; I'm not sure which.

Of course, a hex RGB is simply a number between 0 and 16777215 (a 24-bit number) in base-16 notation. So if your code implementation manipulates these values as numbers, the following might be natural: If you get a value that is valid hexadecimal, but exceeds FFFFFF, say you get BFFFFFF, then you might choose to reduce it to the maximum value in the acceptable range, FFFFFF, and return the corresponding value without an error. On the other hand, if it contains non-hexadecimal characters, such as GFFFFFF, then it is not a number and you should throw an exception or return NULL.