dqyitt2954 2015-07-23 12:27
浏览 62

封装实例化参数还是使它们显式化?

My question is regarding instantiation options...

(I've written in PHP, but the question is applicable to general OOP)

Take an example domain object:

class User{

    private $id;
    private $name;
    private $email;
    ...
    etc
}

It is currently instantiated in 2 places.

  1. Controller: A request comes in from client side. The controller extracts the POST variables, instantiates the User object and passes it down the stack.

  2. Data Access Layer: Some getUser() method is called from some service. The user data is pulled from the DB, and the DAL instantiates the User object and passed it up the stack.

We have 2 options for the constructor

Option 1

public function __construct($id, $name, $email,...){
    $this->id = $id;
    $this->name = $name;
    $this->email = $email;
    ...
}

In this case the controller instantiates the object like so:

parse_str($_POST['data'], $data);
$user = new User($data['id'], $data['name'], $data['email'],...);

And the DAL instantiates the object like so:

$row = ...Get row from DB...
$user = new User($row['id'], $row['name'], $row['email'],...);

Which is clear / explicit, but couples our domain object's instantiation to the controller and the DAL. If we decide to add another field to the User table, we have to update the domain object, the controller and the DAL.

Option 2

public function __construct($data){

    ...check $data is valid etc, handle if not...

    $this->id = $data['id'];
    $this->name = $data['name'];
    $this->email = $data['email'];
    ...
}

In this case the controller instantiates the object like so:

parse_str($_POST['data'], $data);
$user = new User($data);

And the DAL instantiates the object like so:

$row = ...Get row from DB...
$user = new User($row);

Now if we decide to add another field to the User table, we only have to update the domain object.

Questions

  • What are the advantages of each of these constructor options?
  • Is there a best practices way of doing this?
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
    • ¥20 怎么用dlib库的算法识别小麦病虫害
    • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
    • ¥15 java写代码遇到问题,求帮助
    • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
    • ¥15 有了解d3和topogram.js库的吗?有偿请教
    • ¥100 任意维数的K均值聚类
    • ¥15 stamps做sbas-insar,时序沉降图怎么画
    • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
    • ¥15 关于#Java#的问题,如何解决?