web
You’re offline. This is a read only version of the page.
close
Skip to main content
Community site session details

Community site session details

Session Id :

Use of Case Instruction.

Jalmaraz Profile Picture Jalmaraz 669

CASE statement is very good, CASE is very bad.

This function can return quantity in a decimal variable or show item entries. We use CASE to avoid code duplication on filtering the recordset by Item and Customer:

Dependency4.png

If I want to add some new operation I have to change option parameter and add another option in CASE statement:

Dependency5.png

Improving without CASE.

CASE was everywhere in Navision code, but new versions are avoiding this. So, programmers must do the same. What about to write code above this way?

Dependency6.png

 

We have replace the only function by four functions:

-          One common function for filter the record.

-          A function for each option.

This way, we don´t need to modify an existing function for a new use, instead, we add a new function.

The pain: change a function with a lot of CASE statements.

The example is a very short piece of code but imagine a big function, with more CASE statements. It´s hard and complicated adding new particular uses.

With CASE we have a general function and when we need to add a case we must change general function, falling in a design error, general depends on particular. This is the last SOLID principle, dependency inversion. In OOP CASE use is an Smell, and only is allowed in constructor.

Not fully agree, because I am not so dogmatic about methodology and code smells, but almost always Is better add a new function over modify existing one (safer faster and cleaner).

Never use Case?

I think it´s good to be pragmatic over dogmatic. CASE is a good statement and could be used, mostly at the beginning of all functions calls. This could be the equivalent to object constructor. I think is good to avoid CASE, and split functions instead but not always is possible, and could be problematic not to use it sometimes.

Conclusión.

If you can, instead include a new “CASE” in your function you can follow this method:

-          Clone existing function.

-          Change the part of the function for your particular case.

-          Extract common logic of all functions in another new common function and call it from all functions.

This is safer, faster and better, add a new small and particular function instead touch existing function, and sometimes modifying its parameters.

If not possible or cost too much, keep CASE statement: be practical. CASE at the beginning of business logic is not bad.

Comments

*This post is locked for comments