1
\$\begingroup\$

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;
}
Mast
13.8k12 gold badges57 silver badges127 bronze badges
asked Oct 5, 2015 at 12:46
\$\endgroup\$
0

3 Answers 3

3
\$\begingroup\$

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);
answered Oct 5, 2015 at 13:04
\$\endgroup\$
2
\$\begingroup\$

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.

answered Oct 5, 2015 at 13:04
\$\endgroup\$
1
\$\begingroup\$

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));
}
answered Oct 5, 2015 at 13:47
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.