Search code examples
javadata-access-layerbusiness-logic-layer

Static layers in a java web application


I am building a small website for fun/learning using a fairly standard Web/Service/Data Access layered design.

To save me from constantly having to create instances of my service layer/data access layer classes, I have made the methods in them all static. I shouldn't get concurrency issues as they use local variables etc and do not share any resources (things are simple enough for this at the moment).

As far as I can see the only trade-off for this is that I am not really following a true OO approach, but then again it keeps the code much cleaner.

Is there any reason this would not be a viable approach? What sort of problems might arise later on? Would it be better to have a "factory" class that can return me instances of the service and data layer classes as needed?


Solution

  • Disadvantages:

    • You will be unable to write unit tests as you will be unable to write mock data access/business logic objects to test against.
    • You will have concurrency problems as different threads try to access the static code at the same time - or if you use synchronized static methods you will end up with threads queuing up to use the static methods.
    • You will not be able to use instance variables, which will become a restriction as the code becomes more complex.
    • It will be more difficult to replace elements of the business or data access layers if you need to.
    • If you intend to write your application in this manner you would be better off using a language designed to work in this way, such as PHP.

    You would be better off going for non-static business/data access layer classes by either:

    • Using the singleton pattern (creating a single instance of each class and sharing them among threads)...
    • Or creating instances of the classes in each thread as and when they are needed.

    Keep in mind that each user/session connected to your application will be running in it's own thread - so your web application is inherently multi-threaded.