Sample

int-d62fbb4fbc9c-I12

Inline all eligible single-use intermediate local variables

Matched original source

Lines159

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Scalabrino0.2420–1; higher is more readable
Dorn0.0480–1; higher is more readable
Mi0.090–1; higher is more readable
LLOC47Logical lines; fewer is more readable
DeepSeek V4 Pro15.670–20; mean of three runs
GPT-6.1 Sol16.330–20; mean of three runs
BTTF0.3760–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(); 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(), ((testBean.enforceOverride() ? REPLACE : REPLACE_OR_CREATE)), 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. for (String methodName : methodNames) { 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); findMethods(methods, clazz, (method -> (Modifier.isStatic(method.getModifiers()) && supportedNames.contains(method.getName()) && methodReturnType.isAssignableFrom(method.getReturnType())))); 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.7598.585−250.753
Source linesThe number of non-empty source lines.159+63.6
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.05−7.574

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

Score0.242

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.160−4.629
Indentation frequencyHow rapidly indentation changes from line to line.120+3.414
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.164.988−3.323
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.120−2.333
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.164.975+1.857
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.158.873+1.811
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.083+0.14

Intercept 0.07 + feature contributions = -2.993 (log-odds).
Score = sigmoid(-2.993) = 0.048.

Score0.09
Score47
Run 1

The code has a logical structure with clear separation of concerns and good method decomposition. The Javadoc is helpful, and method names are descriptive. However, readability is hindered by the deeply nested findTestBeanFactoryMethod method, which has multiple levels of indentation due to conditional blocks and error handling. The createHandler method has a long return statement with multiple arguments and ternary operators, reducing clarity. Some sections have excessive blank lines, and the fully-qualified method name parsing logic is complex with multiple string manipulations. The code mixes high-level orchestration with low-level implementation details, making it harder to follow. The use of lambda expressions for assertions improves conciseness but adds to nesting depth. Variable names are generally good, and the code follows Spring conventions, but the overall flow could be improved with additional helper methods to reduce complexity.

Run 2

The code is generally well-structured and readable. It uses clear method names and logical separation, with moderate nesting that is mostly manageable. The main readability weakness is the long 'findTestBeanFactoryMethod' method, which combines fully-qualified name parsing, reflection lookup, validation, and error handling into one dense block. Some conditional logic and lambda expressions add minor complexity. Variable naming is descriptive, and comments explain the higher-level intent well. Action granularity is reasonable, though a few statements pack multiple operations into a single line. Overall, the code is maintainable but would benefit from extracting the fully-qualified method resolution into a separate helper method to reduce cognitive load.

Run 3

The code is well-structured with clear separation between the handler creation and factory method discovery. Methods are focused and each performs a single logical operation, enhancing readability. Nesting is mostly flat, though the fully-qualified method name parsing block contains several nested conditions and exception handling that slightly increase complexity. The intent of each section is clear, supported by meaningful method names and Javadoc. The code is reasonably concise, though some repetitive assertion messages and the two-pass method name resolution logic add length. Action granularity is good, with one main action per line in most cases. Reading flow is natural, moving from handler creation to method lookup details. Minor deductions come from the dense fully-qualified name processing and the somewhat tangled dual search strategy (explicit names vs. candidates).

Run 1

Code Structure: Cohesive processor with clearly separated handler creation, factory lookup, and recursive search helpers; the main lookup method carries several responsibilities. Nesting: Generally shallow, though fully qualified name handling combines a loop, conditional, and try/catch. Clarity of intent: Descriptive names, documentation, comments, and informative errors make the purpose clear. However, the documented no-argument requirement is not explicit in the local method filter, and ambiguity validation counts distinct names rather than methods, making behavior less obvious. Code length: Mostly justified by validation and documentation, but redundant parentheses, copied sets, and a long constructor call add clutter. Action granularity: Most lines perform one action; chained stream operations and compound assertions remain reasonably readable. Reading flow: Validation, external lookup, hierarchy search, and final checks follow a logical sequence. Long expressions and uneven whitespace occasionally interrupt scanning.

Run 2

Code Structure: Responsibilities are logically separated into handler creation, factory-method resolution, and recursive searching, though the main resolution method combines several distinct tasks. Nesting: Generally shallow, with moderate nesting in the qualified-name loop and its try/catch block. Clarity of intent: Descriptive names, explanatory comments, and detailed Javadoc make the purpose clear; mutable search sets and subtle method-selection rules require closer inspection. Code length: Mostly justified by validation and documentation, but repeated error formatting and some redundant parentheses add noise. Action granularity: Most lines perform one action, although compound assertions, lambda predicates, and the long handler-construction line are dense. Reading flow: Processing moves naturally from validation through candidate discovery to selection, but long expressions, inconsistent whitespace, and transitions between external and local method searches slightly disrupt scanning.

Run 3

Code Structure: Responsibilities are logically divided between handler creation, factory-method lookup, and recursive discovery, though the main lookup method handles several concerns. Nesting: Generally shallow; fully qualified name processing adds moderate nesting through a loop, conditional, and try/catch. Clarity of intent: Descriptive names, detailed Javadoc, and helpful comments clearly explain the conventions and search strategy. Compound predicates and mutable method/name sets require closer attention. Code length: Mostly justified by validation and documentation, but some redundant parentheses and intermediate collections add noise. Action granularity: Most lines perform one action; the long handler constructor call and chained stream expressions are denser. Reading flow: Validation, discovery, and selection follow a natural sequence, with consistent formatting overall. Long argument lists, wrapped assertion lambdas, and minor whitespace inconsistencies slightly interrupt scanning.