Many methods vs a method with flags

What is preferable ?

public function getByID($id) {}
public function getByIDs(array $id) {}

Or

public function getByID($id) {
if (is_string) {
\\\\do something...
}
elseif (is_array) {
\\\\do something...
}
}

Does the second example violate Single Responsibility Principle ?
Which one do you prefer? Why?

I prefer the first. I think it will be easier to read and understand code that uses those first two methods because it will be more obvious what the return value’s type will be. I might even go one step further and name them:

public function getOneByID($id) {}
public function getAllByIDs(array $id) {}

Just to make it super obvious that one returns a scalar value and the other returns an array of values.

1 Like

I agree with Jeff.

The first choice is a bit more work for you as a programmer, but makes for overall better readability. The code becomes more self-explanatory and when you are working with the class, the methods explain the available logic fairly well, whereas the method with ifs would require you to “go and look” at what the method does (and doesn’t enforce the “tell, don’t ask” principle of encapsulation ((yeah, maybe not quite right, but leave me with that thinking…))). In other words, as the user of the class, you really wouldn’t know you could find multiple ids with the single method with ifs and elseifs, without having to go look at the method.

I’d also say from what I can see, neither choice would break SRP, because you are still getting ids from probably one entity or object or whatever it is.

Now, if you end up with too many methods in your class, that could be more of a sign of breaking SRP. Or if you are calling other classes or even other methods within the if statements, that is a fairly clear sign you are breaking SRP.

Two good rules for clean code is to have only one level of indentation and never use “else”. It is hard, but try it. :wink:

Scott

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.