gpt4 book ai didi

java - 干净的代码,如何改进一个类

转载 作者:行者123 更新时间:2023-12-01 18:05:28 24 4
gpt4 key购买 nike

我有我的 CommandFormatValidator 类,它检查输入的字符串是否符合任何预定义的模式。随着时间的推移,类实现了越来越多的新模式,导致了类的以下形式:

import java.util.StringTokenizer;
import java.util.regex.Pattern;

public class CommandFormatValidator {

private Pattern adlPatternAll = Pattern
.compile("^ACTV/(READ|ADD|DEL|RPL)/ADL.*");

private Pattern adlPatternAddDefault = Pattern
.compile("^ACTV/ADD/ADL/(DFLTTY((/([A-Z0-9]{7})){1,5})|DFLMIN(/[0-9]{1,4}))");

private Pattern adlPatternDeleteTtymailGeneral = Pattern
.compile("^ACTV/(DEL|READ)/ADL/TTYMAIL(/[A-Z0-9]{7})?");

//around 20 more pattern declarations...

public void validate(Object payload){

String command = (String)payload;

if (adlPatternAll.matcher(command).matches()) {
if (!adlPatternAddDefault.matcher(command).matches()) {
if (!adlPatternAddCityTty.matcher(command).matches()) {
if (!adlPatternAddCityFltTty.matcher(command).matches()) {
if (!adlPatternAdd.matcher(command).matches()) {
if (!adlPatternDelDefault.matcher(command).matches()) {
if (!adlPatternDel.matcher(command).matches()) {
if (!adlPatternDelCityFltTty.matcher(command).matches()) {
if (!adlPatternRpl.matcher(command).matches()) {
if (!adlPatternRead.matcher(command).matches()) {
if (!adlPatternReadCityFlt.matcher(command).matches()) {
if(!adlPatternAddTtymail.matcher(command).matches()) {
if( !adlPatternDeleteTtymailGeneral.matcher(command).matches()) {
if (!adlPatternDeleteTtymail.matcher(command).matches()) {
throw new ServiceException(CommandErrors.INVALID_FORMAT);
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}

现在我想清理这个类。有谁知道我怎样才能实现这一目标?我将特别感谢任何可以应用于我的案例的设计模式。

最佳答案

您可以将它们全部列出在一个数组中,然后迭代该数组。

顺便说一句:使用 matches() 时不需要 ^ anchor 。

不知道您是否在第一次测试中错过了!,但这里没有:

public class CommandFormatValidator {

private Pattern adlPatternAll = Pattern
.compile("^ACTV/(READ|ADD|DEL|RPL)/ADL.*");

private Pattern adlPatternAddDefault = Pattern
.compile("^ACTV/ADD/ADL/(DFLTTY((/([A-Z0-9]{7})){1,5})|DFLMIN(/[0-9]{1,4}))");

private Pattern adlPatternDeleteTtymailGeneral = Pattern
.compile("^ACTV/(DEL|READ)/ADL/TTYMAIL(/[A-Z0-9]{7})?");

//around 20 more pattern declarations...

private Pattern[] adlAll = { adlPatternAddDefault
, adlPatternDeleteTtymailGeneral
//more
};

public void validate(Object payload){
String command = (String)payload;
if (! adlPatternAll.matcher(command).matches())
return;
for (Pattern p : adlAll)
if (p.matcher(command).matches())
return;
throw new ServiceException(CommandErrors.INVALID_FORMAT);
}
}

关于java - 干净的代码,如何改进一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36797100/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com