在很多情况下,我都有一个很长的布尔表达式来求值:
fun clickClickableSpan(textToClick: CharSequence): ViewAction {
return object : ViewAction {
override fun getConstraints(): Matcher<View> {
return Matchers.instanceOf(TextView::class.java)
}
override fun getDescription(): String {
return "clicking on a ClickableSpan";
}
override fun perform(uiController: UiController, view: View) {
val textView = view as TextView
val spannableString = textView.text as SpannableString
if (spannableString.isEmpty()) {
// TextView is empty, nothing to do
throw NoMatchingViewException.Builder()
.includeViewHierarchy(true)
.withRootView(textView)
.build();
}
// Get the links inside the TextView and check if we find textToClick
val spans = spannableString.getSpans(0, spannableString.length, ClickableSpan::class.java)
if (spans.isNotEmpty()) {
var spanCandidate: ClickableSpan
for (span: ClickableSpan in spans) {
spanCandidate = span
val start = spannableString.getSpanStart(spanCandidate)
val end = spannableString.getSpanEnd(spanCandidate)
val sequence = spannableString.subSequence(start, end)
if (textToClick.toString().equals(sequence.toString())) {
span.onClick(textView)
return;
}
}
}
// textToClick not found in TextView
throw NoMatchingViewException.Builder()
.includeViewHierarchy(true)
.withRootView(textView)
.build()
}
}
}
这应该返回一个布尔值!
a,b,c,d,e和f是简单的相等比较,并且都不同。 这持续了12行,给我带来了44的圈复杂度我试图查看Map对象以降低复杂性,但没有找到解决方法。
如何减少这种表达式的复杂性?
答案 0 :(得分:2)
您无法降低给定表达式的复杂度。
一种较慢的方法(但可能更结构化)是对表达式进行分组,并对外部数组使用Array#some
进行评估,对内部数组使用Array#every
进行评估。
return [[a, b, c], [d, e, f]].some(a => a.every(Boolean));