Encapsulation

Summary

Encapsulation is the technique by which ColdC carries out the programming concept of Information Hiding, and thereby, Separation of Concerns (advanced programming concepts which I'll only touch on here).

The basic breakdown:

  • Every object has its own information (object variables)
  • Nobody else can see or use its information (in that no other objects may access another object's information)
  • The only code (method) that can access an object's information is its own code -- code that is defined on that same object

Simple enough rules: my info is mine, your info is yours, and we don't share! However, eventually the objects will need to exchange their information with eachother, and possibly change each other's information depending on the scenario. Each object can, however, have public methods, which are usable by other objects.

Object Example

Let us say we have two objects: $picnic_table and $garden_hose. Let us also say that the table can be wet (or dry), and the hose can make things wet.

$picnic_table variables:

wetness
How wet the table is (0 to 100%)

$garden_hose variables:

wetness_per_second
How much wetness the hose adds per second

Let us say we wish to program the hose to automatically spray the table until it is 100% wet (I know... weird example). The code to spray water will be defined on the garden hose, but as we know, code on the garden hose cannot modify the wetness variable found on the table. Instead, the table must also have a method that will allow it to be made wet. In addition, the hose will need to know how wet the table is, so the table will also need to have a method which will reveal the wetness of the table.

$picnic_table methods:

@program $picnic_table.add_wetness +access=public
	arg howMuch;
	wetness += howMuch;
.

@program $picnic_table.get_wetness +access=public
	return wetness;
.

$garden_hose methods:

@program $garden_hose.spray +access=public +flags=forked
	arg target;
	
	while (target.get_wetness() < 100) {
		target.add_wetness(wetness_per_second);
		$scheduler.sleep(1);
	}
.

In this manner, code from one object may interact indirectly with the data stored on another object. The power of this approach to programming is realized when you consider that the hose does not care what it is spraying -- as long as the target knows how to get wet. Likewise, many things can make the table wet -- the table doesn't care how, as long as the .add_wetness() method is called. This concept is a type of Polymorphism.