Things I do while refactoring

By | January 18, 2020

Well, maybe the title should be: Things I hope you do while developing 🙂

  1. Update code to current standards and tools
  2. Limit scope and clean code
  3. Write unit tests

Maybe the third one should be at the top, because it is required for the first two. Never mind, I won’t change it.

First Update code to current standards and tools. Is your code up-to-date? Are you using Java 8 features as streams, try-with-resources, or even generics and the Java 5 for-loop. As weird as it mind sound, we are still seeing old old code in some modules. When you see it, you change it. That’s expected.

Limit scope and clean code. This one is also really important, and basically it is all about readability. Always limit the scope of a variable used, make sure you don’t just bulk-initialize variables at the beginning of a method. Clean code by extracting common functionality into private methods, and give them appropriate names that describes their expected behavior.
Example:

public void kingMethod() {
	String a = ”file.txt”;
	String b = ”B”;
	String c = ”C”;

	doSomething(a);
	extract(b);
	process(c);
	move(b);
	download(a);
	log(c);
}

… rewrite it to this …

public void kingMethod() {
	download("file.txt");
	extractAndMove("B");
	process("C");
}

public void download(String a) {
	doSomething(a);
	download(a);
}

public void extractAndMove(String b) {
	extract(b);
	move(b);
}

public void process(String c) {
	process(c);
	log(c);
}

Okey, so this is a ridiculous example, but just to show my point. A, B and C didn’t have anything at all in common, so just limit scope, that is, call the methods just after the variable is initialized, and then clean code by extracting each to new methods and give the methods good names.

Last but not least, Write unit tests. So, yes, start with this. Write them first, code second. You don’t want to break things and introduce bugs while refactoring.

And remember. It is not your code, it is not your team mates code. Collective ownership of code is important in any development team. You have a collective responsibility to develop and maintain code and product quality.

Category: IT