Skip to content

Add isNotEmpty Utility Methods to Improve Readability and Safety #35247

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ private static AbstractBeanDefinition parseComponentElement(Element element) {
factory.addPropertyValue("parent", parseComponent(element));

List<Element> childElements = DomUtils.getChildElementsByTagName(element, "component");
if (!CollectionUtils.isEmpty(childElements)) {
if (CollectionUtils.isNotEmpty(childElements)) {
parseChildComponents(childElements, factory);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import java.util.List;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.util.CollectionUtils;

public class ComponentFactoryBean implements FactoryBean<Component> {

Expand All @@ -35,7 +36,7 @@ public void setChildren(List<Component> children) {

@Override
public Component getObject() {
if (this.children != null && this.children.size() > 0) {
if (this.children != null && CollectionUtils.isNotEmpty(this.children)) {
for (Component child : children) {
this.parent.addComponent(child);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -571,7 +571,7 @@ else if (this.joinPointStaticPartArgumentIndex != -1) {
numBound++;
}

if (!CollectionUtils.isEmpty(this.argumentBindings)) {
if (CollectionUtils.isNotEmpty(this.argumentBindings)) {
// binding from pointcut match
if (jpMatch != null) {
PointcutParameter[] parameterBindings = jpMatch.getParameterBindings();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,7 @@ public void addAdvisors(Collection<Advisor> advisors) {
if (isFrozen()) {
throw new AopConfigException("Cannot add advisor: Configuration is frozen.");
}
if (!CollectionUtils.isEmpty(advisors)) {
if (CollectionUtils.isNotEmpty(advisors)) {
for (Advisor advisor : advisors) {
if (advisor instanceof IntroductionAdvisor introductionAdvisor) {
validateIntroductionAdvisor(introductionAdvisor);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -186,11 +186,11 @@ public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, C
RootBeanDefinition beanDefinition = registeredBean.getMergedBeanDefinition();
beanDefinition.resolveDestroyMethodIfNecessary();
LifecycleMetadata metadata = findLifecycleMetadata(beanDefinition, registeredBean.getBeanClass());
if (!CollectionUtils.isEmpty(metadata.initMethods)) {
if (CollectionUtils.isNotEmpty(metadata.initMethods)) {
String[] initMethodNames = safeMerge(beanDefinition.getInitMethodNames(), metadata.initMethods);
beanDefinition.setInitMethodNames(initMethodNames);
}
if (!CollectionUtils.isEmpty(metadata.destroyMethods)) {
if (CollectionUtils.isNotEmpty(metadata.destroyMethods)) {
String[] destroyMethodNames = safeMerge(beanDefinition.getDestroyMethodNames(), metadata.destroyMethods);
beanDefinition.setDestroyMethodNames(destroyMethodNames);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ AbstractBeanDefinition getBeanDefinition() {
protected AbstractBeanDefinition createBeanDefinition() {
AbstractBeanDefinition bd = new GenericBeanDefinition();
bd.setBeanClass(this.clazz);
if (!CollectionUtils.isEmpty(this.constructorArgs)) {
if (CollectionUtils.isNotEmpty(this.constructorArgs)) {
ConstructorArgumentValues cav = new ConstructorArgumentValues();
for (Object constructorArg : this.constructorArgs) {
cav.addGenericArgumentValue(constructorArg);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ public void run() {

@Override
public void destroy() {
if (!CollectionUtils.isEmpty(this.beanPostProcessors)) {
if (CollectionUtils.isNotEmpty(this.beanPostProcessors)) {
for (DestructionAwareBeanPostProcessor processor : this.beanPostProcessors) {
processor.postProcessBeforeDestruction(this.bean, this.beanName);
}
Expand Down Expand Up @@ -448,7 +448,7 @@ public static boolean hasDestroyMethod(Object bean, RootBeanDefinition beanDefin
* @param postProcessors the post-processor candidates
*/
public static boolean hasApplicableProcessors(Object bean, List<DestructionAwareBeanPostProcessor> postProcessors) {
if (!CollectionUtils.isEmpty(postProcessors)) {
if (CollectionUtils.isNotEmpty(postProcessors)) {
for (DestructionAwareBeanPostProcessor processor : postProcessors) {
if (processor.requiresDestruction(bean)) {
return true;
Expand All @@ -467,7 +467,7 @@ public static boolean hasApplicableProcessors(Object bean, List<DestructionAware
List<DestructionAwareBeanPostProcessor> processors, Object bean) {

List<DestructionAwareBeanPostProcessor> filteredPostProcessors = null;
if (!CollectionUtils.isEmpty(processors)) {
if (CollectionUtils.isNotEmpty(processors)) {
filteredPostProcessors = new ArrayList<>(processors.size());
for (DestructionAwareBeanPostProcessor processor : processors) {
if (processor.requiresDestruction(bean)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ public Configuration createConfiguration() throws IOException, TemplateException
config.setSettings(props);
}

if (!CollectionUtils.isEmpty(this.freemarkerVariables)) {
if (CollectionUtils.isNotEmpty(this.freemarkerVariables)) {
config.setAllSharedVariables(new SimpleHash(this.freemarkerVariables, config.getObjectWrapper()));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public abstract class AbstractFallbackCacheOperationSource implements CacheOpera

@Override
public boolean hasCacheOperations(Method method, @Nullable Class<?> targetClass) {
return !CollectionUtils.isEmpty(getCacheOperations(method, targetClass, false));
return CollectionUtils.isNotEmpty(getCacheOperations(method, targetClass, false));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -399,7 +399,7 @@ protected void clearMetadataCache() {
CacheOperationSource cacheOperationSource = getCacheOperationSource();
if (cacheOperationSource != null) {
Collection<CacheOperation> operations = cacheOperationSource.getCacheOperations(method, targetClass);
if (!CollectionUtils.isEmpty(operations)) {
if (CollectionUtils.isNotEmpty(operations)) {
return execute(invoker, method,
new CacheOperationContexts(operations, method, args, target, targetClass));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ default boolean isCandidateClass(Class<?> targetClass) {
* @see #getCacheOperations
*/
default boolean hasCacheOperations(Method method, @Nullable Class<?> targetClass) {
return !CollectionUtils.isEmpty(getCacheOperations(method, targetClass));
return CollectionUtils.isNotEmpty(getCacheOperations(method, targetClass));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,7 @@ public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)

@Override
public @Nullable BeanFactoryInitializationAotContribution processAheadOfTime(ConfigurableListableBeanFactory beanFactory) {
boolean hasPropertySourceDescriptors = !CollectionUtils.isEmpty(this.propertySourceDescriptors);
boolean hasPropertySourceDescriptors = CollectionUtils.isNotEmpty(this.propertySourceDescriptors);
boolean hasImportRegistry = beanFactory.containsBean(IMPORT_REGISTRY_BEAN_NAME);
boolean hasBeanRegistrars = !this.beanRegistrars.isEmpty();
if (hasPropertySourceDescriptors || hasImportRegistry || hasBeanRegistrars) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -914,7 +914,7 @@ protected void registerListeners() {
// Publish early application events now that we finally have a multicaster...
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
if (CollectionUtils.isNotEmpty(earlyEventsToProcess)) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -591,7 +591,7 @@ public void start() {
for (LifecycleGroupMember member : this.members) {
doStart(this.lifecycleBeans, member.name, this.autoStartupOnly, futures);
}
if (concurrentStartup != null && !CollectionUtils.isEmpty(futures)) {
if (concurrentStartup != null && CollectionUtils.isNotEmpty(futures)) {
try {
CompletableFuture.allOf(futures.toArray(new CompletableFuture<?>[0]))
.get(concurrentStartup, TimeUnit.MILLISECONDS);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ public class ReloadableResourceBundleMessageSource extends AbstractResourceBased
* @since 6.1
*/
public void setFileExtensions(List<String> fileExtensions) {
Assert.isTrue(!CollectionUtils.isEmpty(fileExtensions), "At least one file extension is required");
Assert.isTrue(CollectionUtils.isNotEmpty(fileExtensions), "At least one file extension is required");
for (String extension : fileExtensions) {
if (!extension.startsWith(".")) {
throw new IllegalArgumentException("File extension '" + extension + "' should start with '.'");
Expand Down Expand Up @@ -379,18 +379,18 @@ protected List<String> calculateFilenamesForLocale(String basename, Locale local
StringBuilder temp = new StringBuilder(basename);

temp.append('_');
if (language.length() > 0) {
if (StringUtils.hasLength(language)) {
temp.append(language);
result.add(0, temp.toString());
}

temp.append('_');
if (country.length() > 0) {
if (StringUtils.hasLength(country)) {
temp.append(country);
result.add(0, temp.toString());
}

if (variant.length() > 0 && (language.length() > 0 || country.length() > 0)) {
if (StringUtils.hasLength(variant) && (StringUtils.hasLength(language) || StringUtils.hasLength(country))) {
temp.append('_').append(variant);
result.add(0, temp.toString());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ public static MBeanServer locateMBeanServer(@Nullable String agentId) throws MBe
// null means any registered server, but "" specifically means the platform server
if (!"".equals(agentId)) {
List<MBeanServer> servers = MBeanServerFactory.findMBeanServer(agentId);
if (!CollectionUtils.isEmpty(servers)) {
if (CollectionUtils.isNotEmpty(servers)) {
// Check to see if an MBeanServer is registered.
if (servers.size() > 1 && logger.isInfoEnabled()) {
logger.info("Found more than one MBeanServer instance" +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -395,11 +395,11 @@ public void addOneTimeTask(DelayedTask task) {
* @since 3.2
*/
public boolean hasTasks() {
return (!CollectionUtils.isEmpty(this.triggerTasks) ||
!CollectionUtils.isEmpty(this.cronTasks) ||
!CollectionUtils.isEmpty(this.fixedRateTasks) ||
!CollectionUtils.isEmpty(this.fixedDelayTasks) ||
!CollectionUtils.isEmpty(this.oneTimeTasks));
return (CollectionUtils.isNotEmpty(this.triggerTasks) ||
CollectionUtils.isNotEmpty(this.cronTasks) ||
CollectionUtils.isNotEmpty(this.fixedRateTasks) ||
CollectionUtils.isNotEmpty(this.fixedDelayTasks) ||
CollectionUtils.isNotEmpty(this.oneTimeTasks));
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,7 @@ public List<String> getParameterNames(Method method) {
}

private void closeMappingStreams(@Nullable List<InputStream> mappingStreams){
if (!CollectionUtils.isEmpty(mappingStreams)) {
if (CollectionUtils.isNotEmpty(mappingStreams)) {
for (InputStream stream : mappingStreams) {
try {
stream.close();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,7 @@ private AbstractNamingEnumeration(SimpleNamingContext context, String proot) thr
}
}
}
if (contents.size() == 0) {
if (contents.isEmpty()) {
throw new NamingException("Invalid root: [" + context.root + proot + "]");
}
this.iterator = contents.values().iterator();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ public int getStepArgument(final int index) {
* @return the corresponding TypePath object, or {@literal null} if the path is empty.
*/
public static TypePath fromString(final String typePath) {
if (typePath == null || typePath.length() == 0) {
if (typePath == null || typePath.isEmpty()) {
return null;
}
int typePathLength = typePath.length();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public CallbackHelper(Class superclass, Class[] interfaces) {
abstract protected Object getCallback(Method method);

public Callback[] getCallbacks() {
if (callbacks.size() == 0) {
if (callbacks.isEmpty()) {
return new Callback[0];
}
if (callbacks.get(0) instanceof Callback) {
Expand All @@ -75,7 +75,7 @@ public Callback[] getCallbacks() {
}

public Class[] getCallbackTypes() {
if (callbacks.size() == 0) {
if (callbacks.isEmpty()) {
return new Class[0];
}
if (callbacks.get(0) instanceof Callback) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -755,7 +755,7 @@ public void generateClass(ClassVisitor v) throws Exception {
*/
protected void filterConstructors(Class sc, List constructors) {
CollectionUtils.filter(constructors, new VisibilityPredicate(sc, true));
if (constructors.size() == 0) {
if (constructors.isEmpty()) {
throw new IllegalArgumentException("No visible constructors in " + sc);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

/**
* Helper class for loading a localized resource,
Expand Down Expand Up @@ -100,20 +101,20 @@ public Resource findLocalizedResource(String name, String extension, @Nullable L
String variant = locale.getVariant();

// Check for file with language, country and variant localization.
if (variant.length() > 0) {
if (StringUtils.hasLength(variant)) {
String location =
name + this.separator + lang + this.separator + country + this.separator + variant + extension;
resource = this.resourceLoader.getResource(location);
}

// Check for file with language and country localization.
if ((resource == null || !resource.exists()) && country.length() > 0) {
if ((resource == null || !resource.exists()) && StringUtils.hasLength(country)) {
String location = name + this.separator + lang + this.separator + country + extension;
resource = this.resourceLoader.getResource(location);
}

// Check for document with language localization.
if ((resource == null || !resource.exists()) && lang.length() > 0) {
if ((resource == null || !resource.exists()) && StringUtils.hasLength(lang)) {
String location = name + this.separator + lang + extension;
resource = this.resourceLoader.getResource(location);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.PlaceholderResolutionException;
import org.springframework.util.ReflectionUtils;

Expand Down Expand Up @@ -80,7 +81,7 @@ public void processPropertySource(PropertySourceDescriptor descriptor) throws IO
String name = descriptor.name();
String encoding = descriptor.encoding();
List<String> locations = descriptor.locations();
Assert.isTrue(locations.size() > 0, "At least one @PropertySource(value) location is required");
Assert.isTrue(CollectionUtils.isNotEmpty(locations), "At least one @PropertySource(value) location is required");
boolean ignoreResourceNotFound = descriptor.ignoreResourceNotFound();
PropertySourceFactory factory = (descriptor.propertySourceFactory() != null ?
instantiateClass(descriptor.propertySourceFactory()) : defaultPropertySourceFactory);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -348,7 +348,7 @@ private boolean isPotentialMatch(String path, String[] pattDirs) {
pos += skipped;
skipped = skipSegment(path, pos, pattDir);
if (skipped < pattDir.length()) {
return (skipped > 0 || (pattDir.length() > 0 && isWildcardChar(pattDir.charAt(0))));
return (skipped > 0 || (StringUtils.hasLength(pattDir) && isWildcardChar(pattDir.charAt(0))));
}
pos += skipped;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -753,7 +753,7 @@ public static String classNamesToString(@Nullable Collection<Class<?>> classes)
* @see StringUtils#toStringArray
*/
public static Class<?>[] toClassArray(@Nullable Collection<Class<?>> collection) {
return (!CollectionUtils.isEmpty(collection) ? collection.toArray(EMPTY_CLASS_ARRAY) : EMPTY_CLASS_ARRAY);
return (CollectionUtils.isNotEmpty(collection) ? collection.toArray(EMPTY_CLASS_ARRAY) : EMPTY_CLASS_ARRAY);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,27 @@ public static boolean isEmpty(@Nullable Map<?, ? extends @Nullable Object> map)
return (map == null || map.isEmpty());
}

/**
* Return {@code true} if the supplied Collection is not {@code null} and not empty.
* Otherwise, return {@code false}.
* @param collection the Collection to check
* @return whether the given Collection is not empty
*/
public static boolean isNotEmpty(@Nullable Collection<? extends @Nullable Object> collection) {
return (collection != null && !collection.isEmpty());
}

/**
* Return {@code true} if the supplied Map is not {@code null} and not empty.
* Otherwise, return {@code false}.
* @param map the Map to check
* @return whether the given Map is not empty
*/
public static boolean isNotEmpty(@Nullable Map<?, ? extends @Nullable Object> map) {
return (map != null && !map.isEmpty());
}

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mdeinum
Added isNotEmpty methods to CollectionUtils as suggested to improve readability and avoid !isEmpty() usage


/**
* Instantiate a new {@link HashMap} with an initial capacity
* that can accommodate the specified number of elements without
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public CommonsLogWriter(Log logger) {


public void write(char ch) {
if (ch == '\n' && this.buffer.length() > 0) {
if (ch == '\n' && StringUtils.hasLength(this.buffer)) {
logger.debug(this.buffer.toString());
this.buffer.setLength(0);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ public MimeType(String type, String subtype, @Nullable Map<String, String> param
checkToken(subtype);
this.type = type.toLowerCase(Locale.ROOT);
this.subtype = subtype.toLowerCase(Locale.ROOT);
if (!CollectionUtils.isEmpty(parameters)) {
if (CollectionUtils.isNotEmpty(parameters)) {
Map<String, String> map = new LinkedCaseInsensitiveMap<>(parameters.size(), Locale.ROOT);
parameters.forEach((parameter, value) -> {
checkParameters(parameter, value);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ else if (ch == '"') {
nextIndex++;
}
String parameter = mimeType.substring(index + 1, nextIndex).trim();
if (parameter.length() > 0) {
if (StringUtils.hasLength(parameter)) {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use StringUtils already has a way to check
@mdeinum

if (parameters == null) {
parameters = new LinkedHashMap<>(4);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ public void forEach(BiConsumer<? super K, ? super V> action) {
}

private @Nullable V adaptValue(@Nullable List<V> values) {
if (!CollectionUtils.isEmpty(values)) {
if (CollectionUtils.isNotEmpty(values)) {
return values.get(0);
}
else {
Expand Down
Loading