Wednesday, May 17, 2006

Repeat after me, "Objects have behaviors and attributes..."

I was catching up on Martin Fowelers blog and caught this article on FluentInterface. This would be a great way to set up your domain objects to collaborate. It also reinforces another idiom - make your API as "natural" as possible, not just a bunch of getters and setters and a functions to tie them all together.

Speaking of which - GetterEradicator is a fantastic article off of Martin Fowler's bliki that addresses what your objects public interface should be. Great quote from the article.

The OO community may have 'won' in the sense that modern languages are dominated by objects, but they are still yet to win in that OO programming is still not widely used. As a result it's still common to see procedures that pull data out of an object to do something, when that behavior would better fit in the object itself - a violation of the pragmatic programmers principle of "Tell Don't Ask". You can only do this kind of procedural programming if you have getters, so telling people to get rid of getters helps push them to move behavior into the right place.

(Special thanks to HoR for sending a reference this out to our Dev team!)

2 Comments:

Blogger Brown Dwarf said...

A happy medium between the "non-fluent" and "fluent" styles might be simply having normally-void methods return 'this'.

Consider StringBuffer:


StringBuffer msg
= (new StringBuffer())
.append( "Helllo, ")
.append( userName)
.append( ", how are you?");

append() returns 'this' for further action.

(new Order())
.setRush( true)
.addLine( new OrderLine(...))
.addLine( (new OrderLine(...)).setSkippable(true))
:
:

(etc.)

9:35 PM  
Blogger Brown Dwarf said...

Fowler calls out a number of flaws w/the fluent interface approach, which I won't repeat, except to add a comment to the following:

The price of this fluency is more effort, both in thinking and in the API construction itself. The simple API of constructor, setter, and addition methods is much easier to write. Coming up with a nice fluent API requires a good bit of thought.

If you have team members who are prone to code first (e.g., via copy and paste) and think never, I don't know how this will work out.

This might be a case of separating developers into two tiers: framework builders and framework users, and that has pitfalls of its own (e.g., framework users waiting on framework builders, which drives managers nuts and may result in rickety frameworks).

9:45 PM  

Post a Comment

<< Home