将大java方法分解为更小的方法

时间:2016-03-03 17:47:32

标签: java

我有这种混乱和混乱的方法,我想分解成更小的方法,但我很难让变量从一种方法转移到另一种方法。我想将其分解为getStudentId()方法和getCourseId()方法,但user_Entered_student_Id导致问题。任何快速提示将不胜感激

      public void signUp(){
    System.out.println("\nSign Up For a Class\n");
    try{
      Scanner input = new Scanner(System.in);
      System.out.println("Enter Student ID: ");  
      String user_entered_student_id = input.nextLine();

      String userEnterId = "student_name" + (user_entered_student_id);

    System.out.println("Enter Class ID from Classes Listed Above to Join: ");

    String selectedClass = input.nextLine();

    student_x_class(selectedClass);
}
    catch (SQLException e) {
        e.printStackTrace();
    }
}


public void student_name(Scanner input,String user_entered_student_id, Statement myStmt, Connection con) {
    try{
    myStmt = con.createStatement();

    String query = ("SELECT student_name FROM ClassSelector.students WHERE student_id = " + user_entered_student_id);

    ResultSet rs;
    rs = myStmt.executeQuery(query);
    while (rs.next()) {
         String userEnterId = rs.getString("student_name");
         System.out.println("Is " + userEnterId + " the correct student? (Y/N)");

         String confirm = input.nextLine();

         if (confirm.equalsIgnoreCase("Y")) {
             getClass();
         }
         else if (confirm.equalsIgnoreCase("N")) {
                System.out.println("Oops, let start over");
         }
         return;
         }
}
    catch (SQLException e) {
        e.printStackTrace();
    }
}

public void getClass(ResultSet rs, Statement myStmt){
        try{
            rs = myStmt.executeQuery("SELECT * FROM ClassSelector.classes");
            while (rs.next()) {
              String avlClasses = rs.getString("class_id") + "\t" + rs.getString("classname") + "\t" + rs.getString("description");
              System.out.println(avlClasses);
            }

          }
        catch (SQLException e) {
            e.printStackTrace();
        }
}

public void student_x_class(Scanner input,String selectedClass, String userEnterId, String user_entered_student_id, ResultSet rs, Statement myStmt, Connection con){
        try{
         rs = myStmt.executeQuery("SELECT * FROM ClassSelector.classes WHERE class_id = " + selectedClass);

          while (rs.next()) {

          String innerJoin = (userEnterId + " has been added to " + rs.getString("classname") + " " + rs.getString("class_id"));
          System.out.println(innerJoin);

          String student_classJoin = "INSERT IGNORE INTO student_x_class" + "(student_id,student_name, class_id, classname)" + "VALUES (?, ?, ?, ?)";
          PreparedStatement pStmt = con.prepareStatement(student_classJoin);
          pStmt.setString(1, user_entered_student_id);
          pStmt.setString(2, userEnterId);
          pStmt.setString(3, rs.getString("class_id"));
          pStmt.setString(4, rs.getString("classname"));
          pStmt.executeUpdate();
          System.out.println("Would you like to enroll " + userEnterId + " into another class? (Y/N)");
            String additionalClass = input.nextLine();
            if(additionalClass.equalsIgnoreCase("Y")){
                signUp();
            }
        }
    }
        catch (SQLException e) {
            e.printStackTrace();
        }
}

3 个答案:

答案 0 :(得分:3)

在Eclipse中,您可以选择一堆代码并执行:

  • 右clic
  • 重构
  • 提取方法......

非常有帮助。但首先要确保在使用它们之前只创建变量,而不是像在方法开头创建并稍后使用的语句。

另外,不要将相同的变量do重用于不同的东西(我没有看到这里的问题,但我还没有完全阅读)并且不创建像“student_classJoin”或“additionalClass”这样无用的变量。 / p>

答案 1 :(得分:2)

首先,您觉得需要将其分解为更小,更易于管理的块,这是一件好事。了解某人何时需要重构是迈向成功的第一步。你可以为此表示祝贺,因为很多人都没有达到这一点。

接下来你要做的就是考虑一下这个方法的作用,然后把它分解成一个单一责任的部分。 (你不需要在头脑中做,你也可以用简单的英语写下来。)

