Few Techniques about Refactor Your Code 代码重构技巧(英文版)

1 If some method includes a part that is long or needs lots of comments to let people understand, then we can consider to divide it into a few smaller method units.
It is like: when a function needs to print a display of the sum of an array and it’s information. We can separate a function into 3 methods: print Banner, calculateSum, printInfo.
2 On the contrary, if we have way too many methods, then sometimes we need inner connection of functions and inner temp variables, (replace temp variables with the expression resigned on them) (I don’t think so, and according to another paragraph, we should do the opposite)
3 Use more lambda expressions.
4 Use constant variables to replace constant, give it a clear variable name.(use static final keywords on those constant, instead make them “magic number”)
5 Use polymorphism to replace switch(减少if else的使用)

重构含有过多参数的方法,为什么要重构,因为当一个方法有过多的参数的时候 即难以阅读又难以维护。也就是说有的时候是远程调用这些方法 所以用到了API,如果要仅仅为了修改一个参数 那么就要修改接口。重构方法:将这些对象封装成一个对象,就很好维护了,即新建一个对象类即可 而无需修改接口。
Reference URL: URL

1 Set class or method as final if we can make sure that this won’t change later, because this keyword can make class non-inheritable or make methods can’t override. And Java complier will seeking all of the inner connection of final method. And inner connection can improve the java running efficiency.(但是
2 When we have to add two string, instead of using +, we should use String Builder and String Buffer. Because JVM needs to take time generate objects, and also needs time to 垃圾回收和处理。so generating too many object will effect performance of program.
3 Use temp variable. Because unlike static variable and instance variable, temp variable stored in stack, and other kinds of variables, use heap to store. Besides, after the method finished, temp variable will be 自动没了,不需要垃圾回收。
4 If we can make a guess about the length of content needs to be added, then we can initialize initial length. (ArrayList, LinkedList, StringBuilder, HashMap, Hashset)
5 Use bit manipulation more
6 Use HashMap, ArrayList, String Builder. Do not use Hashtable, Vector, String Buffer unless we need to make sure the security of multi threads.
Reference URL: URL

还有最重要的一点:
我们学习的设计模式就是用来代码重构的。
还有一个关键的点要记住,之前学的各种设计模式可以被用来做代码优化!比如策略模式+工厂模式来进行重构。
策略模式+工厂模式优化if…else if…else if结构_kawen

posted @ 2020-12-25 22:52  EvanMeetTheWorld  阅读(28)  评论(0)    收藏  举报