Improvements in my code.

  • (2 Pages)
  • +
  • 1
  • 2

24 Replies - 1300 Views - Last Post: 30 May 2012 - 09:59 PM Rate Topic: -----

#1 ILoveJava  Icon User is offline

  • D.I.C Regular

Reputation: 29
  • View blog
  • Posts: 389
  • Joined: 12-March 12

Improvements in my code.

Posted 29 May 2012 - 05:15 AM

Hey guys. I have successfully built a program that has capabilities to access a database, log in to an account, add members to a database, also edit and delete it. It can generate a full report of all members in the database out to a .txt file, which can also be viewed within the program inside a JTextArea. I've created a .jar for it. Upon loading the log in class will display, prompting for a username & password as listed in the database, if correct, it will dispose, and open up the Panel, where you can access the Add Member, Edit Member and View Report panels, also with exit button. I think I'm done with the program, but I was just wondering, if there was any way I could improve my code? All of my classes are as below. Any criticism will be taken well. :P
// Login.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

import java.sql.*;

public class Login extends JFrame {

  JTextField _username = new JTextField(10);
  JPasswordField _password = new JPasswordField(10);

  JButton _login = new JButton("Login");
  JButton _exit = new JButton("Exit");

  Toolkit kit = Toolkit.getDefaultToolkit();
  Dimension screenSize = kit.getScreenSize();
  int screenHeight = (int)screenSize.getHeight();
  int screenWidth = (int)screenSize.getWidth();

  public Login() {
    super("Login to panel");
    setLayout(new GridLayout(3,2,1,1));

    add(new JLabel("Username:"));
    add(_username);

    add(new JLabel("Password:"));
    add(_password);

    add(_login);
      _login.addActionListener(new LoginListener());
    add(_exit);
      _exit.addActionListener(new ExitListener());

    setSize(250, 100);
    //setLocation(screenWidth/3, screenHeight/3);
    setLocation(500, 400);
    setResizable(false);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
  }

  public static void main(String[] args) {
    new Login();
  }

  public class LoginListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      Connection con;
      Statement stmt;
      ResultSet rs;

      try {
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        con = DriverManager.getConnection("jdbc:odbc:collegesys","root","root");

        String usernameT = _username.getText();
        String passwordT = _password.getText();

        stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);

        String sql = "SELECT * FROM main WHERE username = '" + usernameT + "';";
        rs = stmt.executeQuery(sql);

        PreparedStatement loginTime = con.prepareStatement("UPDATE `main` WHERE ID = ?");

        if(rs.next()) {
          if(passwordT.equals(rs.getString("password"))) {
            dispose();
            new Panel();
          } else {
            JOptionPane.showMessageDialog(null, "Invalid password!");
          }
        } else {
          JOptionPane.showMessageDialog(null, "Username not found!");
        }
      } catch(SQLException sqle) {
        sqle.printStackTrace();
      } catch(ClassNotFoundException cnfe) {
        cnfe.printStackTrace();
      }
    }
  }

  public class ExitListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      dispose();
      System.exit(0);
    }
  }
}

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Panel extends JFrame {

  JButton addMember = new JButton("Add Members");
  JButton editMember = new JButton("Edit Members");
  JButton viewReport = new JButton("View Report");
  JButton exit = new JButton("Exit");

  public Panel() {
    super("The Panel");
    setLayout(new GridLayout(1,4));

    add(addMember);
      addMember.addActionListener(new AddMemberListener());
    add(editMember);
      editMember.addActionListener(new EditMemberListener());
    add(viewReport);
      viewReport.addActionListener(new ReportListener());
    add(exit);
      exit.addActionListener(new ExitListener());

    setSize(700, 100);
    setLocation(300, 600);
    setResizable(false);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
  }

  public static void main(String[] args) {
    new Panel();
  }

  public class AddMemberListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      new Main();
    }
  }

  public class EditMemberListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      new EditMember();
    }
  }

  public class ReportListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      new Report();
    }
  }

  public class ExitListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      dispose();
      System.exit(0);
    }
  }
}

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

import java.io.*;
import java.util.*;

import java.sql.*;

public class Main extends JFrame {
  private static final int HEIGHT = 200;
  private static final int WIDTH = 406;

  String[] positions = {"", "Trainee", "Writer", "Moderator", "Administrator"};

