I am going to start with basic things such refactoring. In my point of view every developer should know these methods. Let’s start.
At the beginning need to start with easy methods and I am going to show example of using “Extract method“.
For example we have some code like this. In this post I will use very simple application
public class Main{ public static void main(String[] args){ StringBuilder builder = new StringBuilder(); builder.append("Hello"); builder.append(","); builder.append("World"); builder.append("!"); String text = builder.toString(); System.out.println("##################"); System.out.println(text); System.out.println("##################"); }}As you can see this code consist of:
creating text message
StringBuilder builder = new StringBuilder();builder.append("Hello");builder.append(",");builder.append("World");builder.append("!");getting String from StringBuilder
String text = builder.toString();
printing text message
System.out.println("##################");System.out.println(text);System.out.println("##################");Looks not very clean. What about this variant?
public class Main{ public static void main(String[] args){ String text = generateText(); printText(text); } private static String generateText(){ StringBuilder builder = new StringBuilder(); builder.append("Hello"); builder.append(","); builder.append("World"); builder.append("!"); return builder.toString(); } private static void printText(String text){ System.out.println("##################"); System.out.println(text); System.out.println("##################"); }}As you can see I extracted blocks of code which works on some functionality to external methods and now code is more readable. It is very easy to support code which consist of methods instead of supporting code which consist of one big method for all application’s logic.
This is very simple example,but I hope it will be useful for you.
If you’d like to get the latest posts as soon as they’re published,subscribe to website’s feed!
No related posts.

Recent Comments