Author Topic: Shrinking code  (Read 137 times)

0 Members and 1 Guest are viewing this topic.

ABer

  • Administrator
  • Hero Member
  • *****
  • Posts: 533
    • View Profile
Shrinking code
« on: April 24, 2022, 06:56:18 PM »
Hi there - the following shows how you can shrink and improve code. Thanks to Jean for the amazing final two line version:

First attempt:

` step options - if up +ve += 1, if down -ve -= 1;
if (stepOpt = 0)
     step += updownbutton * 2; ` 1/4 degree
  else
      {if (stepOpt = 1)
         step += updownbutton * 4;} ` 1/2 degree
  else
      {if (stepOpt = 2)
         step += updownbutton * 8;} ` 1 degree
  else
      {if (stepOpt = 3)
         step += updownbutton * 40;} ` 5 degrees
  else
      {if (stepOpt = 4)
         step += updownbutton * 240;} ` 30 degrees

Jean suggested this might be poor code. Next step could be:

` step options - if up +ve += 1, if down -ve -= 1;

if (stepOpt = 0)
   step += updownbutton * 2; ` 1/4 degree

if (stepOpt = 1)
   step += updownbutton * 4; ` 1/2 degree

if (stepOpt = 2)
    step += updownbutton * 8; ` 1 degree

if (stepOpt = 3)
   step += updownbutton * 40; ` 5 degrees

if (stepOpt = 4)
   step += updownbutton * 240; ` 30 degrees

Jean suggested using switch();

switch (stepOpt)
{
:0; step += updownbutton * 2; break; ` 1/4 degree
:1; step += updownbutton * 4; break; ` 1/2 degree
` etc.
}

But then came up with this:

Code: [Select]
int uDValue[5] = { 2, 4, 8, 40, 240 };
 
step += updownbutton * uDValue[stepOpt];

Genius!!

Thanks Jean. It works like a charm.

Ed


Jean

  • Administrator
  • Hero Member
  • *****
  • Posts: 615
    • View Profile
Re: Shrinking code
« Reply #1 on: April 25, 2022, 11:29:42 AM »
I was confused about your code, i know why, look if it write it out in my own indenting style it becomes this, which is perfectly fine. The bracket style got me wrong footed. Hey i didn't know ab could do this :)
Code: [Select]
if (stepOpt = 0)
  step += 2; ` 1/4 degree
else
  {
  if (stepOpt = 1)
       step += 4;
  } ` 1/2 degree
  else
    {
    if (stepOpt = 2)
       step += 8;
    } ` 1 degree
    else
      {
      if (stepOpt = 3)
      step += 40;
      } ` 5 degrees
      else
        {
        if (stepOpt = 4)
          step += 240;
        } ` 30 degrees
Greetings from Groningen Netherlands <)))><.`.><(((>

ABer

  • Administrator
  • Hero Member
  • *****
  • Posts: 533
    • View Profile
Re: Shrinking code
« Reply #2 on: April 25, 2022, 06:06:37 PM »
Thanks Jean - we have very different styles for laying out code - I go for a really condensed style, and you like the looser style. I'm glad that the code I wrote wasn't too bad, but your single line takes some beating. Both do the same work, but your line gets straight to the point. Ed