  JButton _addToFile = new JButton("Add Member");
  JButton _clearFields = new JButton("Clear Fields");
  JButton _generate = new JButton("Generate");
  JButton _exitProgram = new JButton("Exit");

  JTextField _id = new JTextField(10);
  JTextField _name = new JTextField(10);
  JTextField _username = new JTextField(10);
  JTextField _password = new JPasswordField(10);

  JComboBox _position = new JComboBox(positions);

  public Main() {
    super("Administration Panel");
    Container panel = getContentPane();
    setLayout(new GridLayout(7,1,1,1));

    _id.setEditable(false);
    _id.setText(getId());

    add(new JLabel("ID:"));
    add(_id);
    add(new JLabel("Name:"));
    add(_name);
        _name.addActionListener(new NameListener());
    add(new JLabel("Username:"));
    add(_username);
    add(new JLabel("Password:"));
    add(_password);
    add(new JLabel("Position:"));
    add(_position);

    add(_addToFile);
      _addToFile.addActionListener(new AddToFileListener());
    add(_clearFields);
      _clearFields.addActionListener(new ClearListener());
    add(_generate);
      _generate.addActionListener(new GeneraterListener());
    add(_exitProgram);
      _exitProgram.addActionListener(new ExitProgramListener());

    setSize(WIDTH, HEIGHT);
    setResizable(false);
    setLocation(500, 300);
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    setVisible(true);
  }

  public static void main(String[] args) {
    new Main();
  }

  public class ClearListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      _id.setText(getId());
      _name.setText("");
      _username.setText("");
      _password.setText("");
      _position.setSelectedIndex(0);
    }
  }

  public class NameListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
    String fname = "";
    String lname = "";
      Scanner nameScan = new Scanner(_name.getText());
        while(nameScan.hasNext()) {
          fname = nameScan.next();
          lname = nameScan.next();
        }
      _username.setText(fname.toLowerCase() + "" + _id.getText());
      _password.setText(lname.toLowerCase() + "" + _id.getText());

      if(_name.getText().startsWith("Wri")) {
        _position.setSelectedIndex(2);
      } else if(_name.getText().startsWith("Mod")) {
        _position.setSelectedIndex(3);
      } else if(_name.getText().startsWith("Adm")) {
        _position.setSelectedIndex(4);
      } else {
        _position.setSelectedIndex(1);
      }
    }
  }

  public class AddToFileListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
    Connection con;
     try {
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      con = DriverManager.getConnection("jdbc:odbc:collegesys","root","root");

      PreparedStatement pstmt = con.prepareStatement("INSERT INTO `main` (`id`, `name`, `username`, `password`, `position`) VALUES (?, ?, ?, ?, ?)");
        pstmt.setInt(1, Integer.parseInt(_id.getText()));
        pstmt.setString(2, _name.getText());
        pstmt.setString(3, _username.getText());
        pstmt.setString(4, _password.getText());
        pstmt.setString(5, _position.getSelectedItem().toString());

      if(_id.getText().equals("") ||
         _name.getText().equals("") ||
         _username.getText().equals("") ||
         _password.getText().equals("") ||
         _position.getSelectedIndex() == 0) {
        JOptionPane.showMessageDialog(null, "Error in fields");
      } else {
        if(_position.getSelectedIndex() == 4) {
          int result = JOptionPane.showConfirmDialog(null, "Are you sure you would like to make " + _name.getText() + " an admin?", "Confirmation", JOptionPane.YES_NO_OPTION);
          if(result == JOptionPane.YES_OPTION) {
            pstmt.execute();
          }
        } else {
          pstmt.execute();
        }
      }
            /*if(_position.getSelectedIndex() == 0) {
        JOptionPane.showMessageDialog(null, "Position cannot be null");
      } else if(_id.getText().equals("")) {
        JOptionPane.showMessageDialog(null, "ID cannot be null");
      }*/
      _id.setText(getId());
      _name.setText("");
      _username.setText("");
      _password.setText("");
      _position.setSelectedIndex(0);

     } catch(Exception IOE) {
      IOE.printStackTrace();
     }
    }
  }

  public String getId() {
    Connection con;
    Statement stmt;
    ResultSet rs;

    String returnId = "";
    int idA = 0;

    try {
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      con = DriverManager.getConnection("jdbc:odbc:collegesys","root","root");

      stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
      rs = stmt.executeQuery("SELECT MAX(id) FROM main");

      while(rs.next()) {
        idA = rs.getInt(1);
      }
        ++idA;
      returnId = Integer.toString(idA);
      con.close();
    } catch(Exception e) {
      e.printStackTrace();
    }
    return returnId;
  }

  private class GeneraterListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      Connection con;
      Statement stmt;
      ResultSet rs;

      try {
        FileWriter fw = new FileWriter(new File("report.txt"));
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        con = DriverManager.getConnection("jdbc:odbc:collegesys","root","root");

        stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
        rs = stmt.executeQuery("SELECT * FROM main");

        fw.write("Report generated: \r");
        fw.write("     [ID]: Full Name | Username | Password | Position");
        fw.write("\r+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
        while(rs.next()) {
          fw.write("\r|    [" + rs.getInt("id") + "]: " + rs.getString("name") + " | " + rs.getString("username") + " | " + rs.getString("password") + " | " + rs.getString("position"));
        }
        fw.write("\r+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
        fw.close();
        con.close();
      } catch(Exception ie) {
        JOptionPane.showMessageDialog(null, "Something has happened! \n" + ie);
      }
    }
  }

  private class ExitProgramListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      dispose();
    }
  }
}

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

