Forum Stats

  • 3,758,210 Users
  • 2,251,354 Discussions
  • 7,870,110 Comments

Discussions

What NOT to do when Java Coding

sayalipatil
sayalipatil Member Posts: 4
edited Dec 12, 2018 2:20PM in Java User Groups Discussions

We always hear about the best things to do when you code in Java, but oftentimes, people learn by their mistakes. What are some of the WORST practices that you have seen, and what would you suggest as an alternative to that situation?

What are the types of things that will take you from Java Ninja to Java noob?

Tagged:

Answers

  • eudriscabrera-JavaNet
    eudriscabrera-JavaNet Member Posts: 214 Bronze Badge
    edited Dec 12, 2018 2:20PM

    1. Avoid using the + sign to concatenate String, instead use the concat() method or join method of the String class

    Ex.:

    String concat(String str) method:

    name.concat(" - " ).concat(String.valueOf(age));

    String join(CharSequence delimiter, CharSequence... elements)

    Ex.:

    String.join("-", teamId,name);

    2. Don’t use printStackTrace() statement or similar methods

    Never leave printStackTrace() after finishing your code. Chances are one of your fellow colleague will get one of those stack traces eventually, and have exactly zero knowledge as to what to do with it because it will not have any contextual information appended to it.

    printStackTrace() can be the source of future security flaws. We can use the Java Logging API to handle all the messages of your application.

    Ex.:

      try (PreparedStatement stmt = con.prepareStatement(sqlSelect)) {

            try (ResultSet rs = stmt.executeQuery()) {

                while (rs.next()) {

                }

            }

      

    } catch (SQLException ex) {

        Logger.getLogger(DemoRecursos.class.getName()).log(Level.SEVERE, ex.getMessage());

        throw new ExcepcionJdbcMySQL("Not found");

    }

    3. Handle all the resources of your application. A resource is an object that must be closed after the program is finished with it.

    Make sure you are closing the open connections after its use (database connections, socket connections, etc.) to avoid nested connections

    Use the try-with-resources Statement to handle the resource easily.

    try (PreparedStatement stmt = con.prepareStatement(sqlSelect)) {

            try (ResultSet rs = stmt.executeQuery()) {

                while (rs.next()) {

                }

            }

      

    } catch (SQLException ex) {

        Logger.getLogger(DemoRecursos.class.getName()).log(Level.SEVERE, ex.getMessage());

        throw new ExcepcionJdbcMySQL("Not found");

    }

    The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.