开发者

Where to store static methods in OOP?

开发者 https://www.devze.com 2022-12-14 16:30 出处:网络
I have a Blog class that does exactly what you think it would...create an object and handle it. That part is nice and clean.

I have a Blog class that does exactly what you think it would...create an object and handle it. That part is nice and clean.

I am now in need of a function that will quickly return a number of all the blogs in my database (not necessarily related to the blog object). Therefore, I am thinking a static method would be a good choice.

My question is, where should I store this static method? Here are a few options I can think of:

  • store it as a static method in the Blog class (maybe smelly because it has nothing to do with the object that class creates?)

  • create a new class for blog static functions (seems excessive)

  • find a better way to go abou开发者_StackOverflow社区t this altogether (yes, but what?)


Create a class/interface called BlogService which will have count method in it. Other methods such as findAll, findById, etc.


Presumably something is managing the multiple Blog objects you create? If not, there should be, and that's where the method belongs - no need for it to be static.


You could also encapsulate the database access in a class and add the new method there.


find a better way to go about this altogether (yes, but what?)

Model View Controller

Transform your Blog to a 'Controller' at this stage

Create a 'Model' that can handle all your database methods

From Class Blog call the Model as you wish (also suggest at this point refactor all database requests to go into Model).

(For a very good Introduction to MVC search for CodeIgniter).


You do not need static method, but static variable. Static method is just function in object that does not take object but only variables from outside.

0

精彩评论

暂无评论...
验证码 换一张
取 消