Created
January 25, 2018 21:05
-
-
Save kassisdion/a51598637cf16feeb81face622dd7f44 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface BaseRxValidator<T> extends Function<T, Boolean> { | |
} | |
public class StringValidator implements BaseRxValidator<String> { | |
public static final int EMPTY = 0; | |
public static final int TOO_SHORT = 1; | |
@Retention(RetentionPolicy.SOURCE) | |
@IntDef({EMPTY, TOO_SHORT}) | |
public @interface Error {} | |
@Error | |
public int error; | |
@Override | |
@NonNull | |
public Boolean apply(@NonNull String target) throws Exception { | |
if (target.isEmpty()) { | |
error = EMPTY; | |
return false; | |
} else if (target.length() < 2) { | |
error = TOO_SHORT; | |
return false; | |
} | |
return true; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ReusableValidator { | |
abstract class Validator<in T> { | |
data class Result(val isValid: Boolean, val error: Long?) | |
abstract fun isValid(target: T): Result | |
} | |
class StringValidator : Validator<String>() { | |
companion object { | |
const val EMPTY = 0L | |
const val TOO_SHORT = 1L | |
@Retention(AnnotationRetention.SOURCE) | |
@IntDef(EMPTY, TOO_SHORT) | |
annotation class Error | |
} | |
override fun isValid(target: String): Result { | |
return when { | |
target.isEmpty() -> Result(false, EMPTY) | |
target.length < 2 -> Result(false, TOO_SHORT) | |
else -> Result(true, null) | |
} | |
} | |
} | |
} | |
class NonReusableValidator { | |
abstract class Validator<out T>(val target: T) { | |
data class Result(val isValid: Boolean, val error: Long?) | |
abstract val isValid: Result | |
} | |
class StringValidator(target: String) : Validator<String>(target) { | |
companion object { | |
const val EMPTY = 0L | |
const val TOO_SHORT = 1L | |
@Retention(AnnotationRetention.SOURCE) | |
@IntDef(EMPTY, TOO_SHORT) | |
annotation class Error | |
} | |
override val isValid: Result | |
get() { | |
return when { | |
target.isEmpty() -> Result(false, EMPTY) | |
target.length < 2 -> Result(false, TOO_SHORT) | |
else -> Result(true, null) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment