Showing posts with label difference. Show all posts
Showing posts with label difference. Show all posts

Tuesday, September 27, 2011

Difference between Proxy, Decorator, Adaptor, and Bridge Patterns ?

Proxy, Decorator, Adapter, and Bridge are all variations on "wrapping" a class. But their uses are different.
  • Proxy could be used when you want to lazy-instantiate an object, or hide the fact that you're calling a remote service, or control access to the object.
    See proxy pattern with details.
  • Decorator is also called "Smart Proxy." This is used when you want to add functionality to an object, but not by extending that object's type. This allows you to do so at runtime.
  • Adapter / Wrapper is used when you have an abstract interface, and you want to map that interface to another object which has similar functional role, but a different interface.
    In particular Decorator looks very close to Adapter but still there is basic difference:
      Adapter / Wrapper Decorator
    Composes "origin" class True True
    Modifies original interface True False
    Modifies behavior of interface
    False True
    Proxies method calls True True
     
    See Adapter pattern and Decorator Pattern with examples.
  • Bridge is very similar to Adapter, but we call it Bridge when you define both the abstract interface and the underlying implementation. I.e. you're not adapting to some legacy or third-party code, you're the designer of all the code but you need to be able to swap out different implementations.
    See bridge pattern with example.
  • Facade is a higher-level (read: simpler) interface to a subsystem of one or more classes. Think of Facade as a sort of container for other objects, as opposed to simply a wrapper. So you don't have to worry about so many things, just call the facade to do all the stuff.
    See Facade pattern with example.

Sunday, June 19, 2011

Interview Question: Compare two web services type SOAP and RESTful (SOAP Vs RESTful)

Here are the differences between SOAP and Restful web services :





Criteria SOAP RESTful Comments
Orientation Wraps business logic Accesses resources/data
Developer View Object oriented Resource Oriented
Language Independence Yes Yes
Platform Independence Yes Yes
Simplicity No Yes
Standards Based Yes No SOAP web services are based on SOAP and WS-* specifications
Security SSL, WS-Security SSL WS-Security provides end-to-end security covering message integrity and authentication
Transactions WS-AtomicTransaction No
Reliability WS-ReliableMessaging Application specific
Performance Good Better Caching and lower message payload makes RESTful web services performance efficient and scalable
Caching No GET operations can be cached
Transport protocol support HTTP, SMTP, JMS HTTP Multiple transport protocol support makes SOAP Web Services flexible
Message Size Heavy, has SOAP and WS-* specific markup Lightweight, no extra xml markup
Message Communication protocol XML XML, JSON, other valid MIME type This flexibility of REST makes its extremely useful in providing consumer need specific message payloads
Message Encoding Yes No SOAP Web Services support text and binary encoding, RESTful encoding is limited to text
Service Description WSDL No formal contract definition In REST, no formal way to describe a service interface means more dependence on written documentation
Human intelligible Payload No Yes
Developer Tooling Yes Minimal or none Complexity of SOAP Web Services dictates the need for using frameworks to facilitate rapid application development. REST on the other hand due to its simplicity can be developed without any framework


Now we come to most important stage of deciding which type to select. There is no one answer for selecting either SOAP based or RESTful Web Services. Neither is the right choice for every situation. The choice is dependant upon specific needs and which solution addresses them best. An architect should ask the following questions and the responses should assist him/her in making an informed decision:
  • Does the service expose data or business logic? (REST can be a good choice for exposing data, SOAP/WS-* might be a better choice for logic)
  • Does the service need the capabilities of WS-*, or is a simpler RESTful approach sufficient?
  • What’s best for the developers who will build clients for the service?
Areas where RESTful WebServices are a great choice:
  • Limited bandwidth and resources: Remember the return structure is really in any format (developer defined). Plus, any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE verbs. Again, remember that REST can also use the XMLHttpRequest object that most modern browsers support today, which adds an extra bonus of AJAX.
  • Totally stateless operations: If an operation needs to be continued, then REST is not the best approach and SOAP may fit it better. However, if you need stateless CRUD (Create, Read, Update, and Delete) operations, then REST is suitable.
  • Caching situations: If the information can be cached because of the totally stateless operation of the REST approach, this is perfect.
