代码圈复杂度治理小结
什么是圈复杂度
怎么计算圈复杂度
if语句
while语句(包含do...while...语句)
for语句(包含foreach语句)
switch case语句
try catch语句
&& 表达式 || 表达式
三元运算符
//案例1,圈复杂度V(G) = 1(if) + 1(catch) + 1 = 3
public String myMethod1(){
if(xxx){
try {
//xxx;
} catch (IOException e) {
//xxx;
}
}else{
xxx;
}
return xx;
}
//案例2,圈复杂度V(G) = 2(if) + 1(&&) + 1 = 4
public String myMethod2() {
if (xxx) {
//xxx;
} else {
if (xxx && xxx) {
//xxx;
} else {
//xxx;
}
xx();
}
return xx;
}
为什么要关注圈复杂度
public XXresult doSave( XXDTO newScriptDTO) {
String type = Enums.ScriptType.CUSTOM;
Boolean containsTryCatch = StringUtil.contains(content, "try")
&& StringUtil.contains(content, "catch");
if (StringUtil.isBlank(scriptName)) {
baseOperationResult.setMessage("XXX");
return baseOperationResult;
}
if (!scriptName.matches("^[(\\d)|_|a-z|A-Z]+$")) {
baseOperationResult.setMessage("XXX");
return baseOperationResult;
}
NewScript tempScript = null;
try {
tempScript = newScriptManager.findByName(StringUtil.trim(scriptName));
} catch (Exception e) {
baseOperationResult.setMessage("XXX");
return baseOperationResult;
}
if (StringUtil.isBlank(id)) {
if (tempScript != null) {
baseOperationResult.setMessage("XXX");
return baseOperationResult;
}
} else {
Integer editScriptId = Integer.parseInt(id);
if (null != tempScript) {
if (!editScriptId.equals(tempScript.getId())) {
baseOperationResult.setMessage("XXX");
return baseOperationResult;
}
}
}
if (!Enums.NewScriptTypeEnum.XX.contains(scriptType)) {
baseOperationResult.setMessage("XX");
return baseOperationResult;
}
Boolean needSubtypeMode = true;
if (StringUtils.equals(scriptType, Enums.XX.XX)
|| StringUtils.equals(scriptType, Enums.XX.PRE)) {
needSubtypeMode = false;
}
NewScript script = new NewScript();
script.setScriptType(scriptType);
if (StringUtil.isNumeric(status)) {
script.setStatus(Integer.parseInt(status));
}
if (StringUtil.isNotBlank(scriptCategory)) {
script.setScriptCategory(ScriptCategory.getByCode(scriptCategory));
}
String subType = "";
if (needSubtypeMode) {
if (StringUtil.isBlank(subtypeandtip)) {
baseOperationResult.setMessage("XXX");
return baseOperationResult;
}
}
if (needSubtypeMode) {
List<NewScript> allActiveAndTestRunScripts = newScriptManager
.findAllActiveAndTestRunScripts();
List<String> allActiveAndTestRunSubTypeList = new ArrayList<>();
for (NewScript activeAndTestRunScript : allActiveAndTestRunScripts) {
List<String> subTypeListEveryScript = Arrays
.asList(Optional.ofNullable(activeAndTestRunScript.getSubType())
.orElse(new String()).split(","));
for (String subTypeTemp : subTypeListEveryScript) {
if (StringUtil.isNotBlank(subTypeTemp)) {
allActiveAndTestRunSubTypeList.add(subTypeTemp);
}
}
}
try {
JSONArray subtypetipsArray = JSON.parseArray(subtypeandtip);
if (StringUtil.isBlank(id)) {
for (Object object : subtypetipsArray) {
JSONObject subtypetipsObject = (JSONObject) object;
String subtypeSingle = subtypetipsObject.getString("subtype");
if (StringUtil.isBlank(subtypeSingle)) {
baseOperationResult.setSuccess(false);
return baseOperationResult;
}
if (CollectionUtils.contains(allActiveAndTestRunSubTypeList.iterator(),
subtypeSingle)) {
baseOperationResult.setSuccess(false);
return baseOperationResult;
}
}
} else {
if ("1".equals(status) || "2".equals(status)) {
for (Object object : subtypetipsArray) {
//省略部分内容XXX;
if (StringUtil.isBlank(subtypeSingle)) {
baseOperationResult.setSuccess(false);
return baseOperationResult;
}
for (NewScript oldNewScript : allActiveAndTestRunScripts) {
if (oldNewScript.getId().equals(Integer.parseInt(id))) {
continue;
}
//省略部分内容XXX;
if (CollectionUtils.contains(filtered.iterator(), subtypeSingle)) {
baseOperationResult.setSuccess(false);
return baseOperationResult;
}
}
}
}
}
for (Object object : subtypetipsArray) {
if (1 == script.getStatus() || 2 == script.getStatus()) {
SubtypeTips subtypeTips = null;
subtypeTips = subtypeTipsManager.findBySubtype(subtypeSingle);
if (subtypeTips == null) {
subtypeTips = new SubtypeTips();
}
subtypeTips.setSubtype(subtypeSingle);
subtypeTips.setInternalTips(innertips);
subtypeTips.setExternalTips(externaltips);
subtypeTips.setShareLink(shareLink);
subtypeTips.setStatus(1);
subtypeTipsManager.save(subtypeTips);
}
}
subType = StringUtil.substring(subType, 0, subType.length() - 1);
} catch (Exception e) {
baseOperationResult.setSuccess(false);
baseOperationResult.setMessage("XXX");
return baseOperationResult;
}
}
boolean needCreateTestRunScript = false;
if (StringUtils.isNotBlank(id)) {
script.setId(Integer.parseInt(id));
NewScript orgin = newScriptManager.findById(Integer.parseInt(id));
if (null != orgin && 1 == orgin.getStatus() && "1".equals(status)) {
if (StringUtil.isNotBlank(orgin.getContent())) {
String originContentHash = CodeUtil
.getMd5(StringUtil.deleteWhitespace(orgin.getContent()));
String contentHash = CodeUtil.getMd5(StringUtil.deleteWhitespace(content));
if (!StringUtil.equals(originContentHash, contentHash)) {
needCreateTestRunScript = true;
}
}
}
} else {
script.setSubmitter(user.getLoginName());
}
Set<String> systemList = new HashSet<String>();
if (StringUtil.isNotBlank(systems)) {
String[] systemArray = systems.split(",");
for (int i = 0; i < systemArray.length; i++) {
systemList.add(systemArray[i]);
}
}
if (needCreateTestRunScript) {
if (needSubtypeMode) {
content = replaceContent(content, subType);
String testScriptSubType = "";
List<String> subTypeList = Arrays.asList(StringUtil.split(subType, ","));
for (int i = 0; i < subTypeList.size(); i++) {
testScriptSubType += this.UPDATE_SCRIPT + subTypeList.get(i);
if (i != subTypeList.size() - 1) {
testScriptSubType += ",";
}
}
subType = testScriptSubType;
}
scriptName = this.UPDATE_SCRIPT + scriptName;
NewScript oldUpdateScript = newScriptManager.findByName(scriptName);
if (null != oldUpdateScript)
script.setId(oldUpdateScript.getId());
else {
script.setId(null);
}
baseOperationResult.setNeedAudit(true);
}
if (StringUtil.isBlank(fileSuffix)) {
//如果全空的话 默认全扫
script.setSuffix(".*");
} else {
script.setSuffix(fileSuffix);
}
script.setName(scriptName);
if (StringUtil.equals(allPath, "Y")) {
script.setAllPath("Y");
} else {
script.setAllPath("");
}
script.setEnvTag(tenantScope);
script.setNeedAutoScan(needAutoScan);
if (StringUtil.isNotBlank(scopes)) {
for (String each : StringUtil.split(scopes, ",")) {
each = StringUtil.replace(each, " ", "");
script.addScope(each);
}
}
if (StringUtil.isNotBlank(content)) {
BaseOperationResult preLoadResult = syntaxCheck(script);
if (!preLoadResult.isSuccess()) {
baseOperationResult.setMessage(preLoadResult.getMessage());
return baseOperationResult;
}
}
if (StringUtil.contains(content, "new Bug")) {
baseOperationResult.setSuccess(false);
return baseOperationResult;
}
try {
Result<NewScript> result = newScriptManager.saveCustomScript(script);
if (result.isSuccess()) {
if (EnvUtil.isProdEnv() && EnvUtil.isLinux()) {
if (!needCreateTestRunScript) {
//省略部分内容XX
} else {
//省略部分内容XX
}
}
Boolean hasOldScript = processOldEngineRule(scriptName);
if (containsTryCatch) {
if (hasOldScript) {
//省略部分内容XX
} else {
//省略部分内容XX
}
} else {
if (hasOldScript) {
baseOperationResult.setMessage("XXX");
} else {
baseOperationResult.setMessage("保存成功!");
}
}
baseOperationResult.setId(script.getId());
processTenantRelation(script.getId(), tenantIdList, user.getLoginName());
if (!needCreateTestRunScript && needSubtypeMode
&& (StringUtil.equals(Enums.XX.COMMON, script.getScriptType())
|| (StringUtil.equals(Enums.XX.SCRIPT,
script.getScriptType())))) {
JSONArray subtypetipsArray = JSON.parseArray(subtypeandtip);
for (Object object : subtypetipsArray) {
//省略部分内容XX
}
}
} else {
baseOperationResult.setSuccess(false);
return baseOperationResult;
}
} catch (Exception e) {
baseOperationResult.setMessage("XX");
}
return baseOperationResult;
}
我该怎么做
public XXresult doSave( NewScriptDTO newScriptDTO) {
//0.构造结果
XXresult result=new XXresult() ;
try{
//1.脚本名检查
scriptNameCheck(newScriptDTO);
//2.脚本加载
loadScript(newScriptDTO);
//3.脚本保存
saveScript(newScriptDTO);
}catch(XXException e){
result.setSuccess(false)
result.setMessage("XXX");
return result;
}catch(Exception e){
result.setSuccess(false)
result.setMessage("XXX");
return result;
}
//操作完成
result.setSuccess(true)
result.setMessage("XXX");
return result;
}
/**检查脚本名*/
private void scriptNameCheck(NewScriptDTO newScriptDTO){
xxx
}
/**加载脚本*/
private void loadScript(NewScriptDTO newScriptDTO){
xxx
}
/**保存脚本*/
private void saveScript(NewScriptDTO newScriptDTO){
xxx
}
///////// 案例1,抽取频繁出现的条件a/////////
//修改前
if (条件1)
{
if (条件a)
{
// 执行a逻辑
}
}
else if(条件2)
{
if (条件a)
{
// 执行b逻辑
}
}
if (条件a)
{
// 执行c逻辑
}
//修改后
if (条件a)
{
if (条件1)
{
// 执行a逻辑
}
else if(条件2)
{
// 执行b逻辑
} // 执行c逻辑
}
///////// 案例2,优化逻辑判断顺序/////////
//修改前
if((条件1 && 条件2)|| !条件1){
return true;
}else{
return false;
}
//修改后
if(条件1 && !条件2){
return false;
}
return true;
//修改前
List list = XXX;
if (CollectionUtils.isEmpty(list)) {
for (XX item : list) {
if (item==null){
return;
}else{
// 逻辑a
}
}
//修改后
List list = XX;
list = Optional.ofNullable(list).orElse(new ArrayList<>());
list.stream().filter(Objects::nonNull).forEach(item->{
//逻辑a
});
}
结语
阿里云产品评测—阿里云容器镜像服务 ACR
免费试用体验面向容器镜像、Helm Chart 等符合 OCI 标准的云原生制品安全托管及高效分发平台,发布你的评测更有机会获得千元机械键盘,限量定制礼品。
点击阅读原文查看详情。
微信扫码关注该文公众号作者
戳这里提交新闻线索和高质量文章给我们。
来源: qq
点击查看作者最近其他文章