language agnostic - How to recognize that short code blocks can be refactored into something cleaner? -
I have a little code that I wrote a few weeks ago (the purpose of the code is not very important as its structure) :
if (_image.Empty) {// use the real image size if they have not specified a custom size if (_glyphSize.Width> 0) imageSize.Width = _glyphSize Width // override other image With = _image.GetWidth; If (_glyphSize.Height> gt; 0) then image size. Hi = _glyphSize.Height and Choiceist Heights = _image.GetHeight} else {// No image, but they can still override it with a custom shape if _glyphSize.Width> = 0; If (_glyphSize.Height> gt; 0) imageSize.Height = _glyphSize.Height and Choiceist Height: = 0; }
I was going into it tonight, and when I was cleaning it, I realized the clean version should be more concise:
// Understand the width of the final image if (_glyphSize.Width> 0) imageSize.Width = _glyphSize.Width else if (not _glyph.Empty) imageSize.Width = _glyph.GetWidth else imageSize.Width = 0; // See the final image height, if (_glyphSize.Height> gt; 0) imageSize.Height = _glyphSize.Height else if (not _glyph.Empty) imageSize.Height = _glyph.GetHeight and Choiceist. Heights = 0; Note: I have trimmed the code for unnecessary logical flow, and read the source language. Finally, I took the nestined if
, and reversed them, doing this was allowed to do this shoring. My question is how can I recognize it in the future?
What are the signs of narrative-narrative, which I have just written some code that can be re-applied at least?
A few other weeks ago, I had a similar permission check like this: The user can do one thing:
- If they have permission they can do it
- If they do not have permission, but override is in effect
which I initially coded:
if ((HasPermission | | (Promotion and override active) {... work done}
The logical conditions on that clause were verbatim I Tried to get back to my boolean algebra course to explain how to simplify it. Finally I can do this, so I stopped pulling the truth table: Permission Override results 0 0 0 1 1 1 0 1 1 1 1
When I see it is a or operation then my if
statement Has become:
if (smoothened or overridden enneed) {...}
which is clear and simple. And now I am thinking How can I not start?
I have been brought back to my SO question: should I show the fairytale signal in / me to make sure that some blocks of code Need some TLC?
Here are some guidelines to complete the code above my head
- Nested if-
- For some reasons if you are copying and pasting a line of code frequently
I discrete mathematics got an effect of how I statement if statement has been made now. Generally, I think I am writing two statements in two blocks, then I will do some mental 'factoring'.
Comments
Post a Comment