Sample

int-791f1f4dfff2-I13

Lower every eligible classic and enhanced for loop to a while loop

Matched original source

Lines163

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Scalabrino0.2520–1; higher is more readable
Dorn0.1450–1; higher is more readable
Mi0.0820–1; higher is more readable
LLOC51Logical lines; fewer is more readable
DeepSeek V4 Pro110–20; mean of three runs
GPT-6.1 Sol15.670–20; mean of three runs
BTTF0.4150–1; higher is more readable

Views

Source code

package org.springframework.test.context.bean.override.convention; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.springframework.core.MethodIntrospector; import org.springframework.core.ResolvableType; import org.springframework.test.context.TestContextAnnotationUtils; import org.springframework.test.context.bean.override.BeanOverrideProcessor; import org.springframework.test.context.bean.override.BeanOverrideStrategy; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; import org.springframework.util.ReflectionUtils.MethodFilter; import static org.springframework.test.context.bean.override.BeanOverrideStrategy.REPLACE; import static org.springframework.test.context.bean.override.BeanOverrideStrategy.REPLACE_OR_CREATE; /** * {@link BeanOverrideProcessor} implementation for {@link TestBean @TestBean} * support, which creates a {@link TestBeanOverrideHandler} for annotated * fields in a given class and ensures that a corresponding static factory method * exists, according to the {@linkplain TestBean documented conventions}. * * @author Simon Baslé * @author Sam Brannen * @author Stephane Nicoll * @since 6.2 */ class TestBeanOverrideProcessor implements BeanOverrideProcessor { @Override public TestBeanOverrideHandler createHandler(Annotation overrideAnnotation, Class<?> testClass, Field field) { if (!(overrideAnnotation instanceof TestBean testBean)) { throw new IllegalStateException("Invalid annotation passed to %s: expected @TestBean on field %s.%s" .formatted(getClass().getSimpleName(), field.getDeclaringClass().getName(), field.getName())); } String beanName = (!testBean.name().isBlank() ? testBean.name() : null); String methodName = testBean.methodName(); BeanOverrideStrategy strategy = (testBean.enforceOverride() ? REPLACE : REPLACE_OR_CREATE); Method factoryMethod; if (!methodName.isBlank()) { // If the user specified an explicit method name, search for that. factoryMethod = findTestBeanFactoryMethod(field.getDeclaringClass(), field.getType(), methodName); } else { // Otherwise, search for candidate factory methods whose names match either // the field name or the explicit bean name (if any). List<String> candidateMethodNames = new ArrayList<>(); candidateMethodNames.add(field.getName()); if (beanName != null) { candidateMethodNames.add(beanName); } factoryMethod = findTestBeanFactoryMethod(field.getDeclaringClass(), field.getType(), candidateMethodNames); } return new TestBeanOverrideHandler( field, ResolvableType.forField(field, testClass), beanName, testBean.contextName(), strategy, factoryMethod); } /** * Find a test bean factory {@link Method} for the given {@link Class}. * <p>Delegates to {@link #findTestBeanFactoryMethod(Class, Class, Collection)}. */ Method findTestBeanFactoryMethod(Class<?> clazz, Class<?> methodReturnType, String... methodNames) { return findTestBeanFactoryMethod(clazz, methodReturnType, List.of(methodNames)); } /** * Find a test bean factory {@link Method} for the given {@link Class}, which * meets the following criteria. * <ul> * <li>The method is static.</li> * <li>The method does not accept any arguments.</li> * <li>The method's return type matches the supplied {@code methodReturnType}.</li> * <li>The method's name is one of the supplied {@code methodNames}.</li> * </ul> * <p>This method traverses up the type hierarchy of the given class in search * of the factory method, beginning with the class itself and then searching * implemented interfaces and superclasses. If a factory method is not found * in the type hierarchy, this method will also search the enclosing class * hierarchy if the class is a nested class. * <p>If multiple factory methods are found that match the search criteria, * an exception is thrown. * @param clazz the class in which to search for the factory method * @param methodReturnType the return type for the factory method * @param methodNames a set of supported names for the factory method * @return the corresponding factory method * @throws IllegalStateException if a matching factory method cannot * be found or multiple methods match */ Method findTestBeanFactoryMethod(Class<?> clazz, Class<?> methodReturnType, Collection<String> methodNames) { Assert.notEmpty(methodNames, "At least one candidate method name is required"); Set<Method> methods = new LinkedHashSet<>(); Set<String> originalNames = new LinkedHashSet<>(methodNames); // Process fully-qualified method names first. { java.util.Iterator<?> loopIterator = (methodNames).iterator(); while (loopIterator.hasNext()) { String methodName = (String) loopIterator.next(); int indexOfHash = methodName.lastIndexOf('#'); if (indexOfHash != -1) { String className = methodName.substring(0, indexOfHash).trim(); Assert.hasText(className, () -> "No class name present in fully-qualified method name: " + methodName); String methodNameToUse = methodName.substring(indexOfHash + 1).trim(); Assert.hasText(methodNameToUse, () -> "No method name present in fully-qualified method name: " + methodName); Class<?> declaringClass; try { declaringClass = ClassUtils.forName(className, getClass().getClassLoader()); } catch (ClassNotFoundException | LinkageError ex) { throw new IllegalStateException( "Failed to load class for fully-qualified method name: " + methodName, ex); } Method externalMethod = ReflectionUtils.findMethod(declaringClass, methodNameToUse); Assert.state(externalMethod != null && Modifier.isStatic(externalMethod.getModifiers()) && methodReturnType.isAssignableFrom(externalMethod.getReturnType()), () -> "No static method found named %s in %s with return type %s".formatted( methodNameToUse, className, methodReturnType.getName())); methods.add(externalMethod); originalNames.remove(methodName); } } } Set<String> supportedNames = new LinkedHashSet<>(originalNames); MethodFilter methodFilter = method -> (Modifier.isStatic(method.getModifiers()) && supportedNames.contains(method.getName()) && methodReturnType.isAssignableFrom(method.getReturnType())); findMethods(methods, clazz, methodFilter); String methodNamesDescription = supportedNames.stream() .map(name -> name + "()").collect(Collectors.joining(" or ")); Assert.state(!methods.isEmpty(), () -> "No static method found named %s in %s with return type %s".formatted( methodNamesDescription, clazz.getName(), methodReturnType.getName())); long uniqueMethodNameCount = methods.stream().map(Method::getName).distinct().count(); Assert.state(uniqueMethodNameCount == 1, () -> "Found %d competing static methods named %s in %s with return type %s".formatted( uniqueMethodNameCount, methodNamesDescription, clazz.getName(), methodReturnType.getName())); return methods.iterator().next(); } private static Set<Method> findMethods(Set<Method> methods, Class<?> clazz, MethodFilter methodFilter) { methods.addAll(MethodIntrospector.selectMethods(clazz, methodFilter)); if (methods.isEmpty() && TestContextAnnotationUtils.searchEnclosingClass(clazz)) { findMethods(methods, clazz.getEnclosingClass(), methodFilter); } return methods; } }

Loading feature diagnosis…

Source regions

Feature contributions

Feature contributions

FeatureValueContribution
(log-odds)
Halstead volumeHow much symbolic information the code contains. It combines the total number of operators and values with the number of distinct ones.7922.715−261.45
Source linesThe number of non-empty source lines.163+65.2
Byte entropyHow varied the bytes in the source text are. Repeated bytes give a lower value; a more even mixture gives a higher value.5.03−7.546

Intercept 8.87 + feature contributions = -194.925 (log-odds).
Score = sigmoid(-194.925) = 0.

Score0.252

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.164−4.77
Indentation frequencyHow rapidly indentation changes from line to line.124+3.552
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.124−2.425
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.162.915+1.867
Identifier layout (horizontal)How rapidly the visual pattern of identifier characters changes from left to right. It measures spatial frequency, not the meaning of the names.116.957−1.289
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.116.988+1.083
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.083+0.139

Intercept 0.07 + feature contributions = -1.772 (log-odds).
Score = sigmoid(-1.772) = 0.145.

Score0.082
Score51
Run 1

The code is reasonably structured with clear class responsibilities and good Javadoc, but several parts harm readability. The main `createHandler` method is straightforward, but the `findTestBeanFactoryMethod` method becomes tangled in a verbose block that manually iterates with a raw `Iterator<?>` while removing from a set, which is less readable than using a stream or a for-loop. Variable names like `indexOfHash` and `methodNameToUse` are not ideal. Nesting is moderate; the inner block has multiple levels of ifs and nested method calls, reducing flatness. The code mixes multiple actions per line in some places, especially the long boolean expressions and stream collection. The recursive `findMethods` is compact but not obviously clear. Imports are ordered but the `java.util.Iterator` declaration in the middle of a method is awkward. Overall the code is maintainable but falls short of high readability due to the convoluted fully-qualified name parsing section and occasional dense logic.

Run 2

The code has clear intent and good documentation, but readability is significantly harmed by a few factors. The fully-qualified method name block uses an unnecessarily verbose loop with a raw `java.util.Iterator` and casts, disrupting the reading flow. The `findMethods` method uses recursion and mutates a passed-in `Set`, which obscures control flow. Variable names like `indexOfHash` and `methodNameToUse` are slightly awkward. Several lines are very long, and the method's branching logic (explicit method name vs. candidates, fully-qualified vs. simple names) creates moderate cognitive load. On the positive side, the class structure is logical, nesting is mostly flat, and the JavaDoc clearly explains the search conventions and error conditions.

Run 3

The code has some positive aspects: clear package structure, descriptive method names, and good Javadoc documentation. However, it suffers from significant readability issues. The code is overly long and verbose, with unnecessary iterators and concatenation for fully-qualified method names that could be simplified using streams and modern Java features. The nested logic in the fully-qualified method name processing adds depth and complexity. Multiple actions are packed into dense lines, reducing clarity. The constructor call to TestBeanOverrideHandler is a long single line with too many parameters, and the overall flow jumps between string parsing, exception handling, and method filtering. The code combines multiple responsibilities in one method, making it harder to follow. While the intent is documented, the implementation uses convoluted approaches that hinder understanding.

Run 1

Code Structure: Responsibilities are logically divided into handler creation, factory-method lookup, and hierarchy traversal, though fully qualified name handling makes one lookup method bulky. Nesting: Most code is shallow, but the extra scope, explicit iterator loop, conditional, and try/catch create a noticeably nested section. Clarity of intent: Descriptive names, Javadoc, comments, and informative exceptions explain the purpose well; reflection and compound predicates require careful reading. Code length: Generally reasonable, but the raw iterator, cast, redundant scope, and lengthy inline parsing could be simplified or extracted. Action granularity: Statements generally perform one action per line, with readable multiline expressions. Reading flow: Validation, candidate collection, searching, and result checks follow a natural sequence. Inconsistent indentation in the iterator block and dense assertion lambdas interrupt that flow.

Run 2

Code Structure: Responsibilities are logically split between handler creation, factory-method lookup, and hierarchy traversal, though the main lookup method is somewhat overloaded. Nesting: Mostly shallow, but fully qualified name processing adds an unnecessary block, explicit iterator loop, conditional, and try/catch. Clarity of intent: Descriptive names, documentation, comments, and informative errors make the purpose clear; however, documented zero-argument and uniqueness requirements are not clearly reflected in the local filtering and validation. Code length: Generally justified, with some verbosity from iterator boilerplate and repeated error formatting. Action granularity: Most lines perform one action, while compound predicates and stream chains require slightly more concentration. Reading flow: Processing follows a natural sequence from validation to discovery and selection, but inconsistent indentation in the iterator block and dense multiline assertions interrupt otherwise consistent formatting.

Run 3

Code Structure: Clear separation between handler creation, factory-method lookup, and recursive enclosing-class search, though fully qualified name processing crowds the main lookup method. Nesting: Mostly shallow, but the redundant scoped block, explicit iterator loop, conditional, and try/catch introduce a noticeably nested section. Clarity of intent: Descriptive names, Javadoc, comments, and informative assertions explain the purpose well; however, documented zero-argument and multiple-match constraints are not clearly reflected in the filtering and validation logic. Code length: Generally appropriate, but the iterator boilerplate and lengthy inline assertions could be simplified or extracted. Action granularity: Most statements perform one action, with compound predicates and fluent stream expressions remaining reasonably readable. Reading flow: The progression from annotation validation to candidate selection, lookup, and handler creation is natural. Inconsistent indentation in the iterator block and long wrapped expressions interrupt an otherwise coherent style.