Question

Inside our UI there's an option to select something from a dropdown. Depending on what you choose inside that menu the rest of the fields inside the UI change accordingly. At the moment we handle it with if/else clauses which I think is not a good approach. Is there a pattern or a best practice to deal with something like that? The software is written in Java. Every help or idea is appreciated.

Was it helpful?

Solution

A common approach to completely avoiding if/else's in this case is to use a HashTable. The keys are the contents of the dropdown and the values are POJOs containing all the UI config changes associated with each dropdown value. You end up with code like:

SomePojo uiConfig = uiConfigTable.get(dropdownValue);
label1.text = uiConfig.label1Text;
checkBox1.enabled = uiConfig.checkBox1Enabled;
...

I've no idea if their is a name for this pattern.

OTHER TIPS

I recommend the Table-Driven Methods. Which is introduced in the book Code Complete.

ref from the stackoverflow answer: https://stackoverflow.com/questions/105311/what-are-table-driven-methods

Table-driven methods are schemes that allow you to look up information in a table rather than using logic statements (i.e. case, if). In simple cases, it's quicker and easier to use logic statements, but as the logic chain becomes more complex, table-driven code is simpler than complicated logic, easier to modify and more efficient.

Licensed under: CC-BY-SA with attribution
scroll top