Encapsulation

Procedural programming is a technique where a program is divided into small functions. Each module contains a number of variables to store different kinds of data and functions to operate on that data. While this approach is very simple, it can get much more complex as the application grows because we end up having functions all over the place. If one function changes, it requires the other functions to change. This strong interdependency between functions means that we end up with spaghetti code. This approach not only adds duplicate code in every part of the application, it also makes maintaining the code more difficult.

Take a look at the following example. Here, three variables are provided to the display function. By looking at variable names, we can gather that the function prints person-related information on the screen. There is no direct relation between the variables and the functions because they are decoupled. These variables may be declared in one file and the function in another:

char name[20] = "Bob"; 
int age = 10;
double height = 6.5;

void display( char name[], int age, double height)
{
printf("Name is %d " , name);
printf("Age is %s " , age);
printf("Height value is %f ", height);
}

The object-oriented paradigm helps to combine these related variables and functions in one capsule. As we have discussed, variables are called properties and functions are called behaviors. When the properties and behaviors are combined in one place, we call this encapsulation. 

Let's create a Person class and compare it with the procedural programming approach:

class Person {
var name: String = "Abid"
var age : Int = 40
var height : Double = 6.0

fun display () {
println("Name $name, Age $age Height $height")
}
}

fun main(args: Array<String>) {
val person = Person()
person.display()
}

The display function of the procedural programming technique takes three parameters to display the content. The display function of the Person class, however, takes zero parameters, which is a much cleaner approach because the Person class contains tightly coupled parameters and functions that are gathered in one place.

Encapsulation is an object-oriented programming technique that involves binding the data and function into one unit, which is called a class. All examples in the previous sections are implementations of encapsulation, in which we have defined some properties that store the current state of the object and functions to perform some tasks. Encapsulation is useful not only to put different properties and functions in one class, but also to protect them from the outside world.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.10.1