Which class should depend on which class is based on importance level

I have a general question related to OOD, OOP and Modeling and I'm not sure how to ask it. The easiest way is an example. I generally use PHP, but it can be in any other language. Let's say I'm a bank and I want to make a program that handles withdrawals. So I will make 2 classes Withdrawal and Account. now it's better to have a function that draws inference I mean:

$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

      

or

$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

      

One thing known about an account is more "important" than a review and can "live" without it. There could also be deposits or other actions.

There are probably many other ways to do this. How do you think is best?

I will try to give a simpler example of a university website that should allow a student to enroll in a course.

So when the user clicks the registration button, which one will you choose? It:

$student = new Student('John Smith');
$course = new Course('Math');
$student->enrollToCourse($course);

      

Or that:

$student = new Student('John Smith');
$course = new Course('Math');
$course->addStudent($student);

      

Or maybe a third option:

$student = new Student('John Smith');
$course = new Course('Math');
EnrollmentService::enrollStudentToCourse($student,$course);

      

Perhaps all options are equally viable?

+3


source to share


2 answers


more likely

$withdrawal = $account->withdraw(50, 'USD');
$withdrawal->completeTransaction();

      

or



$transfer = $account->transfer(50, 'USD', $transferToAccount);
$transfer->completeTransaction();

      

account actions should result in transactions. transactions need to know how to save themselves, or rollbacks if all updates fail.

+2


source


for me in OOP, clarity is key. I would do it like this.

$account = new Account(1);
$withdrawal = new Withdrawal($account, 50,'USD');
$withdrawal -> makeTransaction();

      

or



$account = new Account(1);
$withdrawal = new Withdrawal($account);
$withdrawal ->setAmmount(50);
$withdrawal ->setCurrency('USD');
$withdrawal -> makeTransaction();

      

I know this is long, but this approach will help you follow the "Single Responsibility Principe"

+2


source







All Articles