How to Write Obfuscated Java Code
To some people obfuscating programming code, including Java, means:
- Job security. If no one can understand their code, they are irreplaceable.
- Smartness. They are so smart, that they can write very complex code.
Of course, obfuscating code is a terrible idea and usually means exactly the opposite to the above bullets, i.e. that the person who wrote it is easily replaceable and far from smart. That's why even though it's not impossible, it's very likely to see obfuscated code nowadays, especially considering the fact that code is peer reviewed and has to be understood by at least one more person.
For the fun of it, here follows an example of some obfuscated code:
class A{public static void main(String[]a){if(System.console()!=null){System.out.println("Hello World");System.exit(0);}}static{System.loadLibrary(String.valueOf(new char[]{'l','i','b'}));}}
Here are some practices that could make obfuscated Java code particularly difficult to read and maintain:
- Using extremely short or cryptic variable names: Instead of using meaningful names, variables are given short names, often consisting of a single letter or digit. This can make it difficult to understand what the variable represents.
- Writing overly complex expressions: Complex expressions can make it difficult to understand what the code is doing, especially if they involve a lot of nested logic or unusual operators.
- Removing whitespace and newlines: Removing whitespace and newlines can make code difficult to read and understand, especially if it is already obfuscated.
- Overusing ternary operators: Ternary operators can be useful for shortening code, but using them excessively can make code difficult to read and understand.
- Using unconventional formatting: Using unconventional formatting, such as putting multiple statements on a single line or using unusual indentation, can make the code difficult to read and understand.
- Reusing variable names for different purposes: This can make it difficult to understand what a variable represents at any given point in the code.
Once you know what's bad, it's easy to try to avoid it. The opposite of obfuscated code is clean code. Continue reading on how to write clean, unobfuscated code.