Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top