首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >哪个类应该取决于基于重要性级别的哪个类

哪个类应该取决于基于重要性级别的哪个类
EN

Stack Overflow用户
提问于 2015-05-27 01:42:08
回答 2查看 67关注 0票数 3

我有一个关于OOD、OOP和建模的一般性问题,但我不确定该如何提问。最简单的方法就是举例。我通常使用PHP,但它可以用任何其他语言。假设我是一家银行,我想编写一个处理提款的程序。所以我会做两个班级的提款和帐目。现在,更好的方法是使用进行取款的函数。我的意思是:

代码语言:javascript
复制
$account = getAccountById(1); //account->balance = 200.00
$withdrawal = new Withdrawal(50,'USD');
$withdrawal->setAccount($account); // $withdrawal->account_id=1
$withdrawal->make(); //SQL changes account where id=1 and set balance to 150
                     //Also save a row in withdrawal tables with withdraw details

代码语言:javascript
复制
$account = getAccountById(1); //account->balance = 200.00
$withdrawal = new Withdrawal(50,'USD');
$account->processesWithdraw($withdrawal); //SQL changes account where id=1 and set balance to 150
                                          //Also save a row in withdrawal tables with withdraw
                                          //$withdrawal->account_id=1

有一件事是知道的,一个帐户比取款更“重要”,没有它也可以“生活”。也可能有存款或其他操作。

可能还有许多其他方法来完成此操作。你认为哪种方式最好?

我将尝试给出一个更简单的大学网站的例子,它需要允许学生注册课程。

那么当用户点击注册按钮时,你会选择哪一个呢?这一点:

代码语言:javascript
复制
$student = new Student('John Smith');
$course = new Course('Math');
$student->enrollToCourse($course);

或者这样:

代码语言:javascript
复制
$student = new Student('John Smith');
$course = new Course('Math');
$course->addStudent($student);

或者可能是第三种选择:

代码语言:javascript
复制
$student = new Student('John Smith');
$course = new Course('Math');
EnrollmentService::enrollStudentToCourse($student,$course);

也许所有的选择都是同样可行的?

EN

回答 2

Stack Overflow用户

发布于 2015-05-27 01:50:52

更有可能是

代码语言:javascript
复制
$withdrawal = $account->withdraw(50, 'USD');
$withdrawal->completeTransaction();

代码语言:javascript
复制
$transfer = $account->transfer(50, 'USD', $transferToAccount);
$transfer->completeTransaction();

帐户操作应导致交易..事务应该知道如何保持自身,或者在所有更新都不成功时如何回滚

票数 2
EN

Stack Overflow用户

发布于 2015-05-27 02:25:14

对我来说,在OOP中,关键点是清晰。我会这样做。

代码语言:javascript
复制
$account = new Account(1);
$withdrawal = new Withdrawal($account, 50,'USD');
$withdrawal -> makeTransaction();

代码语言:javascript
复制
$account = new Account(1);
$withdrawal = new Withdrawal($account);
$withdrawal ->setAmmount(50);
$withdrawal ->setCurrency('USD');
$withdrawal -> makeTransaction();

我知道这很长,但是这个方法将帮助你遵循“单一责任原则”。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30465355

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档