Information-hiding

Information-hiding is a term that is used very often with regard to encapsulation. The idea behind information-hiding is that the class or object should not expose any information to the outside world unless it is necessary for another part of system. Let's try to understand this with an example:

class Person(pName: String, pAge: Int, pHeight : Double ) {

var name : String = pName
var age : Int = pAge
var height : Double = pHeight

init {
require(name.trim().isNotEmpty()) {"Name should not empty"}
require(age > 0 ) {"Age is not correct"}
require(height > 0) {"Height is not correct"}
}
}

fun main(args: Array<String>) {
val person = Person("bob",40,6.1)
println("Name ${person.name}, Age ${person.age} Height ${person.height}"
}

This is a fully functional Person class from the previous chapter where the init function verifies all values before the object is created. If any of the values do not meet the requirements, such as if the name is empty or the age or height is a negative number or zero, Kotlin will throw an IllegalArgumentException. It is necessary to provide valid values when creating a Person object. However, if Kotlin is allowed to access the properties and change the current status of the object without verification, the following might happen:

person.age = -41
person.height = 0.0

The person properties are reassigned with the values that were prevented at the time of object-creation. The idea of information-hiding is to hide the class properties and prevent them from reaching the outer world. In Kotlin, properties are first-class citizens, which means they are directly accessible. This doesn't mean that these properties should be accessible all the time, however; we have to provide a getter function to read the properties and a setter function to update them. Before updating the properties, we can provide an additional layer of validation in the setter function to prevent objects with unwanted data.

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

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