what to return from this function?

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
User avatar
daedalus__
DevNet Resident
Posts: 1925
Joined: Thu Feb 09, 2006 4:52 pm

what to return from this function?

Post 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?
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Re: what to return from this function?

Post by Jenk »

format exception.
André D
Forum Commoner
Posts: 55
Joined: Thu Aug 28, 2008 7:03 pm

Re: what to return from this function?

Post 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.
Post Reply