vendredi 5 mars 2021

Pattern to avoid if else chain methods call using kotlin sealed class and enums

I've a question about, how would you handle this case? Imagine that you have to do a validation of an object and that validation should have a sort of importance, in this case we only have 3 validations, each one can result Valid or his own QualityCheck enum value.

This is the method example in kotlin and the validations

sealed class Validation {

    abstract fun validate(bobject: ObjectToCheck): QualityCheck

    object VeryImportantValidation : Validation() {
        override fun validate(bobject: ObjectToCheck): QualityCheck =
            if (isValid(bobject.valueX)) QualityCheck.Valid
            else QualityCheck.VeryImportantInvalid
    }

    object SecondMostImportant : Validation() {
        override fun validate(bobject: ObjectToCheck): QualityCheck =
            if (isValid(bobject.valueNotSoImportant)) QualityCheck.Valid
            else QualityCheck.SecondMostImportantInvalid
    }

   object NotSoImportant : Validation() {
        override fun validate(bobject: ObjectToCheck): QualityCheck =
            if (isValid(bobject.valueNothingImportant)) QualityCheck.Valid
            else QualityCheck.NotSoImportantInvalid
    }
}

fun getQualityCheck(object: ObjectToCheck): QualityCheck =
     if (VeryImportantValidation.validate(object) === QualityCheck.Valid) {
        if (SecondMostImportant.validate(object) === QualityCheck.Valid) {
                NotSoImportant(paymentsRepository.getSystemPayments()).validate(object)
         } else {
                QualityCheck.SecondMostImportantInvalid
        }
      } else {
            QualityCheck.VeryImportantInvalid
      }

I think this is not scalable neither easy to read/understand or modify if we would want to add a new one.

There is any kind to do this elegant and easier to include more validations?

Aucun commentaire:

Enregistrer un commentaire