这是一个相当基本的问题,但我对此持怀疑态度。假设我有一个类 A,它有方法 method1、method2、method3、method4 和一个 main 方法。
method2 仅由 method1 调用;method4 仅由 method3 调用。
该解决方案说从 main 调用 method1,从 main 调用 method2,与 method3 和 4 相同。
那么让main方法显式调用method1和method2不是不好的设计吗?如果您在主方法中调用私有方法,即使它们仅依赖于整个类中的单个方法,那么在类中拥有私有方法有什么意义?
从method1调用method2和从method3调用method4不是更干净吗,因为在这两种情况下,后一种方法仅由前者调用?
我认为这是辅助方法的全部意义所在,因此我们能够抽象出不必要的实现细节。
再次为这个问题的简单性道歉,我对java很陌生。
Class A{
public static void main(String[] args){
int x = method1()
if ( x = 0){
//user wants to create a new account
method2()
}
}
private static int method1(){
//some code to check user login credentials in list of users
//if login credentials fail,user is asked if they want to create a new account, if yes,
//method 2 is invoked
//return value is whether the user wants to create a new account or not.
}
private static void method2(){
//creates new account for user and is only invoked by method1.
}
}
在上述情况下,从 method1() 调用 method2() 而不是在 main() 中调用它不是更容易吗?我想知道这种实现方式是否有任何优点或缺点。