import java.sql.*;

import java.util.ArrayList;

import java.io.PrintWriter;
import java.io.FileWriter;
import java.io.File;
import java.io.IOException;

public class EditMember extends JFrame {

  String[] positions = {"", "Trainee", "Writer", "Moderator", "Administrator"};

  JComboBox _id = new JComboBox(getId());
  JComboBox _position = new JComboBox(positions);

  JTextField _name = new JTextField(10);
  JTextField _username = new JTextField(10);
  JPasswordField _password = new JPasswordField(10);

  JButton edit = new JButton("Edit Member");
  JButton delete = new JButton("Delete Member");
  JButton generate = new JButton("Generate Report");
  JButton exit = new JButton("Exit");
  JButton load = new JButton("Load in");

  Toolkit kit = Toolkit.getDefaultToolkit();
  Dimension screenSize = kit.getScreenSize();
  int screenHeight = (int)screenSize.getHeight();
  int screenWidth = (int)screenSize.getWidth();

  public EditMember() {
    super("Edit Member");
    setLayout(new GridLayout(7,1,1,1));

    add(_id);
    add(load);
      load.addActionListener(new LoadInListener());

    add(new JLabel("Name:"));
    add(_name);

    add(new JLabel("Username:"));
    add(_username);

    add(new JLabel("Password:"));
    add(_password);

    add(new JLabel("Position:"));
    add(_position);

    add(edit);
      edit.addActionListener(new EditListener());
    add(delete);
      delete.addActionListener(new DeleteListener());
    add(generate);
      generate.addActionListener(new GeneraterListener());
    add(exit);
      exit.addActionListener(new ExitListener());

    setSize(406, 200);
    setResizable(false);
    setLocation(500, 300);
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    setVisible(true);
  }

  public static void main(String[] args) {
    new EditMember();
  }

  public Object[] getId() {
    Connection con;
    Statement stmt;
    ResultSet rs;

    //Object[] returnId;
    ArrayList<Object> returnId = new ArrayList<Object>();
    try {
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      con = DriverManager.getConnection("jdbc:odbc:collegesys","root","root");

      stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
      rs = stmt.executeQuery("SELECT `id` FROM main");

      while(rs.next()) {
        returnId.add(rs.getObject("id"));
      }

      con.close();
    } catch(Exception e) {
      e.printStackTrace();
    }
    return returnId.toArray(new Object[returnId.size()]);
  }

