1

If I am writing in a functional style and want to use the Replace Conditional with Composition refactoring pattern on a switch or a long chain of if/else if/else if/..., how do I approach it?

I understand with OOP that applying the Replace Conditional with Polymorphism pattern makes this easy as you can simply call a single method and it will already execute the correct code that had previously been in a switch case or a conditional branch in the "less clean" version of the code, based on which subclass you're working with.

But if I'm not using OOP, but FP (which I'm very new to), my initial impression is that the composition pattern may be better suited. Is this The Way, and if so, how is this pattern best applied?

Example pseudocode to apply the pattern to:

if (data.graded !== '') {
  // show letter grade
}
else if (data.start_date === '') {
  // show enrollment deadline date (data.deadline)
}
else if (data.start_date < today) {
  // show "Starts in n days!"
}
else if (data.end_date === today) {
  // show "Course ends TODAY!"
}
else if (data.end_date < today) {
  // show "Course concluded."
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.