Thursday, October 23, 2008

Java Design Pattern - Creation Pattern

Design Patten is the pattern of problem solving solution where the problem can be found very often for the complex systems.

There are three group of design pattern such as Creation Patterns, Structural Patterns and Behavioral Patterns.

Creation Patterns
Factory Pattern: In order to create the objects that use the same interface with different implementation.

Abstract Factory Pattern: When we need to decide which class to instantiate from a set of different implementation. This patten can decide from a group of different implementation.

Singleton Pattern: Very useful patten when we want to have only one single instance of the class for the whole process.


Builder Pattern:
To build the complex objects by combination of simple objects step by step.


Prototype Pattern: Use the existing object instead of creating new one. This is not very popular since it would affect the performance.

Principle for Java Dev

Simplicity
Build simple classes and simple methods. Determine how much you need to do to meet the expectations of your users.


Clarity
Ensure each class, interface, method, variable and objects has clear purpose. Explain where, when, why and how to use each.


Completeness
Provide the minimum facilities that any reasonable user would expect to find and use. Create complete documentation: document all features and functionalities.


Consistency
Similar entities should look and behave the same, dissimilar entities should look and behave differently. Create and apply standard whenever possible.


Robustness
Provide predictable documented behavior in response to error and exceptions. Do not hide error and do not force client to detect the errors.

Saturday, October 18, 2008

How to modify the contents of file?

When we went to replace the specific information in the file. This method will help.

public void modifyFile(String filePath, String textToFind,String textToReplace) {
PrintWriter outputStream = null;
try {
File tmpFile = new File(filePath);
String newText = readAndReplace(tmpFile, textToFind, textToReplace);
outputStream = new PrintWriter(new FileWriter(tmpFile));
outputStream.print(newText);
outputStream.flush();
} catch (IOException ioe) {
// handle exception here
} catch (Exception ioe) {
// handle exception here
} finally {
if (outputStream != null) {
outputStream.close();
}
}

}

private String readAndReplace(File file, String textToFind,String textToReplace) throws Exception {
StringBuffer sb = new StringBuffer();
BufferedReader inputStream = null;
try {
inputStream = new BufferedReader(new FileReader(file));
String line = "";
while ((line = inputStream.readLine()) != null) {
if (line.contains(textToFind)) {
line = line.replace(textToFind, textToReplace);
}
sb.append(line);
}
} catch (IOException ioe) {
// handle exception
} finally {
try {
inputStream.close();
} catch (IOException e) {
}
inputStream = null;
}

return sb.toString();
}