Introduction
Suppose you’re running a website with many clients and a commenting system or a similar situation which needs huge String/Array processing on the server side, for example to prevent attackers from XSS (Cross-Site Scripting attacks – See https://en.wikipedia.org/wiki/Cross-site_scripting to find more information ).
What do you do in these situations?
Background
Often for processing String/Array objects, we use length property/method of them in a loop like this:
for(int i=0; i<arrObject.lenght; i++){
}
or:
for(int i=0; i<strObject.lenght(); i++){
}
But this is not a good programming style. Why?
Continue reading!
Using the Code
Length
is a property of the array object while length()
is a method in the String class. If you take a closer look at Java documentation, you’d see that the String class owns an encapsulated private array to store characters which is a very good example of Java’s strong abstraction-encapsulation implementation. - Invoking
length/length()
in the for
loop, you’re calculating the size of your object without storing it. So in each step, you’re doing heavy operations. A better solution is to store your object size before loop and then use it.
int size = arrObject.length;
for(int i=0; i<size i++){
}
or:
int size = strObject.length();
for(int i=0; i<size i++){
}
Really Does It Matter?
Yes! In heavy operations (processing large arrs/strs or a huge number of arrs/strs), you’ll save a lot of resources.
Quick FAQ (Not Related But Useful)
Q-you: How XSS happens?
A: XSS involves an attacker placing malicious code into a site. Websites often feature content created by many different people. For example:
Users create profiles, add comments, contribute articles and so on. These data are called untrusted data because you don’t have complete control over.
Q-you: What can these attacks do?
A: XSS can give the attacker access to information in the DOM, website’s cookies, session tokens and …
Q-you: What if I validate user input on the client side using JavaScript, jQuery or similar frameworks?
A: What if the attacker turns off JavaScript in his/her browser? :)
Q-you: any recommendation?
A: Use a flag to check JavaScript functionality. If it’s on, do your validation on the client machine, then send secure data to the server; else leave the heavy work done on the server.
Conclusion
What makes one programmer professional, another a beginner?
Trust me or not, always, little things make huge differences. Program every bit of your code carefully.
The End --- Feel Free to Develop :)