Java方法设计查询

ano*_*428 2 java

这是一个相当基本的问题,但我对此有点疑虑.假设我有一个A类,它有方法method1,method2,method3,method4和main方法.

method2仅由method1调用; method4仅由method3调用.

解决方案说从main调用method1,从main调用method2,使用method3和4调用method2.

因此,让main方法显式调用method1和method2不是很糟糕的设计吗?如果在main方法中调用私有方法,即使它们仅依赖于整个类中的单个方法,那么在类中使用私有方法有什么意义呢?

从方法3中调用method1和method4中的method2不是更清晰,因为在这两种情况下后一种方法只能由前者调用吗?

我认为这是辅助方法的重点,因此我们能够抽象出不必要的实现细节.

我再次为这个问题的简单性道歉,我对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.
}
Run Code Online (Sandbox Code Playgroud)

}

在上面的例子中,从method1()调用method2()而不是在main()中调用它是不容易的.我想知道这种实现方式是否有任何优点或缺点.

Gre*_*ill 5

一般而言,这是一种分离关注点的练习.首先,让我们给你的方法真实姓名:

checkUserAccount(name, password)
addNewUserAccount(name)
Run Code Online (Sandbox Code Playgroud)

现在,假设您编写checkUserAccount()以便addNewUserAccount()name未找到用户时调用它.在这种情况下,主程序无法调用函数来检查用户凭据.主程序别无选择,只能检查用户帐户,如果找不到用户,则会添加新帐户.如果您决定稍后更改内容,则这不是很灵活.

另一方面,如果您将这些操作分开,那么主程序可以在未找到用户帐户的情况下决定自己做什么.然后,您可以编写类似于您所显示内容的代码:

if (checkUserAccount(name, password)) {
    // great! logged in
} else {
    addNewUserAccount(name);
}
Run Code Online (Sandbox Code Playgroud)

如果您选择添加新功能,则可以轻松修改主程序.例如:

if (checkUserAccount(name, password)) {
    // great! logged in
} else {
    if (newUsersPermitted) {
        addNewUserAccount(name);
    } else {
        System.out.println("Sorry, this system is closed.");
    }
}
Run Code Online (Sandbox Code Playgroud)

当然,真正的登录系统还需要考虑更多细节.