Monday, August 20, 2012

Understanding Encapsulation



Hi

Today, we will be looking at the most important and favorite topic of OOP i.e. encapsulation.

To explain the concept of encapsulation We will be using the java examples this concept remains same for any Object Oriented programming language.

First of all let’s look at the meaning of encapsulation. Encapsulation means to enclose something or we can say to cover something protectively.

When we read the above statement few questions arises

1.  Why should we protect /hide something?
2.  What we need to protect?
3.  What happens if we don’t protect?

With below example let us try to answer these questions

The state of an Object depends on the data stored in variable, which means to say in order to save the state of any object we need to protect the our variables’.We need to protect all those variable which can change the state of the object. The concept of protecting or ensuring the safety of our variable is called encapsulation


package com.alwaysJava.encapsulation;

public class UnderstandingEncapsulation
{
        public int numberOfStudentsEnroled;
        public final int maxNumberOfStudents=100;
       
        public int getNumberOfStudents()
        {
                return numberOfStudentsEnroled;
        }
}


package com.alwaysJava.encapsulation;

public class DriverClass
{

        public static void main(String[] args)
        {
                UnderstandingEncapsulation uE=new UnderstandingEncapsulation();
                uE.numberOfStudentsEnroled=10;
               
                System.out.println(uE.getNumberOfStudents());

        }
}

By running the above output we will see the output to be 10.

We may feel at first look that the code is working really fine why we need to encapsulate?

If we observe carefully we will know that we are giving too much power to the DriverClass, which allows user to even set negative values to numberOfStudentsEnroled as -100, or set 65535 as the number of students enrolled against maximum capacity of 100.

So how can we protect out class from being exploited by user, in order to do this we need to validate the input given by the user, this can be achieved by providing setter and getter methods and also by setting access specifier as private  
package com.alwaysJava.encapsulation;

public class UnderstandingEncapsulation
{
        private int numberOfStudentsEnroled;
        public final int maxNumberOfStudents=100;
       
        public int getNumberOfStudents()
        {
                return numberOfStudentsEnroled;
        }
       
        public void setNumberOfStudents(int userInput)
        {
                if(userInput>maxNumberOfStudents)
                        throw new IllegalArgumentException();
                else
                        numberOfStudentsEnroled=userInput;
        }
}

By changing the UnderstandingEncapsulation class variables to private we can force the user to set a correct value, if the user tries to set an invalid value we can throw a illegalArgumentException which is an uncheck exception, by doing this we protect our code from taking illegal values and hence protecting functionality of the code.

This concept of protecting the code from user is called encapsulation.

Hence by using the right coding practices and concepts we give the programmers more power to change the code at a later stage when required without making any changes to the code or implementation of the class.

It is industry best practice to have a validate method in every class, whenever there is a possibility of change in object we need to invoke this method to check the value set to instances are correct by doing so it helps to identify bugs at a very early stage and the debugging will be comparatively easier.

Wednesday, April 4, 2012

Create an XMl file using java

Scenario: to create an XML file using java
JAR files required: DOM jar,JXL jar.


Java Code: 



import java.io.File;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;


import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;




public class GenerateXmlFile {

public static void main(String argv[]) throws ParserConfigurationException, TransformerException 
{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("Organization");
doc.appendChild(rootElement);

Attr attr = doc.createAttribute("Name");
attr.setValue("Saankya labs");
rootElement.setAttributeNode(attr);

Element Employee = doc.createElement("Employee");
rootElement.appendChild(Employee);

attr = doc.createAttribute("FirstName");
attr.setValue("XYZ");
Employee.setAttributeNode(attr);

attr = doc.createAttribute("LastName");
attr.setValue("abc");
Employee.setAttributeNode(attr);

Element Education = doc.createElement("Education");
Education.appendChild(doc.createTextNode("BE"));
Employee.appendChild(Education);


TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("C:\\Blog.xml"));

// Output to console for testing
// StreamResult result = new StreamResult(System.out);

transformer.transform(source, result);

System.out.println("File saved!");
}


}

The usual XML parsing is done using SAX PARSER or DOM parser.
DOM parser is comparatively rich in functionality,it creates a DOM tree in memory not just that it even allows to manipulate that DOM tree.
Having said that SAX parser saves a lot of space when dealing with large input files, it runs faster and also a lot more easier to learn because the API's is very simple.



Comment:Little tedious to work on if we generating large XML files but work good for small XML files