I have a question, which one of these 2 code block...
# coroutines
h
I have a question, which one of these 2 code blocks is better in term of closing resources and coroutine structure? Thanks in advance
Copy code
override suspend fun getId(email: String): String? = withContext(Dispatchers.IO) {
        dataSource.connection.use { connection ->
            connection.prepareStatement("SELECT id FROM users WHERE email = ?;").use { statement ->
                statement.setString(1, email)
                statement.executeQuery().use { resultSet ->
                    if (resultSet.next()) {
                        resultSet.getString("id")
                    } else {
                        null
                    }
                }
            }
        }
    }
Copy code
override suspend fun getId(email: String): String? {

    var userId: String? = null

    withContext(Dispatchers.IO) {

        val dbconnection = dataSource.connection

        val statement: PreparedStatement = dbconnection.prepareStatement("SELECT * FROM users WHERE email = ?;")

        statement.setString(1, email)

        val resultSet: ResultSet = statement.executeQuery()



        while(resultSet.next()) {
            userId =  resultSet.getString("id")

            statement.close()
            dbconnection.close()

            return@withContext userId
        }



    }
j
The second snippet doesn't use a `try`/`finally` block to close the resources, so they won't be closed if an exception is thrown. The approach with
use
is more correct (at least at a quick glance, I didn't dissect the code).
👍 1
Also, why declare
userId
so far from its usage in the second snippet?
h
I couldn’t remember why
userId
was there actually
Does using
use
affect the testability of the code, since one statement flow into another, I wouldn’t be able to test them separately?
j
Not sure what you mean here. You only have one function, so from the outside
use
will look the same as with
finally
h
I see. Thanks Joffrey