Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DoSomethingToThing(Thing n) vs Thing.DoSomething()

What factors determine which approach is more appropriate?

like image 863
Larsenal Avatar asked Sep 16 '08 20:09

Larsenal


3 Answers

I think both have their places.

You shouldn't simply use DoSomethingToThing(Thing n) just because you think "Functional programming is good". Likewise you shouldn't simply use Thing.DoSomething() because "Object Oriented programming is good".

I think it comes down to what you are trying to convey. Stop thinking about your code as a series of instructions, and start thinking about it like a paragraph or sentence of a story. Think about which parts are the most important from the point of view of the task at hand.

For example, if the part of the 'sentence' you would like to stress is the object, you should use the OO style.

Example:

fileHandle.close();

Most of the time when you're passing around file handles, the main thing you are thinking about is keeping track of the file it represents.

CounterExample:

string x = "Hello World";
submitHttpRequest( x );

In this case submitting the HTTP request is far more important than the string which is the body, so submitHttpRequst(x) is preferable to x.submitViaHttp()

Needless to say, these are not mutually exclusive. You'll probably actually have

networkConnection.submitHttpRequest(x)

in which you mix them both. The important thing is that you think about what parts are emphasized, and what you will be conveying to the future reader of the code.

like image 62
Orion Edwards Avatar answered Nov 05 '22 10:11

Orion Edwards


To be object-oriented, tell, don't ask : http://www.pragmaticprogrammer.com/articles/tell-dont-ask.

So, Thing.DoSomething() rather than DoSomethingToThing(Thing n).

like image 30
benefactual Avatar answered Nov 05 '22 09:11

benefactual


If you're dealing with internal state of a thing, Thing.DoSomething() makes more sense, because even if you change the internal representation of Thing, or how it works, the code talking to it doesn't have to change. If you're dealing with a collection of Things, or writing some utility methods, procedural-style DoSomethingToThing() might make more sense or be more straight-forward; but still, can usually be represented as a method on the object representing that collection: for instance

GetTotalPriceofThings();

vs

Cart.getTotal();

It really depends on how object oriented your code is.

like image 3
Aeon Avatar answered Nov 05 '22 09:11

Aeon