  public class EditListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      edit();
    }
  }

  public class ExitListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      dispose();
    }
  }

  public class LoadInListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      String giveId = _id.getSelectedItem().toString();

      populate(giveId);
    }
  }

  public class DeleteListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      delete();
    }
  }

  private class GeneraterListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      Connection con;
      Statement stmt;
      ResultSet rs;

      try {
        FileWriter fw = new FileWriter(new File("report.txt"));
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        con = DriverManager.getConnection("jdbc:odbc:collegesys","root","root");

        stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
        rs = stmt.executeQuery("SELECT * FROM main");

        fw.write("Report generated: \r");
        fw.write("     [ID]: Full Name | Username | Password | Position");
        fw.write("\r+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
        while(rs.next()) {
          fw.write("\r|    [" + rs.getInt("id") + "]: " + rs.getString("name") + " | " + rs.getString("username") + " | " + rs.getString("password") + " | " + rs.getString("position"));
        }
        fw.write("\r+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
        fw.close();
        con.close();
      } catch(Exception ie) {
        JOptionPane.showMessageDialog(null, "Something has happened! \n" + ie);
      }
    }
  }

  public void edit() {
    Connection con;
    Statement stmt;
    ResultSet rs;

    try {
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      con = DriverManager.getConnection("jdbc:odbc:collegesys", "root", "root");

      stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);

      PreparedStatement prep = con.prepareStatement("UPDATE `main` SET `name` = ?, `username` = ?, `password` = ?, `position` = ? WHERE `ID` = ?");
        prep.setString(1, _name.getText());
        prep.setString(2, _username.getText());
        prep.setString(3, _password.getText());
        prep.setString(4, _position.getSelectedItem().toString());
        prep.setInt(5, (int)_id.getSelectedItem());

      prep.executeQuery();
    } catch(SQLException sqle) {
      StringBuilder sb = new StringBuilder();
      StackTraceElement[] st = sqle.getStackTrace();
      for(StackTraceElement s : st) {
        sb.append(s);
        sb.append('\n');
      }
      try {
        FileWriter fw = new FileWriter(new File("Error_Report.txt"));
        fw.write(sb.toString());
        fw.close();
      } catch(IOException ioe) {
        ioe.printStackTrace();
      }
    } catch(ClassNotFoundException cnfe) {
      StringBuilder sb = new StringBuilder();
      StackTraceElement[] st = cnfe.getStackTrace();
      for(StackTraceElement s : st) {
        sb.append(s);
        sb.append('\n');
      }
      try {
        FileWriter fw = new FileWriter(new File("Error_Report.txt"));
        fw.write(sb.toString());
        fw.close();
      } catch(IOException ioe) {
        ioe.printStackTrace();
      }
    }
  }

  public void delete() {
    Connection con;
    Statement stmt;
    ResultSet rs;
    int idA;
    String name, username, password, position;

    try {
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      con = DriverManager.getConnection("jdbc:odbc:collegesys","root","root");

      stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
      PreparedStatement pstmt = con.prepareStatement("DELETE FROM `main` WHERE ID = ?");
        pstmt.setInt(1, (int)_id.getSelectedItem());
        pstmt.execute();
        _id.removeItem(_id.getSelectedItem());
        _name.setText("");
        _username.setText("");
        _password.setText("");
        _position.setSelectedIndex(0);
    } catch(Exception e) {
      e.printStackTrace();
    }
  }

  public void populate(String a) {
    Connection con;
    Statement stmt;
    ResultSet rs;
    int idA;
    String name, username, password, position;

    try {
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      con = DriverManager.getConnection("jdbc:odbc:collegesys","root","root");

      stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
      rs = stmt.executeQuery("SELECT * FROM main");

      while(rs.next()) {
        idA = rs.getInt("id");
        name = rs.getString("name");
        username = rs.getString("username");
        password = rs.getString("password");
        position = rs.getString("position");
        if(Integer.parseInt(a) == idA) {
          _name.setText(name);
          _username.setText(username);
          _password.setText(password);
          _position.setSelectedItem(position);
        }
      }
    } catch(Exception e) {
      e.printStackTrace();
    }
  }
}

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileNotFoundException;

public class Report extends JFrame {
  private static final int HEIGHT = 300;
  private static final int WIDTH = 506;

  JTextArea report = new JTextArea(14, 45);
  JScrollPane scrollPane = new JScrollPane(report);

  JButton load = new JButton("Load File");
  JButton exit = new JButton("Exit");

  public Report() {
    super("Report Viewer");
    setLayout(new FlowLayout());

    report.setEditable(false);

    add(scrollPane);
    add(load);
      load.addActionListener(new LoadListener());
    add(exit);
      exit.addActionListener(new ExitListener());

    setSize(WIDTH, HEIGHT);
    setResizable(false);
    setLocation(480, 280);
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    setVisible(true);
  }

  public static void main(String[] args) {
    new Report();
  }

