Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object.DoSomething() vs DoSomethingWith(Object) [closed]

Tags:

oop

This may simply be a matter of preference, however, I am interested to know what is the best-practise way of when to use either approach.

e.g.

var person = new Person();
person.Run();

as opposed to

var person = new Person();
Excercise.Run(person);

The above example may not be the best, but my general point is when should you decide to give the object the responsibility as opposed to another class?

like image 573
James Avatar asked Jun 30 '09 09:06

James


1 Answers

Don't do things for your objects. They're there to do things for you.

That sounds quite simplistic, but it's a useful maxim to follow. It means (as you've identified) calling methods on an object and it will use all the knowledge available to it to produce a result. It reinforces encapsulation and separation/containment of responsibilities

An indicator that this is not happening is code like this:

priceBond(bond.getPrincipal(), bond.getMaturity(), bond.getCoupons(), interestRate)

where the bond object is yielding all it's information to some third party. Code like the above will end up beng duplicated everywhere. Instead write

bond.priceBond(interestRate)

and keep all the information tied up in the one object.

If your objects suffer from huge numbers of getters, then it's a possible indicator that your objects aren't doing what they're supposed to.

like image 69
Brian Agnew Avatar answered Sep 28 '22 08:09

Brian Agnew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!