miqbaldc
09/12/2021, 10:36 PMobject Filter {
private val filters = StringBuilder()
private fun append(value: String?) = apply {
if (filters.isNotBlank()) filters.append(" and ")
if (!value.isNullOrBlank()) filters.append(value)
}
fun jobCategoryId(value: String?) = apply {
append("job_category_id" eq value)
}
fun isFeatured(value: Boolean) = apply {
append("is_featured" eq "$value")
}
override fun toString(): String = filters.toString()
}
// caller:
val filter = Filter
.jobCategoryId("job-1")
isFeatured(true)
2️⃣
object Filter {
private val filters = StringBuilder()
private fun append(value: String?) = apply {
if (filters.isNotBlank()) filters.append(" and ")
if (!value.isNullOrBlank()) filters.append(value)
}
override fun toString(): String = filters.toString()
}
fun Filter.jobCategoryId(value: String?) = apply {
append("job_category_id" eq value)
}
fun Filter.isFeatured(value: Boolean) = apply {
append("is_featured" eq "$value")
}
// caller:
import com.company.filter.jobCategoryId
import com.company.filter.isFeatured
val filter = Filter
.jobCategoryId("job-1")
.isFeatured(true)
object
to have a similar behavior as static class, so we can directly calls the class without having to instantiate first, e.g:
val filter = Filter() // instantiation
.x()
// vs
val filter = Filter
.x()
cmiiwPaul Griffith
09/12/2021, 11:59 PMFilterBuilder
like this. It can get harder to indicate required vs optional stuff, but that's a problem with builders toomiqbaldc
09/13/2021, 4:31 AMto indicate required vs optionalAny suggestions which pattern that’ll be convenience about this parts?
Paul Griffith
09/13/2021, 2:22 PM