Question

Suppose a class whose responsibility is to set parameters to a JDBC query.

It would have a fillParameters() method and a PreparedStatement as a field because shared across all private submethods.

Furthermore, these submethods need to know about current JDBC parameter index.

So two solutions may adopted :

  • Pass current index into each method as a local parameter (redondant if there are many submethods)

  • Declare current index position as a field (or attribute) so that no need to pass it through multiple method parameters. But the drawback is that it can cause side-effect if we imagine that a second call to this method is made with the same object instance (for a particular reason, no real usecase but imagine...). Indeed, it would be compulsory to reinitialize current Index Posion to 0 before calling all process made by submethods.

What is the best-practice ?

public void fillParameters(){
this.currentIndex = 0; //reinitialize to first index !
//....call to each submethods without need to pass currentIndex as local parameter
}

Or :

public void fillParameters(){
int currentIndex = 0;
//....call to each submethods with currentPosition as index like :
feedFirstParameter(++currentIndex);
feedSecondParameter(++currentIndex);
}
Was it helpful?

Solution

The local variable option is better encapsulation of the details of how your method works. That will be easier to maintain and less likely to have side effects as you point out. If overhead becomes an issue you can optimize. I'm not sure there's a best practice, since a design depends on what's important to you. The best thing either way would be to document your reasoning in the code.

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