views:

142

answers:

2

Consider the following source snippets:

Snippet #1

  StoredProcedure sp = new StoredProcedure( "PROC_NAME", getConnection() );
  sp.putParameter( "ID", getId() );
  sp.execute();

Snippet #2

  StoredProcedure sp = new StoredProcedure( "PROC_NAME" );
  sp.setConnection( getConnection() );
  sp.putParameter( "ID", getId() );
  sp.execute();

Snippet #3

  StoredProcedure sp = new StoredProcedure( "PROC_NAME" );
  sp.putParameter( "ID", getId() );
  sp.execute( getConnection() );

Q: Which snippet is the most object-oriented, and why?

Q: What are the pros and cons of each snippet?

+2  A: 

My opinion: None and all of them at the same time.

All snippets show a method which is named action. Part of OO design in general is that each method does only one thing and the method name reflects that; action as a method name isn't reflective and can be used as a blanket title for anything. By looking at what the thing actually does, this method should apparently be called something like executeProcName.

OO is also a lot about Law of Demeter, also known as Principle of Least Knowledge. This means that using getters is a good thing and since all snippets already do that, they really all are OO and equivalent in that case, just like jball says in his answer. If I had to pick the one I'd prefer, it'd be #3 for obtaining the needed external classes/values at the last possible moment (in this case they do affect performance) or #2 because it's the easiest to read.

That's pretty much what I think can be said about this without going deeper into academic semantics.

Esko
#3 also means the procedure doesn't need to hold a reference around to the connection. Thus reducing it's coupling to that class. When cleaning up a connection you don't need to worry about removing this reference.
reccles
Removed reference to the action() method; was a container that detracted from the snippet.
Dave Jarvis
A: 

As the other posters have mentioned, it's highly a matter of preference.

Personally I like the first one, because you are showing your intentions earlier as far as the connection is concerned. You already know you are going to execute against the connection from getConnection, so why set it later?

p = new Person("Joe", "Smith");

is clearer than

p = new Person();
p.setFirstName("Joe");
p.setLastName("Smith");

I'd say whichever is most readable to you is the best one.

z5h
The first is only good until you have to deal with middle names. The Builder pattern addresses this issue.
Dave Jarvis