Areas where SOAP based WebServices is a great solution:
  • Asynchronous processing and invocation: If application needs a guaranteed level of reliability and security then SOAP 1.2 offers additional standards to ensure this type of operation. Things like WSRM – WS-Reliable Messaging etc.
  • Formal contracts: If both sides (provider and consumer) have to agree on the exchange format then SOAP 1.2 gives the rigid specifications for this type of interaction.
  • Stateful operations: If the application needs contextual information and conversational state management then SOAP 1.2 has the additional specification in the WS* structure to support those things (Security, Transactions, Coordination, etc). Comparatively, the REST approach would make the developers build this custom plumbing.
I have used a lot of information from resources generously shared by fellow bloggers. It would inconsiderate in case I do not mention them. The resources are:
  1. REST and SOAP: When to use each (or both)?
  2. SOAP vs REST: Complements or Competitors
  3. Introduction to Web APIs: REST vs SOAP



Wednesday, June 15, 2011

Hibernate vs JDBC

Abstraction
One of the objectives of Hibernate and other ORM tools is to abstract the persistence of an object. Hibernate works hard to provide as much flexibility as JDBC offers while at the same time removing much of the maintenance headaches that are associated with managing SQL statements embedded into an application.

Flexible Configuration with ORM
There are some additional considerations and complexity that must be tackled, but this quickly becomes a non-issue as a developer becomes adept with the framework. The complexities that were ones a problem with JDBC (connection management, connection pooling, caching, lazy-loading associations, etc.) become configuration driven and no longer an issue for a developer to contend with.
With HQL (Hibernate Query Language) the developer can achieve nearly all of the same semantics that are available in SQL. All the power of the relational database is still present and can even be reinforced in the application through column definition, foreign keys, etc. on the object meta-data (which is amazingly simple with annotations).
If you additionally leverage Spring in conjunction with Hibernate (or JPA) you will also reap the benefit of springs transaction management, connection management, etc. and still have access to the underlying JDBC connection if you find a reason to need it.

Transparent Persistence
The automatic mapping of Java objects with database tables and vice versa is called Transparent Persistence. Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS. With JDBC this conversion is to be taken care of by the developer manually with lines of code.

Thursday, June 9, 2011

StringBuilder vs StringBuffer, Choose StringBuilder if possible

StringBuilder is an unsynchronized version of StringBuffer. That is, its instances are not safe for use by multiple threads. The upside is that it’ll be faster than StringBuffer in most implementations as well. Think of Vector vs. ArrayList.
Now let’s think about our most common use of StringBuffer. What is it? I bet it’s inside a method, as a local variable, to concatenate a bunch of strings, just like this:
public String buildHQLString() {
    StringBuffer sb = new StringBuffer();
    sb.append("something");
    // append a lot more things here
    return sb.toString();
}

It is safe to replace StringBuffer with StringBuilder in this very common case, because every thread has its own stack, in which local variables reside. So, next time you’re typing “StringBuffer sb = “, it’s a good time to reflect whether “StringBuilder sb = ” is more appropriate.

(In fact, I can’t think of a good reason to use StringBuffer now. Have any of you ever come across a case where you just absolutely have to use StringBuffer instead of StringBuilder? If anyone can enlighten me with a good, legit, uncontrived usage of StringBuffer in the comments, I’ll be grateful.)

But the default StringBuilder constructor, which has the initial capacity hardcoded to 16! So it results in a lot of extendCapacity() calls. So provide the reasonable value to StringBuilder(int capacity), instead of using StringBuilder no-arg constructor–BUT spend too much time on this and you’re doing the root of all evil, premature optimization.

Tuesday, May 31, 2011

Difference between synchronized and volatile



The main differences between synchronized and volatile are:
  • a primitive variable may be declared volatile whereas synchronized cannot be applied on the primitive types, but on some object or method or class.
  • Lock - Volatile deals with visibility, so if one thread modifies some variable, it will be known to other thread, so unlike a synchronized block we will never hold on to any lock; This is the big difference as synchronized offers mutual exclusion while volatile don't.
  • Attempting to synchronize on a null object will throw a NullPointerException, while  this is fine with volatile.
  • As synchronized offers mutual exclusion, it offers atomicity as well. But volatile doesn't mean atomic. (click on the link to see why)
Thanks

Sunday, May 29, 2011

Difference between Factory Pattern or Abstract Factory Pattern and Builder Pattern

Abstract factory may also be used to construct a complex object, then what is the difference with builder pattern? In builder pattern emphasis is on ‘step by step’. Builder pattern will have many number of small steps. Those every steps will have small units of logic enclosed in it. There will also be a sequence involved. It will start from step 1 and will go on upto step n and the final step is returning the object. In these steps, every step will add some value in construction of the object. That is you can imagine that the object grows stage by stage. Builder will return the object in last step. But in abstract factory how complex the built object might be, it will not have step by step object construction.

Both are creational pattern but differ:
Factory Pattern Builder Pattern
The factor pattern defers the choice of what concrete type of object to
make until run time.
E.g. going to a restaurant to order the special of  the day.  The waiter is the interface to the factory that takes the
abstractor generic message "Get me the special of the day!" and returns
the concrete product (i.e "Chilli Paneer" or some other dish.)
The builder pattern encapsulates the logic of how to put together a
complex object so that the client just requests a configuration and the
builder directs the logic of building it.   E.g The main contractor
(builder) in building a house knows, given a floor plan, knows how to
execute the sequence of operations (i,e. by delegating to subcontractors)
needed to build the complex object.  If that logic was not encapsulated in
a builder, then the buyers would have to organize the subcontracting
themselves 
The factory is concerned with what is made. The builder with how it is
made. So it focuses on the steps of constructing the complex object.
In case of Factory or Abstract Factory, the product gets returned immediately Builder returns the product as
the final step.

Thursday, May 26, 2011

Process vs threads

The distinction between processes and threads is important.

  • Process: A process runs independently and isolated of other processes. It cannot directly access shared data in other processes. The resources of the process are allocated to it via the operating system, e.g. memory and CPU time.
  • Threads: threads are so called lightweight processes which have their own call stack but an access shared data. Every thread has its own memory cache. If a thread reads shared data it stores this data in its own memory cache. A thread can re-read the shared data, when this happens in Java will be explained in Java memory model part of this article.
Within a Java application you work with several threads to archive parallel processing or asynchronously behavior.

Wednesday, May 25, 2011

Static class loading vs Dynamic class loading

There are two ways in which classes can be loaded -- explicitly or dynamic or implicitly or static-- with subtle variations between the two.
Static Class Loading
Classes are statically loaded with Java’s 'new' operator.
class MyClass 
{     
    public static void main(String args[]) 
   { 
        Car c = new Car(); 
   }
}


A NoClassDefFoundException is thrown if a class is referenced with Java’s 'new' operator (i.e. static loading) but the runtime system cannot find the referenced class.

Dynamic class loading
Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time.
we can load classes dynamically by...
Class.forName (String className); //static method which returns a Class

The above static method returns the class object associated with the class name. The string className can be supplied dynamically at run time. Unlike the static loading, the dynamic loading will decide whether to load the class Car or the class Jeep at runtime based on a properties file and/or other runtime conditions. Once the class is dynamically loaded the following method returns an instance of the loaded class. It’s just like creating a class object with no arguments.
  class.newInstance (); //A non-static method, which creates an instance of 
                        //a class (i.e. creates an object).
  Jeep myJeep = null ;//myClassName should be read from a properties file or 
                     //Constants interface.
                     //stay away from hard coding values in your program. 
  String myClassName = "au.com.Jeep" ;
  Class vehicleClass = Class.forName(myClassName) ;
  myJeep = (Jeep) vehicleClass.newInstance();
  myJeep.setFuelCapacity(50);

Summary
Explicit class loading occurs when a class is loaded using one of the following method calls:
  • cl.loadClass() (where cl is an instance of java.lang.ClassLoader)
  • Class.forName() (the starting class loader is the defining class loader of the current class)
When one of these methods is invoked, the class whose name is specified as an argument is loaded by the class loader. If the class is already loaded, then a reference is simply returned; otherwise, the loader goes through the delegation model to load the class.

