[Design][Think outside the box] Not either True or False

kokchai
2 min readJun 12, 2020

Scenario 1:

Day 1: Your bosses gives instruction that write a logic of counting down from 100 to 0;
Day 2: They add a new requirement to add a timer to count from 0 to 100.
Day 3: They require to add a timer to multiply by 2.

Day 1: We create the code to count down from 100 to 0, then it will look like:

var timeInSeconds = 100
while (timeInSeconds != 0) {
timeInSeconds--
}

Day 2: We add count up, then it will look like:

var isCountDown: Boolean = trueif (isCountDown) {
while (timeInSeconds > 0) {
timeInSeconds--
}
} else {
while (timeInSeconds < 100) {
timeInSeconds++
}
}

Comment: It’s not a good ideas to only consider true or false in the design phrase. Why don’t we think about what-if ?

Day 3: If we are forced to add multiply by 2, then it would look like:

const val COUNT_DOWN = 1
const val COUNT_UP = 2
const val MULTIPLY_BY_2 = 3
var type: Int = COUNT_DOWN
var timeInSeconds =
when (type) {
COUNT_DOWN -> {
val timeInSeconds = 100
while (timeInSeconds > 0) {
timeInSeconds--
}
}
COUNT_UP -> {
val timeInSeconds = 0
while (timeInSeconds < 100) {
timeInSeconds++
}
}
MULTIPLY_BY_2 -> {
val timeInSeconds = 0
while (timeInSeconds < 100) {
timeInSeconds *= 2
}
}
}

Day N, they want you to add this and that, so how ?

How about let’s slightly change the logic to try to be flexible to handle more requirement in future ?

var timeInSeconds: Int
val end: Int
val operation: (Int)->Int
val type = COUNT_DOWN
when (type) {
COUNT_DOWN -> {
timeInSeconds = 100
end = 0
operation = (a)->a-1
}
COUNT_UP -> {
timeInSeconds = 0
end = 100
operation = (a)->a+1
}
MULTIPLY_BY_2 -> {
timeInSeconds = 0
end = 100
operation = (a)->a*2
}
else -> {
//TODO others
}
}
while (timeInSeconds != end) {
timeInSeconds = operation.invoke(timeInSeconds)
}

Scenario 2:

--

--