I have some code that I wrote a few weeks ago (the purpose of the code is not as important as its structure):
if (_image.Empty) {
I was going to survive this tonight, and when I cleaned it, I realized that the cleaned version should be more concise:
//Figure out the final image width if (_glyphSize.Width > 0) imageSize.Width = _glyphSize.Width else if (not _glyph.Empty) imageSize.Width = _glyph.GetWidth else imageSize.Width = 0; //Figure out the final image height if (_glyphSize.Height > 0) imageSize.Height = _glyphSize.Height else if (not _glyph.Empty) imageSize.Height = _glyph.GetHeight else imageSize.Height = 0;
Note. . I cut the code to a logical thread and distorted the source language.
In the end, I took the nested if and turned them over. This has reduced this time. My question is: how can I find out in the future?
What are the telltale signs that I just wrote code that can be reorganized into something shorter?
Another example that I had a few weeks ago was something like a permission check: a user can perform an action:
- if they have permission, they can do it
- if they don’t have permission, but override is valid
Which I originally encoded as:
if ((HasPermission || (!HasPermission and OverrideEnabled)) { ...do stuff }
The logical conditions of this if clause seemed terse. I tried to return to my course in logical algebra to figure out how to simplify it. In the end, I could do this, so I ended up drawing a truth table:
Permission Override Result 0 0 0 0 1 1 1 0 1 1 1 1
That when I look, this is an OR operation. So my if become:
if (HasPermission or OverrideEnabled) { ... }
It is obvious and simple. So, now I wonder how I could not understand this.
Which brings me back to my SO question: what control characters can / should I look for to understand that some block of code needs some TLC?