I am working on a project where I have to look into someone else’s code and modify it.
However since many classmates in my class are quite new to program, many have such a messy organization.
The code that I am assigned to improvise has a lot of flaws and messy redundant lines.
I am trying my best to clean them up, however due to my inexperience, I find it hard to clean them up.
Lines such as
if (turnElapsed[1] == 2)
{
turnElapsed[0] += 1;
turnElapsed[1] = 0;
}
turnElapsed[1]++;
looks quite redundant to me.
I believe, and there must be a better way to write a simple version of it.
so I tried the code below but it seemed to not work properly.
turnElapsed[0] += (turnElapsed[1]++ == 2) ? 1 ; 0 ;
turnElapsed[1] = (turnElapsed[1] == 2 ) ? 0; turnElapsed[1];
Firstly, you are using
;as separator instead of:which is a syntax error. Secondly, you’re incrementingturnElapsed[1]on the first line, which means that when it reaches the second line it will no longer equal 2 – that’s different to the original logic. This is why your version does not work properly.However, if you did fix those errors I don’t think your code would be easier to read. The original is more readable, because it expresses the intention more clearly. You can read that and verbalise it as “if turnElapsed[1] is 2 then …”. Your alternative takes fewer lines, but is more “cryptic”. Another advantage of the original code is that you can put a breakpoint inside the braces if you wanted to break when the if condition was true – you cannot do that with the ternary operator (?).