• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Database access via a static method

 
Chris Bicnal
Ranch Hand
Posts: 96
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Guys,

What's the general consensus on database access with a static method (or methods). Is this generally frowned upon?

For the sake of clarity, I'm thinking about some business logic which needs to read something from the database (say for instance whether a person is over a certain age limit).

Would it be bad to encapsulate this logic into a static helper method - and if so, why?

Thanks,

Chris

 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is too little information there to say for sure if it is good or bad, but it does feel a little icky to me. The problem with static methods for this sort of thing is that they aren't very flexible - it makes it harder to reuse code without creating un-necessary dependencies, harder to mock an object for test, etc...

Since the database can be expected to change independently of the business logic (and the logic independently of the database) I feel it is generally better to isolate one from the other.

You might want or need to subclass the business object, and you might need to override or change the behavior of the way the data is taken: or you may want to generalize the interface to the business logic and how it gets the data it needs. This is all pretty simple to do until you have to think about static methods and shadowing and which version gets called. So for that reason I would rather the data-access be handled in an instance method rather than static (independent of whether it is in the same class as the business logic or not).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic