Tags

Jan 24, 2012

Design patterns for Java Interview


Before you appear for an interview, be ready with 8-10 design patterns with examples from your projects and be confident to answer questions about how you implemented those design patterns. Here I am providing a list of some common design patterns which a candidate can talk about in a Java interview.

1) Flyweight: As discussed above, it’s a part of JDK and hence is used by every Java program.
2) Iterator: All collection classes provide the feature of an iterator to iterate their elements. Moreover, I have also seen custom classes in my projects where the feature of iterator is custom built for those classes.
3) DAO (Data Access Object) : This is also one of the common design pattern seen in many applications which use SQL commands to interact with the datasource/database. Usually a DAO class has methods which invoke the SQL queries for CRUD operations on the database tables thus avoiding the need to write and maintain SQL queries in multiple classes for the same database tables.

4) DTO (Data Transfer Object) : This design pattern represents the data which is actually stored in the database tables in terms of Java classes and is accepted as argument by various methods of the DAO classes. This design pattern usually translates to POJO classes corresponding to database tables and their columns.
5) Factory: If you have used DAO then it is very likely that you have also seen factory design pattern being used as a factory class is written for generating the DAO’s.
6) Abstract Factory: This design pattern represents a factory of factories. When you have many closely related factory classes, you will write an interface which all those factories implement and thus can be generically referenced. You will write a class which will have methods to return the appropriate factory depending upon the need.
7) MVC: This is also one of the famous design patterns and should not be missed in Java interview.
8) Front Controller: This design pattern is closely associated with MVC design pattern and is used to write the single point of contact for any request that comes from the users. The controller then dispatches the request to appropriate handler depending upon the arguments being passed along with the request.
9) Singleton: Though Singleton design pattern looks to be easy to understand and get away with any Java interview but one can be grilled like anything on this design pattern. There is so much to ask on Singleton that a candidate can be judged only by asking questions on Singleton. This is because the interviewer can associate Inheritance, Reflection, Serialization, Collections, Polymorphism, Cloning and other Java concepts with Singleton.
Still if you were to choose only five design patterns for an interview due to time constraints then I would advise the following list:
1) Singleton
2) DAO (Data Access Object)
3) DTO (Data Transfer Object)
4) MVC (Model View Controller)
5) Factory


How HashSet works in Java


HashSet in Java is implemented to use hash based storage of elements and also has the property of having no duplicate elements at the same time.
When we dig dipper into the implementation of HashSet then we see that a HashMap instance member variable is used which not only provides the capability of hash based storage but also ensures zero duplicates contract.
Since HashMap has the property of having unique keys, HashSet makes use of this property of HashMap and stores the members of HashSet as the keys of internal HashMap instance.

If we open the source of HashSet then we see the following two member variables:-
   public boolean remove(Object o) {
            return map.remove(o)==PRESENT;
    }
Here PRESENT is a dummy object which is used as the value object for every key,value pair inserted into the internal HashMap instance. There is no PRESENT dummy object for every key,value pair and this object is declared as static in the HashSet class.
It is interesting to see how HashSet class implements clone method which is reproduced here for reference:

public Object clone() {
            try {
                HashSet newSet = (HashSet) super.clone();
                newSet.map = (HashMap) map.clone();
                return newSet;
            } catch (CloneNotSupportedException e) {
                throw new InternalError();
            }
    }
Here we see that first the clone of super class which is AbstractSet is invoked and then the internal HashMap reference of HashSet class is cloned.
The HashSet class also implements Serializable interface and takes proper care to customize the serialization operation by
1) providing a custom serial version UID
2) provide readObject and writeObject methods

Session handling tips for web application


1) Specify default session timeout interval in web.xml

2) Execute request.getSession.invalidate() when user clicks logout button

3) Start a Javascript timer so that user can be alerted about session being going to expire and he should save his work before session actually expires

4) Capture browser window/tab closing javascript event so that session can be invalidated before user closes the application window/tab and opens a new browser window/tab to access the web application.

5) Maintain a list of users who are currently logged in either by storing a list in database and updating it as and when users log in or logout OR Maintain a Hashmap in application context and update it with user info of currently logged in users. The DB and HashMap can be updated by using Session Binding Listener API provided by JEE.

6) Use proper session handling mechanism by always encoding URL so that jsessionid can be used when cookies are disabled by a browser

7) Whenever user clicks a link, always check if his session is valid by using isValid function and if the session is invalid or expired, forward him to login/index page rather than processing his request.

8) If the session has expired then immediately forward the user to login page instead of showing him current page
9) If you are using AJAX calls then whole page refresh may not happen in your application but make sure that session is valid if Ajax calls are being sent.

10) Choose a proper default session timeout depending upon the kind of application. A banking application will have session timeout of the order of 2 minutes and internal portal should have session timeout of the order of 15 minutes

Jan 23, 2012

Advantage of Hibernate over JDBC



Advantage are
1) Hibernate is data base independent, same code will work for all data bases like ORACLE,MySQL ,SQLServer etc.
In case of JDBC query must be data base specific.

2) As Hibernate is set of Objects , you don't need to learn SQL language.
You can treat TABLE as a Object .
In case of JDBC you need to learn SQL.

3) Don't need Query tuning in case of Hibernate. If you use Criteria Quires in Hibernate then hibernate automatically tuned your query and return best result with performance.
In case of JDBC you need to tune your queries.

4) You will get benefit of Cache. Hibernate support two level of cache. First level and 2nd level. So you can store your data into Cache for better performance.
In case of JDBC you need to implement your java cache .

Jan 22, 2012

Good Practices for Rich Web Applications


Use jQuery
jQuery is the best thing that has happened to Javascript. The library is elegant, powerful and has exactly the right level of abstraction for working with the DOM.
Learn it and use it. Good resources are: the jQuery API,

Learn Javascript
Javascript is the programming language of the web. Learn it! Javascript is different from most other programming languages. 
If you want to learn Javascript you should get the following books, The Little Schemer, The Seasoned Schemer, Javascript, the Good Parts, and possibly High Performance Javascript
 
Learn CSS 


Many programmers think that CSS is the language of designers and not programmers. This is not the case at all. If you are lucky enough to have a designer on your team (most people don't), CSS is the language with which you communicate. It is the interface between designers and programmers and as a programmer you should know it better than the designers.
It will also be up to you to keep the HTML clean, and a good way to do this is to use semantic HTML, combined with CSS. You have no idea what the designers can come up with.

Decide how "Rich" your application should be


How rich should your application be? The scale varies from no Javascript to only Javascript, but you will probably want to land somewhere in between. Here are a few suggestions.
  • No Javascript, everything is server generated.
  • Slightly enhanced pages, simple validations, but no Ajax.
  • Ajax enhanced pages, but every page still reloads frequently.
  • Single page per area, entire area is handled by Javascript.
  • Only Javascript, Ajax interaction with the server
  • Only Javascript, no interaction with the server

    Html
    HTML is code! Divide your pages into partials by responsibilities. It allows you to keep your pages DRY and readable. The Single Responsibility Principle applies to HTML too.
    Make sure you keep the Javascript with the code that it manipulates. If you, for example, have a calendar partial that uses jQuery DatePicker, you have to make sure that the partial includes all the necessary Javascript to configure the calendar. Don't keep Javascript code in the page away from the partial. Things that change together should be together.
    Use clone()
    Separating the HTML and the Javascript goes both ways. Don't generate HTML code in Javascript. It doesn't matter that it is super simple to do it using jQuery.html(). Keep them separate, use jQuery.clone() instead.

    The point of this is, again, to keep the HTML separate from the Javascript.
    Conclusion :
              We have to realize that we are responsible for the entire application, not just the business logic, but  the HTML and CSS too

Jquery changes from 1.4.2 to 1.6

jQuery is a powerful library and it is possible to get by without
using any of the new features. 



delegate()
Most people know about live() and how it can be used to attach
listeners to elements that don’t yet exist in the DOM.
live() has
a younger brother that was born in 1.4.2 and he is called
delegate().
delegate() is more powerful. It gives you more precision in
where to attach the listener.
$('.main-content').find('section').delegate 'p', 'click', ->
  $(this).addClass 'highlight'
As you can see above, delegate(), unlike live(), can be chained like
normal jQuery calls.
jQuery.now(), jQuery.type() and jQuery.parseXML()
Nothing special here, just some utilities that are good to know about.
$.now() is (new Date()).getTime()

$.type('hello') is 'string'

xml = """
RSS Title
"""
xmlDoc = $.parseXML xml
($(xmlDoc).find 'title').text() is 'RSS Title'
All these utilities are interesting, but the truly good thing that came
out of jQuery-1.5+ is
Deferred().
Deferred()
With the release of jQuery 1.5 the internal implementation of $.ajax
was changed to use
Deferred(), and, even better, the implementation
was deemed so useful, that it became part of the public API.
Here is how you can use it via the $.ajax method.
Declare a function hex that calls the /hex url on the server, which
will return a hex value between 00 and FF.
  hex = ->
    $.ajax { url: '/hex' }
Call the function multiple times, and you get a new Deferred back for
each call. Notice the lack of handlers for the calls.
  red = hex()
  green = hex()
  blue = hex()
Attach handlers to each of the Deferreds to do something useful with
the returned value. Notice the use of
done instead of success.
success is deprecated and will be removed in 1.8.
  red.done (hh)->
    $("#r").css 'background-color', "##{hh}0000"
  green.done (hh)->
    $("#g").css 'background-color', "#00#{hh}00"
  blue.done (hh)->
    $("#b").css 'background-color', "#0000#{hh}"
I am not limited to adding one handler, I can attach as many as I like.
Here I attach another one for logging the success of the
red-call.
  red.done (hh) ->
    console.log(hh)
If this was all there was to it, I would be happy, but it is not by
using the
$.when method I get a new Deferred object that orchestrates
multiple
Deferreds in a very simple way. Let me create a color-Deferred
that waits for the others to return and then calls a new callback when
they are all done.
  color = $.when(red, green, blue)

  color.done (r, g, b) ->
    $("#color").css 'background-color', "##{r[0]}#{g[0]}#{b[0]}"
The results from the requests are given in the same order as the
Deferred objects are passed in. The results are given as an array with
three arguments
[ data, ‘success’ , deferred ].
Apart from the examples I have shown, there are methods
working with
Deferred. Methods for creating, jQuery.Deferred(),
resolving,
resolve(), resolveWith(), and rejecting, reject(),
rejectWith().
To attach handlers to the events, you can use done() for resolve,
fail for reject, always() for both resolve and reject. You can also
use
then(doneCallback, failCallback) to attach both a done and a
fail handler with one call.
Deferreds are really cool, check them out here