Thursday, May 12, 2022

Maven plugin configuration without editing POM xml

 Usually maven plug-ins are configured by modifying the POM xml file. For example, in the following configuration POM file is edited to set the expected source and target for the maven-compiler-plugin

<plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin>


In some scenario, we may not have option to modify the POM file. In those conditions, we can configure the plugin by adding the configuration in the command line. For example, in the command below the maven-compiler-plugin is configured using command line arguments without modifying the POM file.

mvn install -Dmaven.compiler.source=1.7 -Dmaven.compiler.target=1.7


Note: The configuration set in the command line is not same as in the POM file. We should set User property in the command line. The User property should be available in the plugin documentation. For example, https://maven.apache.org/plugins/maven-compiler-plugin/compile-mojo.html


Friday, February 11, 2022

Clean code - Optional comparison

Following is an example of writing less verbose and clean code for optional value comparison. This code (isAbc2) avoids unnecessary IF condition. The code sample also has a way to compare clean code and legacy code for a safety.


import java.util.Optional;

public class C1 {
	public static void main(String[] arg) {
		Optional val = Optional.of("abc");
		Optional noval = Optional.empty();
		Optional def = Optional.of("def");
		
		System.out.println(isAbc1(val) == isAbc2(val));
		System.out.println(isAbc1(noval) == isAbc2(noval));
		System.out.println(isAbc1(def) == isAbc2(def));
		
	}
	
	private static boolean isAbc1(Optional op) {
		if(op.isPresent()) {
			return op.get().equals("abc");
		}
		return false;
	}

	// clean code
	private static boolean isAbc2(Optional op) {
		return op.map("abc"::equals).orElse(false);
	}
}


The result of the above code in JDK 11.

true
true
true