https://kotlinlang.org logo
Title
a

ahegazy

08/21/2018, 1:03 PM
If you have some validation method like
isValidUsername
or
isValidEmail
, do you feel it’s okay to write this as an extension method to String?
l

louiscad

08/21/2018, 1:07 PM
@ahegazy Here's a way to do it without pollution your auto-completion:
object DataValidation {
    suspend fun String.isValidUsername() = ...
    suspend fun String.isValidEmail() = ...
}

with(DataValidation) {
    someInputUserNameString.isValidUsername()
}
👍 3
suspend
modifier is optional. I added because I assume you're checking into some database that no one has taken the username yet, and same for email
a

Albert

08/21/2018, 1:11 PM
I think adding database behavior in this might become unpredictable. With an extension method I assume that it does not need more information only then the class it is extending
👍 1
d

Denis A

08/21/2018, 1:12 PM
I Use this struture
object Regulars{ val notEmpty = Regex(“^(?!\\s*$).+“) } val tt = Regulars.notEmpty.matches(“some text”)
a

ahegazy

08/21/2018, 1:14 PM
@louiscad Interesting way to do it! didn’t know that we can use
with
with extension methods 🙂
😉 1
l

louiscad

08/21/2018, 1:15 PM
About my
suspend fun
example, if you ever do some db check or alike (that is, not listening to @Albert wise words) that can suspend, be sure to not let this be your only consistency check, or you're opening your system to race conditions otherwise
p

Paul Woitaschek

08/21/2018, 3:58 PM
If I can't scope it to the class using it, I use a top level funcition that just it as an argument.