False positive java:S3516

  • ALM used: GitHub

  • CI system used: Jenkins

  • Reproduced in: SonarCloud, SonarLint in Eclipse

  • Languages of the repository: Java

  • Error observed
    Even though the filter method can return different values, the rule java:S3516 reports: Refactor this method to not always return the same value.

  • Workaround: removal of Lombok log removes the remark

  • Steps to reproduce

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Optional;
import lombok.extern.log4j.Log4j2;

@Log4j2
public class TestS3516 {
	boolean filter(SelectionKey selectionKey, String hostAddress) {
		if (hostAddress == null) {
			return true;
		}
		return getInetSocketAddress(selectionKey)
			.map(address -> address.getAddress().getHostAddress().equals(hostAddress)).orElse(false);
	}

	private Optional<InetSocketAddress> getInetSocketAddress(SelectionKey selectionKey) {
		SelectableChannel channel = selectionKey.channel();
		if (channel instanceof SocketChannel socketChannel) {
			try {
				return Optional.of(((InetSocketAddress) socketChannel.getRemoteAddress()));
			} catch (IOException e) {
				log.error("", e);
			}
		}
		return Optional.empty();
	}

}

Hi @lrozenblyum,

Thank you for reporting!
This is a known issue for us, and we have a ticket for it. SONARJAVA-3063
Until we fix this issue, and if it creates too much noise, you can mark it as False Positive or disable it in the Quality Profile.

All the best,

Irina

Hello @irina.batinic.
I think this case is different than [SONARJAVA-3063] - Jira

It’s reproduced even without try/catch:

package com.iqm.web.rtc.config.websocket;

import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Optional;

import lombok.extern.log4j.Log4j2;

@Log4j2
public class TestS3516 {
	boolean filter(SelectionKey selectionKey, String hostAddress) {
		if (hostAddress == null) {
			return true;
		}
		return getSth(selectionKey).map(address -> true).orElse(false);
	}

	private Optional<String> getSth(SelectionKey selectionKey) {
		SelectableChannel channel = selectionKey.channel();
		if (channel instanceof SocketChannel) {
 // if we remove the logging statement, filter is no longer marked as java:S3516
			log.info("Test");
			return Optional.of("test");
		}
		return Optional.empty();
	}

}

Hi @lrozenblyum,

Sorry, my bad!
This is the ticket SONARJAVA-4699

All the best,

Irina

1 Like

Thanks for sharing @irina.batinic!

1 Like