项目开发过程中,我们可能会遇到很多难以维护的代码,超长的方法,一看都头大,正常来说,代码一般不会超过100行,如果业务复杂,尽量分成多个小方法配合注释加以说明。
如何便捷的查找项目中的超长代码呢,一可以借助阿里巴巴代码规约插件,这个就不多说了,下面时另一种方式,利用java代码进行实现:
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Stack;
/**
* @desc: 获取项目中方法长度超过指定行数的工具代码,对超长方法进行优化
* class{
* 方法
* method(){
* if(){
* ...
* }
* }
* 匿名代码块
* {
* <p>
* }
* 内部类
* class{
* <p>
* }
* }在此我们将次一级都当做方法,采用先进后出的栈Stack存储方法行和方法行号,通过记录读取当前行号与方法起始行号相减获得方法行数
* @auther: tjs
* @date: 2019/8/13
*/
@Slf4j
public class MethodRowCountUtil {
public static void main(String[] args) {
String path = "E:\\qgs\\demo\\src\\main\\java\\com\\example\\demo\\config\\StringToDateConfig.java";
moreRowCount(path);
}
/**
* @desc: 超长方法行数统计
* @auther: tjs
* @date: 2019/8/13
*/
public static void moreRowCount(String path) {
File file = new File(path);
readSourceDir(file);
}
/**
* @desc: 源文件获取
* @auther: tjs
* @date: 2019/8/13
*/
private static void readSourceDir(File sourceFile){
if (sourceFile.isDirectory()){
for (File file:sourceFile.listFiles()){
if(file.isDirectory()){
readSourceDir(sourceFile);
}else {
readFile(file);
}
}
}else {
readFile(sourceFile);
}
}
/**
* @desc: 文件读取
* @auther: tjs
* @date: 2019/8/13
*/
private static void readFile(File file) {
BufferedReader reader = null;
String currentLineData;
int currentLineNum = 0;
try {
reader = new BufferedReader(new FileReader(file));
//先进后出
Stack<String[]> stack = new Stack<>();
while ((currentLineData = reader.readLine()) != null) {
currentLineNum++;
int num = appear(currentLineData, "{") - appear(currentLineData, "}");
if (num > 0) {
for (int i = 0; i < num; i++) {
stack.push(new String[]{currentLineNum + "", currentLineData});
}
} else {
for (int i = 0; i < -num; i++) {
if (stack.empty()) {
System.out.println(file.getName() + "match {} fail,currentLineNum:" + currentLineNum);
}
String[] arrData = stack.pop();
//当栈中取出后栈中只有一条数据时,说明该方法已经结束
if(stack.size() == 1){
if(currentLineNum-Integer.parseInt(arrData[0]) >80){
System.out.println("Class:"+file.getName()+" methodLength:"+(currentLineNum-Integer.parseInt(arrData[0])+1)+"methodRow:"+arrData[1]);
}
}
}
}
}
} catch (Exception e) {
log.error("read file exception");
}finally {
if(reader != null){
try {
reader.close();
} catch (IOException e) {
log.error("reader close exception");
}
}
}
}
/**
* @desc: 获取{或}出现次数
* @auther: tjs
* @date: 2019/8/13
*/
private static int appear(String sourceData, String search) {
int appear = 0;
int index = -1;
while ((index = sourceData.indexOf(search, index)) > -1) {
index++;
appear++;
}
return appear;
}
}
ok,这样即可~.~