If-statements can contain duplicated statements with minimal differences. For example, copy-paste changes can result in such code duplication. The duplication can often be simplified by extracting the difference using the conditional operator and reducing the if-else to the deduplicated statement.
Before (Example)
if (direction === "left") {
move(original.x, -10);
} else {
move(original.x, 10);
}
Refactoring Steps
π‘Β Β The refactoring steps are using P42 JavaScript Assistant v1.99
- Extract variable twice with the same variable name
- Split declaration and initialization of both extracted constants
- Move duplicated first statement out of if-else
- Move duplicated last statement out of if-else
- Convert the if-else statement into a conditional expression
- Merge variable declaration and initialization
- Inline variable
After (Example)
move(original.x, direction === "left" ? -10 : 10);
Top comments (8)
From the look of the video, it would have been quicker just to re-type the refactored version yourself?
Yup, and I tested it. Manual retyping is about 2x as fast in this case.
However, the main strength of automated refactoring is their safety, both in terms of accurately executing the changes and in terms of evaluating pitfalls (some of the time).
When I talked to other people about chaining automated refactorings vs manually retyping, there was a preference for safety over speed, especially in legacy code that's more complex than this toy example.
Unless it's an extensive variable rename, my instincts are quite the opposite... I much prefer to do it myself - a tool like this just feels cumbersome and unnecessary
That's fair - the tooling value depends on personal preferences, experience, the complexity of & familiarity with the codebase, etc.
On this .. refactoring yourself would also increase your knowledge and understanding.
I am not sure about this. The example would be a situation where I explicitly NOT use any tool for the task, since just typing it manually is so much less work.
Are there complicated examples, where a tool like this actually HELPS instead of wasting time?
As mentioned in the other comment, manual re-typing is 2x as fast. The advantage of using a tool is to prevent mistakes, e.g. when you think you could refactor some code, but missed a small difference and as a result introduced a regression.
That's pretty cool!