Can you simplify this amount of conditions?

0

I have the following code:

        foreach (var lote in collection.ToList())
        {
            count++;

            ushort[] dadosBalanca = new ushort[9];

            if (lote.AlvoPasso > ushort.MaxValue)
            {
                var subtracao = (lote.AlvoPasso - 65536);
                dadosBalanca[3] = 1;

                if (lote.AlvoPasso > (ushort.MaxValue * 2))
                {
                    subtracao -= 65536;
                    dadosBalanca[3] = 2; //[OUT37]

                    if (lote.AlvoPasso > (ushort.MaxValue * 3))
                    {
                        subtracao -= 65536;
                        dadosBalanca[3] = 3; //[OUT37]

                        if (lote.AlvoPasso > (ushort.MaxValue * 4))
                        {
                            subtracao -= 65536;
                            dadosBalanca[3] = 4; //[OUT37]
                        }
                    }
                }

                dadosBalanca[4] = (ushort)subtracao; //[OUT38]
            }
            else
            {
                dadosBalanca[3] = 0; //[OUT37]
                dadosBalanca[4] = (ushort)lote.AlvoPasso; //[OUT38]
            }

            //...
        }

This code already works, I'd like to suggest improvement.

    
asked by anonymous 19.02.2018 / 16:27

2 answers

1

There is not much to spruce up. You can replace those chained if's with a for .

BTW, the three if's are chained together does not make much sense because they write in the same place, that is, one overwrites the other. Anyway, I kept the original behavior in for .

The code looks like this:

foreach (var lote in collection.ToList())
{
    count++;
    ushort[] dadosBalanca = new ushort[9];

    if (lote.AlvoPasso <= ushort.MaxValue) // Note que isso foi invertido
    {
        dadosBalanca[3] = 0; //[OUT37]
        dadosBalanca[4] = (ushort)lote.AlvoPasso; //[OUT38]
        continue;        
    }

    var subtracao = (lote.AlvoPasso - 65536);
    dadosBalanca[3] = 1;

    for(ushort i = 2; i <= 3; i++)
    {
        if (lote.AlvoPasso > (ushort.MaxValue * i))
        {
            subtracao -= 65536;
            dadosBalanca[3] = i; //[OUT3X]    
        }    
    }        

    dadosBalanca[4] = (ushort)subtracao; //[OUT38]    
}
    
19.02.2018 / 16:52
3

Yes, it does, a lot:

var deslocamento = lote.AlvoPasso / ushort.MaxValue;
dadosBalanca[3] = deslocamento;
dadosBalanca[4] = lote.AlvoPasso - ushort.MaxValue * deslocamento;

I'm assuming that the offset can not be more than 4, since the current code ignores this. If you can, it will give error in the original and in mine, it would have to treat, but it would have to see which is the criterion.     

19.02.2018 / 16:57