Tips for making a cleaner code

Asked

Viewed 44 times

0

Starting in java programming and would like to know how to make code cleaner, this is an example of a recent code I created

public void chamarButton(JTextField login, JTextField senha){

        String pass = "";
        Connection connection = Connectionfactory.getConnection();
        try{
            String sqlLogin = "select senha from administrador where login = " + "'"+login.getText()+"'";
            Statement statement = connection.createStatement();
            ResultSet resultSetlogin = statement.executeQuery(sqlLogin);
            while(resultSetlogin.next()){
               pass = resultSetlogin.getString(1);
                System.out.println(resultSetlogin.getString(1));
            }
             if (pass.equals(senha.getText())){
                 JOptionPane.showMessageDialog(new JFrame(),"SUCESSO");
                 this.ativo = true;
             }else if(pass == "")
                 JOptionPane.showMessageDialog(new JFrame(),"Login errado");
             else
                 JOptionPane.showMessageDialog(new JFrame(), "senha errada");
                  resultSetlogin.close();
        }catch (SQLException e){
            JOptionPane.showMessageDialog(new JFrame(),"ERRO AO LOGAR");
            e.printStackTrace();```

Como deixar ele mais limpo por exemplo
  • To compare strings is used equals instead of ==, then it would be if ("".equals(pass))

1 answer

0

  1. Your method takes Jtextfields, which are GUI components, and makes a query in the bank. Ah, and do login and password authentication. Ah! And it warns with graphic component if it is wrong. It has nothing to do with one thing with the other. I suggest doing one thing at a time (it is not a rule, that some say it is, but the point is that the less thing does the cleaner it gets): for example receiving strings (it is better in this case because they are more generic than Jtextfields), consulting the bank, and outside the method (or in another object) authenticate and warn if error.

  2. Study about SQL Injection and the difference between Statement and Preparedstatement.

  3. Study about Try-with-Resources.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.