Showing posts with label advantage. Show all posts
Showing posts with label advantage. Show all posts

Tuesday, 17 May 2011

Benefits of a Collections Framework

  • It reduces programming effort: By providing useful data structures and algorithms, a collections framework frees you to concentrate on the important parts of your program, rather than the low-level plumbing required to make it work. By facilitating interoperability among unrelated APIs (as described below), the collections framework frees you from writing oodles of adapter objects or conversion code to connect APIs.
  • It increases program speed and quality: The collections framework does this primarily by providing high-performance, high-quality implementations of useful data structures and algorithms. Also, because the various implementations of each interface are interchangeable, programs can be easily tuned by switching collection implementations. Finally, because you're freed from the drudgery of writing your own data structures, you'll have more time to devote to improving the quality and performance of the rest of the program.
  • It allows interoperability among unrelated APIs: The collections interfaces will become the "lingua franca" by which APIs pass collections back and forth. If my network administration API furnishes a Collection of node names, and your GUI toolkit expects a Collection of column headings, our APIs will interoperate seamlessly even though they were written independently.
  • It reduces the effort to learn and use new APIs: Many APIs naturally take collections on input and output. In the past, each such API had a little "sub-API" devoted to manipulating its collections. There was little consistency among these ad-hoc collections sub-APIs, so you had to learn each one from scratch and it was easy to make mistakes when using them. With the advent of standard collections interfaces, the problem goes away.
  • It reduces effort to design new APIs: This is the flip-side of the previous advantage: designers and implementers don't have to reinvent the wheel each time they create an API that relies on collections. They just use the standard collections interfaces.
  • It fosters software reuse: New data structures that conform to the standard collection interfaces are by nature reusable. The same goes for new algorithms that operate on objects that implement these interfaces.

Monday, 16 May 2011

Advantage of using exceptions to handle errors in java

By using exceptions to manage errors, Java programs have the following advantages over traditional error management techniques:


Advantage 1: Separating Error Handling Code from "Regular" Code

In traditional programming, error detection, reporting, and handling often lead to confusing spaghetti code. For example, suppose that you have a function that reads an entire file into memory. In pseudo-code, your function might look something like this:
readFile {
open the file;
determine its size;
allocate that much memory;
read the file into memory;
close the file;
}
At first glance this function seems simple enough, but it ignores all of these potential errors:


  • What happens if the file can't be opened?

  • What happens if the length of the file can't be determined?

  • What happens if enough memory can't be allocated?

  • What happens if the read fails?

  • What happens if the file can't be closed?
To answer these questions within your read_file function, you'd have to add a lot of code to do error detection, reporting and handling. Your function would end up looking something like this:

errorCodeType readFile {
initialize errorCode = 0;
open the file;
if (theFileIsOpen) {
determine the length of the file;
if (gotTheFileLength) {
allocate that much memory;
if (gotEnoughMemory) {
read the file into memory;
if (readFailed) {
errorCode = -1;
}
} else {
errorCode = -2;
}
} else {
errorCode = -3;
}
close the file;
if (theFileDidntClose && errorCode == 0) {
errorCode = -4;
} else {
errorCode = errorCode and -4;
}
} else {
errorCode = -5;
}
return errorCode;
}
Java provides an elegant solution to the problem of error management: exceptions. Exceptions enable you to write the main flow of your code and deal with the, well, exceptional cases elsewhere. If your read_file function used exceptions instead of traditional error management techniques, it would look something like this:


readFile {
try {
open the file;
determine its size;
allocate that much memory;
read the file into memory;
close the file;
} catch (fileOpenFailed) {
doSomething;
} catch (sizeDeterminationFailed) {
doSomething;
} catch (memoryAllocationFailed) {
doSomething;
} catch (readFailed) {
doSomething;
} catch (fileCloseFailed) {
doSomething;
}
}


Advantage 2: Propagating Errors Up the Call Stack


A second advantage of exceptions is the ability to propagate error reporting up the call stack of methods. Suppose that the readFile method is the fourth method in a series of nested method calls made by your main program: method1 callsmethod2, which calls method3, which finally calls readFile.


method1 {
call method2;
}
method2 {
call method3;
}
method3 {
call readFile;
}
Suppose also that method1 is the only method interested in the errors that occur within readFile. Traditional error notification techniques force method2 and method3 to propagate the error codes returned by readFile up the call stack until the error codes finally reach method1--the only method that is interested in them.

method1 {
errorCodeType error;
error = call method2;
if (error)
doErrorProcessing;
else
proceed;
}
errorCodeType method2 {
errorCodeType error;
error = call method3;
if (error)
return error;
else
proceed;
}
errorCodeType method3 {
errorCodeType error;
error = call readFile;
if (error)
return error;
else
proceed;
}
As you learned earlier, the Java runtime system searches backwards through the call stack to find any methods that are interested in handling a particular exception. A Java method can "duck" any exceptions thrown within it, thereby allowing a method further up the call stack to catch it. Thus only the methods that care about errors have to worry about detecting errors.

method1 {
try {
call method2;
} catch (exception) {
doErrorProcessing;
}
}
method2 throws exception {
call method3;
}

method3 throws exception {
call readFile;
}

However, as you can see from the pseudo-code, ducking an exception does require some effort on the part of the "middleman" methods. Any checked exceptions that can be thrown within a method are part of that method's public programming interface and must be specified in the throws clause of the method. Thus a method informs its callers about the exceptions that it can throw, so that the callers can intelligently and consciously decide what to do about those exceptions.
Note again the difference in the bloat factor and code obfuscation factor of these two error management techniques. The code that uses exceptions is more compact and easier to understand.


Advantage 3: Grouping Error Types and Error Differentiation



Often exceptions fall into categories or groups. For example, you could imagine a group of exceptions, each of which represents a specific type of error that can occur when manipulating an array: the index is out of range for the size of the array, the element being inserted into the array is of the wrong type, or the element being searched for is not in the array. Furthermore, you can imagine that some methods would like to handle all exceptions that fall within a category (all array exceptions), and other methods would like to handle specific exceptions (just the invalid index exceptions, please).
Because all exceptions that are thrown within a Java program are first-class objects, grouping or categorization of exceptions is a natural outcome of the class hierarchy. Java exceptions must be instances of Throwable or any Throwabledescendant. As for other Java classes, you can create subclasses of the Throwable class and subclasses of your subclasses. Each "leaf" class (a class with no subclasses) represents a specific type of exception and each "node" class (a class with one or more subclasses) represents a group of related exceptions.
For example, in the following diagram, ArrayException is a subclass of Exception (a subclass of Throwable) and has three subclasses.

InvalidIndexException, ElementTypeException, and NoSuchElementException are all leaf classes. Each one represents a specific type of error that can occur when manipulating an array. One way a method can exceptions is to catch only those that are instances of a leaf class. For example, an exception handler that handles only invalid index exceptions has a catch statement like this:

catch (InvalidIndexException e) {
. . .
}
ArrayException is a node class and represents any error that can occur when manipulating an array object, including those errors specifically represented by one of its subclasses. A method can catch an exception based on its group or general type by specifying any of the exception's superclasses in the catch statement. For example, to catch all array exceptions regardless of their specific type, an exception handler would specify an ArrayException argument:

catch (ArrayException e) {
. . .
}
This handler would catch all array exceptions including InvalidIndexException, ElementTypeException, andNoSuchElementException. You can find out precisely which type of exception occurred by querying the exception handler parameter e. You could even set up an exception handler that handles any Exception with this handler:

catch (Exception e) {
. . .
}
Exception handlers that are too general, such as the one shown here, can make your code more error prone by catching and handling exceptions that you didn't anticipate and therefore are not correctly handled within the handler. We don't recommend writing general exception handlers as a rule.
As you've seen, you can create groups of exceptions and handle exceptions in a general fashion, or you can use the specific exception type to differentiate exceptions and handle exceptions in an exact fashion.

Sunday, 15 May 2011

Advantage of garbage collection

Garbage collection relieves you from the burden of freeing allocated memory. Knowing when to explicitly free allocated memory can be very tricky. Giving this job to the Java virtual machine has several advantages. To list few :

  1. It can make you more productive. When programming in non-garbage-collected languages you can spend many late hours (or days or weeks) chasing down an elusive memory problem. When programming in Java you can use that time more advantageously by getting ahead of schedule or simply going home to have a life.
  2. A second advantage of garbage collection is that it helps ensure program integrity. Garbage collection is an important part of Java's security strategy. Java programmers are unable to accidentally (or purposely) crash the Java virtual machine by incorrectly freeing memory.