danieljharvey / scala-egg-server

Scala-based levels server for It Is The Egg
0 stars 0 forks source link

Use of def vs. val #3

Open krivachy opened 6 years ago

krivachy commented 6 years ago

def is a method, it always evaluates while val is evaluated once. In com/danieljharvey/eggserver/MySQL.scala:22 you are doing (removed all extra code):

def getLevel (levelID: Int) : Option[String] = {
        try {
            def connection = DriverManager.getConnection(dbOptions("url"), dbOptions("username"), dbOptions("password"))
            var preparedStatement = connection.prepareStatement(sql);
            while (rs.next) {
                connection.close
            }
    }

Everytime there's a connection called it creates a new one, so connection.close is not closing the previous one, but a new one and the previous one is never closed.

krivachy commented 6 years ago

Similar here:

def overZero = (x: Int) => (x > 0)

def means that every time overZero is called it will create for you a function of (x: Int) => (x > 0). Arguable you don't need to always create the function so val would be more appropriate here.