Implicit class loading occurs when a class is loaded as result of a reference, instantiation, or inheritance (not via an explicit method call). In each of these cases, the loading is initiated under the covers and the JVM resolves the necessary references and loads the class. As with explicit class loading, if the class is already loaded, then a reference is simply returned; otherwise, the loader goes through the delegation model to load the class.

Sunday, May 22, 2011

&& vs & operator

Don't confuse &&, which is the short-circuit logical and, with &, which is the uncommon bitwise and. Altho the bitwise and can also be used with boolean operands, this is extremely rare and is almost always a programming error.

Tuesday, May 17, 2011

throw vs throws in java

throws is used to specify that an exception/s can be thrown. Specifying is more pertinent to checked exceptions.

throw is simply the statement to manually/programically throw the exception or any object of throwable type.

Using throws

a method, and then tell that this method throws following exception…and then write da .. da .. da. Eg.

public void myMethod() throws MalformedURLException,MyCustomException1
{
//do something in method
}



Using throw


throw just throws exception. Eg.

if(something)
throw someObjectOfThrowableType

Monday, May 16, 2011

Difference between fields and local variables

There are few difference between fields and local variables. Fields are defined in the class, whereas local variables are local to the methods. The big difference comes in case of initialization.
You must always explicitly initialize local variables in a method. But if you don't initialize a field in a class, it is automatically initialized to a default (0, false, or null).

Differences between methods and constructors.

  • There is no return type given in a constructor signature (header). The value is this object itself so there is no need to indicate a return value.
  • There is no return statement in the body of the constructor.
  • The first line of a constructor must either be a call on another constructor in the same class (using this), or a call on the superclass constructor (using super). If the first line is neither of these, the compiler automatically inserts a call to the parameterless super class constructor.
These differences in syntax between a constructor and method are sometimes hard to see when looking at the source. It would have been better to have had a keyword to clearly mark constructors as some languages do.

Difference between a web server and an application server

A Web server serves pages for viewing in web browser, application server provides exposes business logic for client applications through various protocols .Web server exclusively handles http requests.
- A Web Server (otherwise known as an HTTP Server)

An Application Server is any server that supplies additional functionality related to enterprise computing -- for instance, load balancing, database access classes, transaction processing, messaging, and so on.

A Web Server understands and supports only HTTP protocol whereas an Application Server supports HTTP, TCP/IP and many more protocols. Also many more features such as Caches, Clusters, and Load Balancing are there in Application Servers which are not available in Web Servers. We can also Configure Application Servers to work as Web Server.


In short, Application Server is a super set of which Web Server is a sub set.

Sunday, May 15, 2011

equals() vs ==

Object class has a default method which looks like this :

public boolean equals(Object other)
{
return this==other;
}


== tests identity of the object, i.e. whether the 2 references are pointing the same object or not.

The default implementation of equals() is based on the == operator: Two objects are equal if and only if they are the same object. Naturally, most classes should define their own alternative implementation of this important method.

Difference between ArrayList and LinkedList

java.util.ArrayList and java.util.LinkedList are two Collections classes used for storing lists of object references Here are some differences:

ArrayList LinkedList
ArrayList uses primitive object array for storing objects. LinkedList is made up of a chain of nodes. Each node stores an element and the pointer to the next node. A singly linked list only has pointers to next. A doubly linked list has a pointer to the next and the previous element. This makes walking the list backward easier.
ArrayList implements the RandomAccess interface. LinkedList does not implement RandomAccess interface.
Because of above point its fast to access any element randomly in arraylist. The commonly used ArrayList implementation uses primitive Object array for internal storage. Therefore an ArrayList is much faster than a LinkedList for random access, that is, when accessing arbitrary list elements using the get method. Note that the get method is implemented for LinkedLists, but it requires a sequential scan from the front or back of the list. This scan is very slow. For a LinkedList, there's no fast way to access the Nth element of the list.
Adding and deleting at the start and middle of the ArrayList is slow, because all the later elements have to be copied forward or backward. (Using System.arrayCopy()) Whereas Linked lists are faster for inserts and deletes anywhere in the list, since all you do is update a few next and previous pointers of a node.
Uses memory equivalent to element in it.