  public class LoadListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
     try {
      FileReader reader = new FileReader("report.txt");
      BufferedReader br = new BufferedReader(reader);
      report.read(br, null);
      br.close();
     } catch(IOException ioe) {
      ioe.printStackTrace();
     }
    }
  }

  public class ExitListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      dispose();
    }
  }
}


Is This A Good Question/Topic? 0
  • +

Replies To: Improvements in my code.

#2 Gungnir  Icon User is offline

  • Your Imaginary Friend

Reputation: 152
  • View blog
  • Posts: 527
  • Joined: 21-May 11

Re: Improvements in my code.

Posted 29 May 2012 - 06:51 AM

I'm not sure what your question is. :P

Could your code be more conventional? Probably.
___

Your tab spaces are 2 spaces wide. Convention is 4 or 8 spaces.
___

Your statement spacing is as correct as it's ever going to be (it's fine).
___

You have naming conventions pretty much down. Don't go crazy with putting underscores at the start of variables. That's usually reserved for post-defined keyword methods.

Just stick to the convention of:
ClassName, methodName, variableName, CONSTANT_NAME
___

One issue I have is with this line:
String[] positions = {"", "Trainee", "Writer", "Moderator", "Administrator"}

I'll admit, when I was must less experienced I used to do this too (having element 0 as a control value). It's not a very good habit to get into.
___

new GridLayout(7,1,1,1) It's tough to read parameters that are set out like this. Just like in the English language a space should follow the comma.
______


To answer your question...
Is there room for improvement? Yes, there is. But all in all it looks like a well coded (and readable) project. Just pat yourself on the back and brush up on convention before your next project. Because there's ALWAYS room for improvement.

See Coding Conventions for the Java Language

This post has been edited by Gungnir: 29 May 2012 - 06:53 AM

Was This Post Helpful? 3
  • +
  • -

#3 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Improvements in my code.

Posted 29 May 2012 - 07:17 AM

A complete lack of simple comments
This code would never pass QA at my place

String[] positions is declared in two places. Change one you are better not to forget to change the other one.
Was This Post Helpful? 3
  • +
  • -

#4 ILoveJava  Icon User is offline

  • D.I.C Regular

Reputation: 29
  • View blog
  • Posts: 389
  • Joined: 12-March 12

Re: Improvements in my code.

Posted 29 May 2012 - 05:09 PM

Gungnir, the only reason I use the "_" infront of some variables, is when I'm declaring text fields, buttons, etc as its my way of not creating another variable, with the exact name.

And thank you pbl, I should probably get into the habit of annotating my work if I ever get want to get a job doing this.
Was This Post Helpful? 0
  • +
  • -

#5 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10387
  • View blog
  • Posts: 38,439
  • Joined: 27-December 08

Re: Improvements in my code.

Posted 29 May 2012 - 05:18 PM

Quote

Gungnir, the only reason I use the "_" infront of some variables, is when I'm declaring text fields, buttons, etc as its my way of not creating another variable, with the exact name.

This is bad practice. Name them something more specific to describe what they are/do. That way, you won't have to scroll up to see what type the Object is.
Was This Post Helpful? 1
  • +
  • -

#6 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Improvements in my code.

Posted 29 May 2012 - 05:20 PM

used to be (or is still) a C++ convention
Was This Post Helpful? 0
  • +
  • -

#7 ILoveJava  Icon User is offline

  • D.I.C Regular

Reputation: 29
  • View blog
  • Posts: 389
  • Joined: 12-March 12

Re: Improvements in my code.

Posted 29 May 2012 - 06:17 PM

Using an underscore before variables is a C++ convention? Never knew that.
Was This Post Helpful? 0
  • +
  • -

#8 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Improvements in my code.

Posted 29 May 2012 - 07:32 PM

View PostILoveJava, on 29 May 2012 - 09:17 PM, said:

Using an underscore before variables is a C++ convention? Never knew that.

My first C++ book 25 years ago was hot on that convention to identify private member.

Certain coding conventions state that underscores should be used to prefix all instance variables, for improved reading and program understanding.
http://stackoverflow...n-c-c-variables

Here is a msdn one.
http://blogs.msdn.co...2/05/67687.aspx

But I guess there are almost as many conventions as there are programmers.
Was This Post Helpful? 0
  • +
  • -

