One lined class functions, do or don't?

2020-07-25 23:47发布

问题:

Is there any harm to having functions one lined instead of multilined? For example, I wrote a class file for a PDO database connection. All the functions I wrote for it, are one lined. I haven't run into any errors yet, but can they crop up if there is lag or something?

Here are some of the functions.

public function getObject($query, $object) {
  return $this->db->prepare("$query")->execute()->fetch(PDO::FETCH_OBJ)->$object;
}

public function getArray($query) {
  return $this->db->prepare("$query")->execute()->fetchAll(PDO::FETCH_NUM);
}

public function insertArray($query, $array) {
  return $this->db->prepare("$query")->execute($array);
}

Will this eventually run into problems? Or do they get called one section at a time, as if they were on their own line?

Thanks.

回答1:

Using chained methods in one single line like this

return $this->db->prepare("$query")->execute()->fetch(PDO::FETCH_OBJ)->$object;

is what Robert Martin calls "Train Wrecks" in Clean Code (pg 98/99). It's hard to read and "generally considered sloppy" and should be avoided for the more readable

$statement = $this->db->prepare("$query");
$statement->execute();
$result = $statement->fetch(PDO::FETCH_OBJ);
return $result->$object;

Please note that I corrected the code in the snippet above, as your one-liner will not work, because execute returns a boolean, so you cannot call fetch on it:

bool PDOStatement::execute ([ array $input_parameters ] )

In other words, you cannot write this as a one-line statement anyway.

Also note that Method Chaining is very often a violation of the Law of Demeter, which states that

a method M of an object O may only invoke the methods of the following kinds of objects:

  • O itself
  • M's parameters
  • any objects created/instantiated within M
  • O's direct component objects
  • a global variable, accessible by O, in the scope of M

Not following LoD usually leads to Mockfests in your UnitTests and makes your application tightly coupled to much more classes than necessary, which in turn impairs reusability and increases the time required for changes (among other things).



回答2:

Imperative code will always get called in the expected order. There is nothing to worry about, except maybe if the code is readable or not. In case where the line is very very long, you might want to wrap it to multiple lines, but the examples you show look OK to me.



回答3:

If the connection to the database fails for some reason it could cause a FATAL_ERROR because one of the objects will return false.



标签: php pdo