skylot / jadx

Dex to Java decompiler

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[feature] Can Jadx reduce excessively long statements with nested ternary operators

DecompExplorer opened this issue · comments

Describe your idea

Description:

Hi, I've observed that Jadx sometimes produces excessively long statements with nested ternary operators, which can impact code readability and understandability.

Here is an example:

The following code snippet is from org/apache/commons/codec/binary/Conversion.java in the project commons-lang

public static char binaryToHexDigitMsb0_4bits(final boolean[] src, final int srcPos) {
	...
	if (src[srcPos + 3]) {
		if (src[srcPos + 2]) {
			if (src[srcPos + 1]) {
				return src[srcPos] ? 'f' : '7';
			}
			return src[srcPos] ? 'b' : '3';
		}
		if (src[srcPos + 1]) {
			return src[srcPos] ? 'd' : '5';
		}
		return src[srcPos] ? '9' : '1';
	}
	if (src[srcPos + 2]) {
		if (src[srcPos + 1]) {
			return src[srcPos] ? 'e' : '6';
		}
		return src[srcPos] ? 'a' : '2';
	}
	if (src[srcPos + 1]) {
		return src[srcPos] ? 'c' : '4';
	}
	return src[srcPos] ? '8' : '0';
}

The corresponding code generated by Jadx:

public static char binaryToHexDigitMsb0_4bits(boolean[] src, int srcPos) {
	...
	return src[srcPos + 3] ? src[srcPos + 2] ? src[srcPos + 1] ? src[srcPos] ? 'f' : '7' : src[srcPos] ? 'b' : '3' : src[srcPos + 1] ? src[srcPos] ? 'd' : '5' : src[srcPos] ? '9' : '1' : src[srcPos + 2] ? src[srcPos + 1] ? src[srcPos] ? 'e' : '6' : src[srcPos] ? 'a' : '2' : src[srcPos + 1] ? src[srcPos] ? 'c' : '4' : src[srcPos] ? '8' : '0';
}

In this case, Jadx generates a single-line expression that represents the same functionality using nested ternary operators. While this condensed form is more compact, it sacrifices readability significantly. The deeply nested ternary operators can be challenging to parse and comprehend, especially when dealing with multiple levels of conditions. In this case, the change from the multiple if structure to the single-line ternary expression has decreased the code's understandability.

I think keep the multiple if structure OR format the nested ternary operators in the following way might be a helpful improvement. Thank you.

	return src[srcPos + 3] 
		? src[srcPos + 2] 
			? src[srcPos + 1] 
				? src[srcPos] ? 'f' : '7' 
				: src[srcPos] ? 'b' : '3' 
			: src[srcPos + 1] 
				? src[srcPos] ? 'd' : '5' 
				: src[srcPos] ? '9' : '1' 
		: src[srcPos + 2] 
			? src[srcPos + 1] 
				? src[srcPos] ? 'e' : '6' 
				: src[srcPos] ? 'a' : '2' 
			: src[srcPos + 1] 
				? src[srcPos] ? 'c' : '4' 
				: src[srcPos] ? '8' : '0';

The corresponding .class file can be found here

JDK version: openjdk 17.0.5
Jadx version: jadx-1.4.7.297-3599b248