tags:

views:

77

answers:

2

I'm learning J2EE and migrating my AP.NET project into Java.

IN Asp.NET I have Helper class which has methods like encode decode, convert, etc...

In ASP.NET I'm initiating public static class Helper as separate cs file and then I'm calling this static class from code behind when ever I need it.

Helper.Parse();
Helper.Convert();

etc....

How can I achieve the same functionality in Servlet/JSP project?

+1  A: 

In Java it is straigt the same you will define a class Helper with only public static methods.

package my.proyect;

public class Helper {

    public static void Parse() {
        // your code 
    }
}

Maybe it is a good deal then to rename to Java name conventions.

PeterMmm
+2  A: 

Just as an addition to what PeterMmm said, it is good practice with such classes which merely exist to group static methods, to enforce non-instantiability of the class. To achieve this, you can provide only a private default (no arguments) constructor, which does nothing but throw an AssertionError. This prevents instantiation both inside and outside the class.

This technique is something I learned from Effective Java, and is available in a sample chapter at:

http://www.informit.com/articles/article.aspx?p=1216151&seqNum=4

That said, I do recommend the whole book if you're moving to Java and want to learn about best practices and how exactly they improve your code.

Sinjo
Thank You very much.
danny.lesnik
Hi Then I have an another question following question:I build this Classpublic class Parser{private Parser(){throw new AssertionError();public static int Multiply(int x, int y){int z = x*y;return z;}}Since I'm using it in servlet id the value of z Thread Safe? Since I have single instance of this class how will it behav under concurenncy?
danny.lesnik
There isn't an instance of the class (which is exactly what we avoided by having the constructor like that). Calls to that particular static method can be considered thread safe. z is a local variable and will be instantiated separately each time the method is called. A case I can think of where you may hit concurrency issues with such a method is if you were passing it a mutable object (rather than a primitive, and an immutable object wouldn't suffer the same problem). That object could then be modified externally at the same time, depending what else you'd passed it to.
Sinjo
If you're looking up to read up on such issues, then Effective Java will give you a background on making things immutable, and other basics. For a richer coverage of concurrency issues you may want to take a look at Java Concurrency in Practice.
Sinjo