在您的情况下,您的故障看起来像这样:

  • 选择学生
    • 要求学生身份
    • 获取学生数据库
    • 询问这是否是正确的学生,如果不是,则重新开始
  • 选择课程
  • 将学生添加到班级
  • 如果用户愿意,请重复所有这些。

现在,您可以为每个步骤创建一个方法(只是空方法声明,仅此而已),并考虑它们如何组合在一起。你需要传递什么作为参数,该方法应该返回什么。

当你完成这项工作时,你可以填写方法的主体。作为一个额外的技巧,你可以先用虚拟实现来填充方法,然后你可以逐个实现它们。所以你可以这样:

public String askForStudentId() {
    return "1";
}

然后你可以编写其余的代码,并在某些时候返回到它并将其替换为:

public String askForStudentId() {
    Scanner input = new Scanner(System.in);
    System.out.println("Enter Student ID: ");
    return input.nextLine();
}

答案 2 :(得分:1)

您需要检查Java面向对象的概念。特别是封装。 我重构了你的代码,但没有要测试的表和数据,但是你将会了解如何创建不同的函数。带参数和返回类型。代码中需要更多的更正和重构,但我重写了你的代码,让你了解如何将代码分成不同的功能,你也可以在以后使用它们。有一点不在execute方法中编写整个查询,将查询保存在字符串变量中,然后在execute方法中传递它,这是一种更优雅的编写代码的方法。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class NewClass
{

ResultSet rs;
PrepareStatement stmt;
Connection conn;
conn  = DriverManager.getConnection("jdbc:mysql://localhost:3306/ClassSelector?autoReconnect=true&useSSL=false", "root", "Volks91!");

public void signUp()
{

    System.out.println("\nSign Up For a Class\n");

    try
    {
        // getting user input. 

        Scanner input = new Scanner(System.in);
        System.out.println("Enter Student ID: ");
        String user_entered_student_id = input.nextLine();

        /*
         Calling private methid in the class
         @param user_enter_student_id
         @return String userEnterID
         */
        String userEnterId = student_name(user_entered_student_id);

        // getting user input
        System.out.println("Enter Class ID from Classes Listed Above to Join: ");

        String selectedClass = input.nextLine();

        //calling method
        student_x_class(selectedClass);

    } catch (java.sql.SQLException SQL)
    {
        SQL.printStackTrace();
    }

}

private string student_name(String user_entered_student_id)
{
    stmt = con.createStatement();

    String query = "SELECT student_name FROM ClassSelector.students WHERE student_id = " + user_entered_student_id;

    rs = stmt.executeQuery(query);

    while (rs.next())
    {
        String userEnterId = rs.getString("student_name");
        System.out.println("Is " + userEnterId + " the correct student? (Y/N)");

        String confirm = input.nextLine();

        if (confirm.equalsIgnoreCase("Y"))
        {
            getClass();

        } else if (confirm.equalsIgnoreCase("N"))
        {
            System.out.println("Oops, let start over");
            return;
        }
    }

    return userEnterId;
}

private void getClass()
{
    rs = stmt.executeQuery("SELECT * FROM ClassSelector.classes");
    while (rs2.next())
    {
        String avlClasses = rs.getString("class_id") + "\t" + rs.getString("classname") + "\t" + rs.getString("description");
        System.out.println(avlClasses);
    }
}

private void student_x_class(String selectedClass)
{
    rs = stmt.executeQuery("SELECT * FROM ClassSelector.classes WHERE class_id = " + selectedClass);

    while (rs.next())
    {

        String innerJoin = (userEnterId + " has been added to " + rs.getString("classname") + " " + rs.getString("class_id"));
        System.out.println(innerJoin);

        String student_classJoin = "INSERT IGNORE INTO student_x_class" + "(student_id,student_name, class_id, classname)" + "VALUES (?, ?, ?, ?)";
        PreparedStatement pStmt = conn.prepareStatement(student_classJoin);
        Stmt.setString(1, user_entered_student_id);
        Stmt.setString(2, userEnterId);
        Stmt.setString(3, rs.getString("class_id"));
        Stmt.setString(4, rs.getString("classname"));
        Stmt.executeUpdate();
        System.out.println("Would you like to enroll " + userEnterId + " into another class? (Y/N)");
        String additionalClass = input.nextLine();
        if (additionalClass.equalsIgnoreCase("Y"))
        {
            signUp();
        }
    }
}

}