eEcho blog

is een halte van de gedachte

Keeping Clear and Consistent Interfaces

You may hate seeing the word consistency again, but for designing interfaces it’s a criti-
cal piece in the mosaic of programming.
Unfortunately, an example of how not to do it can be found in PHP itself.
When you’re driving a car, the gas pedal is on the right and the brake is on the
left.When you change cars, you expect this setup to stay the same.You expect that
wherever you go, a red traffic light means stop and green means go. Similarly, when you
use a library to access files and have to pass a file handle to every function, it would be
very strange if the function to read from a file would expect the file handle as first
parameter, the write function would expect it as last parameter, and a third function
would expect it somewhere in the middle of its parameter list.

When designing an interface, you should first think about these things:

What data will be exchanged using the interface?

Which parameters do I really need?

What are the common parameters that most (or all) interface functions share?

What would be the most logical order for these parameters?

Keeping this in mind, once you’ve decided to do it in a certain way you should make
no exceptions to this rule in your module. Even internal functions should conform to
the rule.This strategy will enable you to make internal functions available in the inter-
face later on. Plus, your team members will thank you when they have to integrate
new code into your module.
If you look at the string functions in the PHP manual, you’ll find strpos(),
strchr(), strrchr(), and so on. All these functions take as parameters string
haystack, string needle, with haystack being the string in which to search and
needle being the string to search for. Now take a look at str_replace(). Not only
does this function suddenly introduce a different naming scheme, its arguments are
also the exact opposite of the rest of the functions: it accepts string needle, string
haystack.
When we asked the reason for this discrepancy, we got the answer that
str_replace() would be a fast replacement for ereg_replace() and that most people
would change their calls from ereg_replace() (accepting the reverse order arguments)
to str_replace(). Of course, this argument has a point. But why do the regex
functions accept their arguments in an order opposite to that of the string functions?
Because the regex functions in PHP reflect the ones in C.When developing an appli-
cation, it’s always annoying to see str_replace() sticking out from the rest of the
function group.When outlining the interfaces of your next libraries, take great care
that this situation doesn’t happen to you.

Comments are closed.

Home | info@eecho.info | Voorwaarden | Blog