#9 ILoveJava  Icon User is offline

  • D.I.C Regular

Reputation: 29
  • View blog
  • Posts: 389
  • Joined: 12-March 12

Re: Improvements in my code.

Posted 29 May 2012 - 07:45 PM

And everybody is taught different to others. It's just a matter of readability, and well, if it works.
Was This Post Helpful? 1
  • +
  • -

#10 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Improvements in my code.

Posted 29 May 2012 - 07:51 PM

View PostILoveJava, on 29 May 2012 - 10:45 PM, said:

And everybody is taught different to others. It's just a matter of readability, and well, if it works.

Not really. There is a kind of snobism between programmers of different languages.
Your Java code with _ will not get credibility (that it might desserve) just because your _ will denote a C++ programmer that is just beginning in Java or refuse to respect Java conventions :)

And in real world, QA would return you to your editor (at leat I would) :)
Was This Post Helpful? 0
  • +
  • -

#11 ILoveJava  Icon User is offline

  • D.I.C Regular

Reputation: 29
  • View blog
  • Posts: 389
  • Joined: 12-March 12

Re: Improvements in my code.

Posted 29 May 2012 - 08:06 PM

Funny thing is, I was taught to use "_" to denote private global variables when we started Java. And well, guess I'll need to conform them. :(
Was This Post Helpful? 0
  • +
  • -

#12 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Improvements in my code.

Posted 29 May 2012 - 08:13 PM

View PostILoveJava, on 29 May 2012 - 11:06 PM, said:

Funny thing is, I was taught to use "_" to denote private global variables when we started Java.

Nerver heard of that
Global variables are not a good coding practice and Java does not hava a global reserved word as C/C++

So they are declare static or in a singleton.

You do what ever you want, it is just a courtousy to the programmer communauty you are dealing with like in this forum.
Was This Post Helpful? 1
  • +
  • -

#13 cfoley  Icon User is offline

  • Cabbage
  • member icon

Reputation: 1940
  • View blog
  • Posts: 4,027
  • Joined: 11-December 07

Re: Improvements in my code.

Posted 30 May 2012 - 02:51 AM

Something in Java that has always irritated me is how to properly write a setter. I think an underscore convention could help but it would never be accepted. Say we have a private int size;


// single letter variable names are bad style
public void setSize(int s) {
  size = s;
}

// duplicate variable names are bad style
public void setSize(int size) {
  this.size = size;
}


// verbose variable names are verbose and don't really add anything
public void setSize(int newSize) {
  size = newSize;
}

// Underscore would be useful here but would never be accepted
public void setSize(int _size) {
  size = _size;
}


There is something minor wrong with or at least something I don't like about all these examples. My favourite when I'm writing code for something this small is the single letter variant. But I know I don't like using other people's interfaces when they do this.
Was This Post Helpful? 0
  • +
  • -

#14 Gungnir  Icon User is offline

  • Your Imaginary Friend

Reputation: 152
  • View blog
  • Posts: 527
  • Joined: 21-May 11

Re: Improvements in my code.

Posted 30 May 2012 - 03:09 AM

View Postcfoley, on 30 May 2012 - 02:51 AM, said:

// Underscore would be useful here but would never be accepted
public void setSize(int _size) {
  size = _size;
}



That's a good point. I use that when I'm coding in C++, but for some reason in Java I don't have an issue with distinguishing between size, this.size, and super.size. I guess it's just the way that I learned.
Was This Post Helpful? 1
  • +
  • -

#15 ILoveJava  Icon User is offline

  • D.I.C Regular

Reputation: 29
  • View blog
  • Posts: 389
  • Joined: 12-March 12

Re: Improvements in my code.

Posted 30 May 2012 - 03:23 AM

Personally, I'm not looking forward to finishing University and getting into the programming work force. When I started programming, my brackets, always follow the method like this
public static void main(String[] args) {

}

But 98% of programmers I have met/spoken to, will do it on the next line like this
public static void main(String[] args)
{

}

Am I the only one who doesn't like the look of this? As much as programming is all about readability and actual function, I personally like the aesthetics of the source code.
If I'm lurking the board, and there is an extremely sloppy source code posted, even if I don't know how to fix the problem, I will take the code, post it into my IDE, and clean it up. And again, am I the only one who does this? Haha.
Was This Post Helpful? 1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2