一个内联的类函数,是或不是? [英] One lined class functions, do or don't?

查看:79
本文介绍了一个内联的类函数,是或不是?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将函数排成一行而不是多行是否有害?例如,我为PDO数据库连接编写了一个类文件.我为此编写的所有功能都是一行.我还没有遇到任何错误,但是如果出现迟滞或其他问题,它们可以出现吗?

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?

以下是其中一些功能.

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?

谢谢.

推荐答案

像这样在一行中使用链接方法

Using chained methods in one single line like this

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

Robert Martin ,应避免阅读,以提高可读性

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

对象O的方法M只能调用以下类型的对象的方法:

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

  • O本身
  • M的参数
  • 在M中创建/实例化的所有对象
  • O的直接组成对象
  • O可以访问的全局变量,范围为M
  • 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

不遵循LoD通常会导致UnitTests中出现Mockfest,并使应用程序紧密耦合到不必要的更多类,这继而削弱了可重用性并增加了更改所需的时间(除其他外).

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).

这篇关于一个内联的类函数,是或不是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