+ 3
If Statements and Code Refactoring
if (i >= ring.length()) i = i - ring.length(); if (i < 0) i = ring.length() + i; The above are from lines 94 - 97 of my code. Is it possible to refactor to eliminate these if statements or this the simplest way to make these decisions already? Thoughts? https://code.sololearn.com/c6fBC0Ak72t6/?ref=app
8 Respuestas
+ 8
how about this?
get rid of both ifs
change the command before to
i = (ring.indexOf(decodeMe.charAt(j)) - temp)%ring.length();
[edit]
no good xD
index out of range
[edit2]
leaving the 2nd if worked
i = (ring.indexOf(decodeMe.charAt(j)) - temp)%ring.length();
if (i < 0)
i = ring.length() + i;
+ 6
i = (i >= ring.length())? i-ring.length():i+ring.length());
+ 3
@Jeth I don't hate if statements, I'm just wondering if there were possibilities I could have explored that would minimize, if not eliminate, my use of if's.
Yeah, I'm aware of the newline character. I just hadn't learned how to use it by the time I first got my code working. Knowing how to use the newline character in Java is one reason, of many, that I'm now considering refactoring my code.
+ 3
@Burey Thanks, I'll have to try that. It does appear to reduce the complexity of my code a bit.
+ 2
Lol. Thanks, but aren't terniary operators an obfuscated if-then? :)
+ 2
By the way you can refactor this:
System.out.println();
System.out.println();
System.out.println("To enter a new word hit enter or else type 'done': ");
System.out.println();
with this:
System.out.println("\n\nTo enter a new word hit enter or else type 'done': \n");
There is a special symbol to break line, no need to call println function for this many times in a row.
+ 1
i = i >= ring.length() ? i - ring.length() : i < 0 ? ring.length() + i : i;
+ 1
Only if they used with complex statements or nested many times. If you don't like them why you want to refactor simple "if" statements? It is better to leave code in state of better readability for you. Even if it will take more lines.