Hello, Im looking for a way to clean this code. I ...
# getting-started
d
Hello, Im looking for a way to clean this code. I dont like this part of init empty String, is there other way write this?
Copy code
fun getStreetNameByStreetId(id: String): String {
        val query = Query()
        query.fields().include("name")
        query.addCriteria(Criteria.where("_id").`is`(id))
        var streetName = ""
        mongoTemplate.executeQuery(
            query, STREET_COLLECTION
        ) { document: Document ->
            streetName = document.getValue("name").toString()
        }
        return streetName
    }
j
I don't know the MongoTemplate API, is this call synchronous or asynchronous? Is the callback guaranteed to be called in-place once? At least once? It looks like an asynchronous call but maybe it's not, I guess it depends on the flavor of mongoDB lib you're using. If it is asynchronous, the code here shouldn't even work because
streetName
might not be updated before you return from the enclosing function.
If the call is synchronous (which should be the case if this code works), I guess it's not worth wrapping it as a suspend function. But I think you should deal with errors more cleanly by initializing to null first, and then checking for null when returning (for instance using an elvis operator).
🙏 1
m