Each element of a linked list (especially a doubly linked list) uses a bit more memory than its equivalent in array list, due to the need for next and previous pointers.

ArrayList may also have a performance issue when the internal array fills up. The arrayList has to create a new array and copy all the elements there. The ArrayList has a growth algorithm of (n*3)/2+1, meaning that each time the buffer is too small it will create a new one of size (n*3)/2+1 where n is the number of elements of the current buffer. Hence if we can guess the number of elements that we are going to have, then it makes sense to create a arraylist with that capacity during object creation (using construtor new ArrayList(capacity)). LinkedLists should not have such capacity issues.

Collections.sort() vs Arrays.sort()

Difference between the Collections.sort() and Arrays.sort()?

Difference between the two is input. Collections.sort() has a input as List so it does a translation of List to array and vice versa which is an additional step while sorting. So this should be used when you are trying to sort a list. Arrays.sort is for arrays so the sorting is done directly on the array. So clearly it should be used when you have a array available with you and you want to sort it.

Algorithm – Algorithm seems to be same.

Difference between Enumeration and Iterator interface or Enumeration vs Iterator

Enumeration and Iterator are the interface available in java.util package. The functionality of Enumeration interface is duplicated by the Iterator interface. New implementations should consider using Iterator in preference to Enumeration. Iterators differ from enumerations in following ways:

Enumeration Iterator
Enumeration contains 2 methods namely hasMoreElements() & nextElement(). Iterator contains three methods namely hasNext(), next(),remove().
No such operation supported. It acts as read-only interface, as delete not supported. Iterator adds an optional remove operation, and has shorter method names. Using remove() we can delete the objects.
Enumeration interface is used by legacy classes. Vector.elements() & Hashtable.elements() method returns Enumeration. Iterator is returned by all Java Collections Framework classes. java.util.Collection.iterator() method returns an instance of Iterator.

Difference between Vector and ArrayList? What is the Vector class OR ArrayList vs Vector

Vector & ArrayList both classes are implemented using dynamically resizable arrays, providing fast random access and fast traversal. ArrayList and Vector class both implement the List interface. Both the classes are member of Java collection framework, therefore from an API perspective, these two classes are very similar. However, there are still some major differences between the two. Below are some key differences :

Vector ArrayList

Vector is a legacy class which has been retrofitted to implement the List interface since Java 2 platform v1.2

Introduced in java v1.4.2. So its newer API.
Vector is synchronized. ArrayList is not.
Note: Even though Vector class is synchronized, still when you want programs to run in multithreading environment using ArrayList with Collections.synchronizedList() is recommended over Vector.
Vector has default size. ArrayList has no default size.
The Enumerations returned by Vector's elements method are not fail-fast. Whereas ArrayList does not have any method returning Enumerations, like other new collections.

Saturday, May 14, 2011

Difference between iterator and index access

Index based access allow access of the element directly on the basis of index. The cursor of the datastructure can directly goto the ‘n’ location and get the element. It doesnot traverse through n-1 elements. So this is like random access, as it is in case of arrays.

In Iterator based access, the cursor has to traverse through each element to get the desired element.So to reach the ‘n’th element it need to traverse through n-1 elements. So this is the case of linked list, where we have to go through each element to insert something in list.

Insertion,updation or deletion will be faster for iterator based access if the operations are performed on elements present in between the datastructure.

Insertion,updation or deletion will be faster for index based access if the operations are performed on elements present at last of the datastructure.

Traversal or search in index based datastructure is faster.

ArrayList is index access and LinkedList is iterator access.

Difference between static and init block

The static block is only loaded when the class object is created by the JVM for the 1st time whereas init {} block is loaded every time class object is created. Also first the static block is loaded then the init block.

public class LoadingBlocks {

static{
System.out.println("Inside static");
}

{
System.out.println("Inside init");
}
public static void main(String args[]){
new LoadingBlocks();
new LoadingBlocks();
new LoadingBlocks();
}
}



Output:

Inside static
Inside init
Inside init
Inside init


So static block is initialized only once, that is it is per class basis, whereas init block is per object basis.

Chitika