Saturday, February 25, 2012

Explaining Obfuscation

Obfuscation is the act of making computer programs more efficient by running through less processes. In this article I will explain how to obfuscate your computer programs. My code snippets are written in the Java programming language, but a lot of the functions are language agnostic.

1. Avoid variables
Variables are used to store information in RAM. RAM is very limited in how much it can hold, so making a lot of variables to store information is a bad idea. Below are two examples of avoiding variables.

boolean stopLooping=false;
bad
for(index=0; stopLooping==true; index++)
{
System.out.println(index);
if(index==5)
   stopLooping=true;
}
Your Computer Science professor will tell you that loops are controlled by the state of a boolean, so you might be tempted to do something like the above example. Instead, do something like this:
good
for(int index=0; index<5; index++)
System.out.println(index);
The above example still uses a boolean, but doesn't waste a variable on it. You could also use and if statement with a break, but since for contains functionality to do so it would waste processor resources.

2. Use centralized variables
 Imagine that you are looking at somebody's code and then have 5 variables.
int x, y, a, b, c;
now, you come across this:
bad
x=4;
System.out.println(x);
y=4;
System.out.println(y);
a=5;
System.out,println(a);
b=9 ;
System.out.println(b);
c=2;
System.out.println(c);
You will be deciphering this for a while, so you should use a centralized variable. A centralized variables provides one place to store information, and then it is overwritten after it has been used.
good
int temp;
temp=4;
System.out.println(temp);
System.out.println(temp);
temp=5;
System.out.println(5);
temp=9;
System.out.println(9);
temp=2;
System.out.println(temp);
In the above example, I could have just used System.out.println() with the number I wanted to display, but the point remains. It's better than initializing a bunch of variables to hold the information.
3) if-then-else cleanup
The last thing I will talk about is the reservation of using if-then statements. Let's say that you want to return true if x==4, or else return false.
bad
if(x==4)
 return true;
else
  return false;
This is actually a very common approach, but here is how it should be done:
good
return x==4;
This approach overall shortens up the code and makes it ever so slightly more efficient. You could also use a conditional operator, but this would be a much better way of doing it.

No comments:

Post a Comment