I always prefer to minimize the code, but sometimes I get into conflict with other people about the DRY concept.
In this simple example, which one would be a good choice?
function str_cleaner($str)
{
$str = trim($str);
$str = str_replace(".", "", $str);
$str = str_replace(",", "", $str);
$str = str_replace("-", "", $str);
$str = str_replace("/", "", $str);
return $str;
}
function str_cleaner($str)
{
$chars = array('.', ',', '-', '/');
foreach($chars as $char) {
$str = str_replace($char, '', trim($str));
}
return $str;
}
3 Answers 3
I would say that the first one is a bit more readable, while the second one is a bit more extendable.
Note though that the functions are not actually the same. For example . a .
will produce different results.
Also, personally, I would extract the array from the body of the second function to make it actually reusable:
$str = "my string";
$chars = array('.', ',', '-', '/');
$cleaned_str = str_cleaner($str, $array);
function str_cleaner($str, $chars)
{
foreach($chars as $char) {
$str = str_replace($char, '', trim($str));
}
return $str;
}
Of course, this is also more complex than it needs to be, as str_replace
actually accepts an array:
$chars = array('.', ',', '-', '/');
$cleaned_str = str_replace($chars, "", $str);
I'm not a PHP guru, but from a language agnostic standpoint I'd definitely go for the latter.
function str_cleaner($str)
{
$chars = array('.', ',', '-', '/');
foreach($chars as $char) {
$str = str_replace($char, '', trim($str));
}
return $str;
}
It's easier to maintain and does not use needless repetition.
Also, if you ever want to expand this function, the amount of extra characters in the latter function to achieve this are negligible while significant in the first.
DRY is more important than code size in most situations.
You can pass in an array of chars that need to be replaced in str_replace
function str_cleaner($str)
{
return trim(str_replace(array('.', ',', '-', '/'), '', $str));
}