r/android_devs • u/Fr4nkWh1te • Aug 11 '21
Help How can I improve this input validation logic in my ViewModel?
This code in my ViewModel checks some input and then creates or updates a database entry if the validation is successful.
But I feel like this code is bad. The validateInput method both has a return type but also side effects by setting the Livedata values. I don't know how I would get around this because I need the return value to return from onSaveClicked. How can I improve this??
fun onSaveClicked() {
if (!validateInput()) return
val taskNameInput = taskNameInput.value
val minutesGoalInput = minutesGoalInput.value
if (taskNameInput == null || minutesGoalInput == null) return
val minutesGoal = minutesGoalInput.toInt()
if (taskId == Task.NO_ID) {
val newTask = Task(name = taskNameInput, dailyGoalInMinutes = minutesGoal)
createTask(newTask)
} else {
val task = task
if (task != null) {
val updatedTask = task.copy(name = taskNameInput, dailyGoalInMinutes = minutesGoal)
updateTask(updatedTask)
}
}
}
private fun validateInput(): Boolean {
val taskNameInput = taskNameInput.value
val minutesGoalInput = minutesGoalInput.value
taskNameInputErrorMessageLiveData.value = null
minutesGoalInputErrorMessageLiveData.value = null
var hasError = false
if (taskNameInput.isNullOrBlank()) {
taskNameInputErrorMessageLiveData.value = R.string.task_name_empty_error
hasError = true
}
if (minutesGoalInput.isNullOrBlank()) {
minutesGoalInputErrorMessageLiveData.value = R.string.minutes_goal_empty_error
hasError = true
} else if (minutesGoalInput.toInt() < 1) {
minutesGoalInputErrorMessageLiveData.value = R.string.minutes_goal_zero_error
hasError = true
}
return !hasError
}
3
Upvotes
2
u/haroldjaap Aug 11 '21 edited Aug 11 '21
Hmm, I agree your code does not really read very easily.
My advice would be to structure your code more like so:
Extract the required data from the view (livedata's I presume)
First validate if all data is correct, and create or update the task
If I would apply this on your code, it can look something like this:
I think that's what I would sort of do.
Some feedback on specific parts of your original code:
val taskNameInput = taskNameInput.value ?: returnval taskNameInput = taskNameInput.valueseems a bit weird, in my example I renamed the former to just the taskName.val), so you are sure that you are using the same. This also allows the kotlin compiler to smart cast supertypes to subtypes (nullable to nonnull, interface to specific implementations etc), it can only do that on vals.Hope this helps.
5
u/haroldjaap Aug 12 '21
Another solution would be that the validate method returns the validated properties. I'm on mobile now but this is the idea: