Today's anonymous submitter sends us some C# code. This particular block of code controls whether two different columns are visible on the screen. If the field Dist_Por equals one set of constants, we display one column, if it equals a different constant, we display the other. Seems simple enough.

My question to you is this: how many nested ternaries do you need to solve this problem?

ColHectarias.Visible = Dist_Por == TIPO_DIST_COSTO.Directo ? false : Dist_Por == TIPO_DIST_COSTO.Plantilla ? false : Dist_Por == TIPO_DIST_COSTO.Hectáreas ? true : Dist_Por == TIPO_DIST_COSTO.CCosIndirecto ? true : false;
ColPorcentaje.Visible = Dist_Por == TIPO_DIST_COSTO.Directo ? false : Dist_Por == TIPO_DIST_COSTO.Plantilla ? true : Dist_Por == TIPO_DIST_COSTO.Hectáreas ? false : Dist_Por == TIPO_DIST_COSTO.CCosIndirecto ? false : false;

If you read through just the first ternary, you'll notice the pattern: if the field equals Directo, this is false. If the field equals Plantilla this is false. If the field equals Hectáreas, it's true. If the field equals CCosIndirecto, also true. And when you write it out that way, it's just a simple or expression: ColHectarias.Visible = Dist_Por == TIPO_DIST_COSTO.Hectáreas || Dist_Por == TIPO_DIST_COSTO.CCosIndirecto;

The ColPorcentaje column is even worse: it's only visible when Dist_Por equals TIPO_DIST_COSTO.Plantilla.

Our anonymous submitter adds:

Simple, right? If only, starting with the fact they even got the ColHectarias column name wrong: it should have been ColHectareas. Do not make the mistake of assuming those are the only lines with issues or this is the first time it happens. I known the person who wrote that and if I had any choice in the matter I would never, ever, look a their code, because my sanity drops every time I do.

[Advertisement] Keep all your packages and Docker containers in one place, scan for vulnerabilities, and control who can access different feeds. ProGet installs in minutes and has a powerful free version with a lot of great features that you can upgrade when ready.Learn more.