Hello, Im looking for a way to clean this code. I ...
# codereview
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
    }
s
I would probably write an extension function on MongoTemplate that uses a sequence builder to return a
Sequence<T>
, and in your case where you only want one value, do
val streetName = mongoTemplate.executeQueryToSequence(query,STREET_COLLECTION) { document -> document.getValue("name").toString() }.firstOrNull()
.
👍 1
(
executeQueryToSequence
is the extension function I would write.)
p
it looks like
findOne
already exists and is nullable, so something like this would probably be more idiomatic. As a sidenote, this function should probably return
String?
since the lookup is fallible
t
An
apply
might make things a bit cleaner:
Copy code
fun getStreeNameByStreetId(id: String): String {
    val query = Query().apply {
        fields().include("name")
        addCriteria(Criteria.where("_id").`is`(id))
    }
    return mongoTemplate...
}
p
d
@Paul Griffith findOne will shout "None of the following functions can be called with the arguments supplied." and Document: id Unresolved reference: _id Im trying to rewrite it somehow but always coming with errors
p
🤷 I don't have Spring, MongoDB, or your internal classes in front of me, so I'm just guessing. Your original query syntax may work, it's just not very 'nice' Kotlin