在可能的良好实践中声明一个方法是静态的吗?

时间:2013-03-13 05:00:58

标签: java oop coding-style

这是非常不言自明的。在Java中,(以及我认为的所有OO语言)我应该声明实例方法,因为它是唯一的选择,或者通常我们不关心它?

6 个答案:

答案 0 :(得分:3)

当你不需要他们知道类状态来处理某些东西时,方法是静态的。辅助方法就是这种情况的很好的例子。

DateUtils.getDateNowInGMT()

上述方法不需要任何状态来给你答案。下面的那个。

Withdrawer w = new Withdrawer.Builder().account(12545).build();
w.withdraw(100);

您不能在不知道帐号的情况下取款(),这是与提款人相关联的州。您当然可以争辩说这可能是一种静态方法,并且将帐户信息传递给该方法可以解决问题,但由于所有其他方法都需要相同的帐户信息,因此会使其不方便。

答案 1 :(得分:1)

一般来说,如果你使用很多静态方法对单元进行单元测试将会比较困难(人们认为使用Mockito之类的东西来模拟对象比使用类似的东西模拟静态方法更容易Powermock)。

但是,如果您不关心它,并且该方法不使用其所在类的实例数据,您也可以将其设置为静态。

答案 2 :(得分:0)

是。

这是正确的方法,至少我遵循这一点。

例如,实用程序方法应该是静态的。

但是,大多数都需要很多未来的要求和改变,我们今天无法预见所有这些要求。因此,实例应优先于static。除非你遵循一些设计模式。

答案 3 :(得分:0)

因此你可以使用任何类型的实现。但标准应该是要求,而不是可能性。 如果您要在全班级执行某些操作,则应选择静态方法。例如,如果你必须为每个实例生成一些uniqueID,或者你必须初始化实例将使用的任何东西,如display或db-driver。 在其他情况下,如果操作是特定于实例的,则首选实例方法。

答案 4 :(得分:0)

方法只有在它们是静态的时候才应该是静态的。静态方法属于类,而不属于它的特定实例。静态方法只能使用类的其他静态功能。例如,静态方法无法调用实例方法或访问实例变量。如果这对您正在设计的方法有意义,那么使用静态是个好主意。

静态元素,无论是变量还是方法,都会在类加载时加载到内存中,并保持到执行结束或类加载器卸载/重新加载它所属的类。

当我们想要进行不适合我的应用程序的一般面向对象建模的计算时,我使用静态方法。通常的实用方法,例如验证输入数据或保存特定于整个应用程序执行的信息的方法,或者访问外部数据库的访问点,都是很好的选择。

答案 5 :(得分:0)

据我所知, 如果你有这样的代码或逻辑利用或产生与特定对象状态相关的东西,或者简单地说,如果你的side方法中的逻辑用不同的输入集处理不同的对象并产生一些不同的输出,你需要将此方法作为实例方法。 另一方面,如果您的方法具有每个对象通用的逻辑,并且输入和输出不依赖于对象的状态,则应将其声明为静态但不是实例。

Explaination with examples:

    Suppose you are organizing a college party and you have to provide a common coupon to the students of all departments,you just need to appoint a person for distributing a common coupon to students(without knowing about his/her department and roll no.) as he/she(person) approaches to the coupon counter. 
    Now think if you want to give the coupons with different serial numbers according to the departments and roll number of students, the person appointed by you need to get the department name and roll number of student(as input from each and every student)
    and according to his/her department and roll number he will create a separate coupon with unique serial number.

First case is an example where we need static method, if we take it as instance method unnecessary it will increase the burden.

Second case is an example of instance method, where you need to treat each student(in sense of object) separately.

这个例子可能看起来很傻,但我希望它能帮助你清楚地理解这个区别。

相关问题