Encapsulation

In procedural programming language like C, data and behavior are mixed together in one file. The data can be accessed in any behavior. It means that some data can be changed by some behaviors that are not associated with that data. It leads to data corruption.

Reason for Data Insecurity in Procedural Programming

  • It is the global variables that leads to data insecurity
  • Global variables can be accessed in any functions in the program. So it means that the value of the global variables can be changed by the unrelated functions.
  • Whenever unrelated functions accessed that data, data corruption arises.

For example:


#include <stdio.h>

int result = 0;

int main() {
	result = sum(5, 5);
	printResult();
	return 0;
}

int sum(int firstNumber, int secondNumber) {
	return firstNumber + secondNumber;
}

int multiply(int firstNumber, int secondNumber) {
	return firstNumber * secondNumber;
}

void printResult() {
	printf("Result is %d", result);
}

void unrelatedFunction() { //assuming some unrelated behavior accesses the "result" variable
	result++;
}

Encapsulation?

Encapsulation is one of the core concepts in object oriented programming. Encapsulation is the binding of data with their corresponding behavior.

What is binding?

  • The concept of restricting the availability of the data only to its related areas and related functions it is known as binding.
  • Because of binding we can restrict the availability of data to the unrelated functions
  • So that unrelated functions cannot access the data
  • Class is the base for encapsulation
public class Room {

	private long id;
	private String roomName;
	private String building;

	public String getRoomName() {
		return roomName;
	}

	public void setRoomName(String roomName) {
		this.roomName = roomName;
	}

	public String getBuilding() {
		return building;
	}

	public void setBuilding(String building) {
		this.building = building;
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + (int) (id ^ (id >>> 32));
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Room other = (Room) obj;
		if (id != other.id)
			return false;
		return true;
	}

	@Override
	public String toString() {
		return roomName + " " + building;
	}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s