We’ve discussed object-oriented programming for game developers in general and the specific OOP principles of cohesion and coupling. Now let’s take a look at encapsulation and how it helps to keep code loosely coupled and more maintainable. Note: Although this Quick Tip is explained using Java, you should be able to use the same techniques and concepts in almost any game development environment.
What Is Encapsulation?
Encapsulation is the principle of information hiding. That is, the implementation (the internal workings) of an object is hidden from the rest of the program. A popular example you’ll hear for encapsulation is driving a car. Do you need to know exactly how every aspect of a car works (engine, carburettor, alternator, and so on)? No – you need to know how to use the steering wheel, brakes, accelerator, and so on. Another example is searching for a value in an array. In Java, you can do the following:int myArray[] = {1, 2, 3, 5, 7, 9, 11, 13}; Arrays.asList(myArray).contains(11);The above code will return
true
if the value 11
is in myArray
, otherwise it will return false
. How does the contains()
method work? Which searching technique does it use? Does it pre-sort the array before searching? The answer is it doesn’t matter because the exact implementation of the method is hidden. Why Is Encapsulation Helpful?
Encapsulation helps to create code that is loosely coupled. Because the details are hidden, it reduces the ability of other objects to directly modify an object’s state and behavior. It also greatly helps when you must change the data type of a variable. Lets say you decided to use aString
to keep track of time in “hh:mm:ss” format. After awhile, you come to realize that an int
representing seconds might be a better data type for time. Not only must you change the data type in the object, but also every time you referenced the object’s time in the entire program! Instead, you can use what are known as getter and setter functions. Getters and setters are usually small functions that return and set a variable respectively. A getter function to get the time would look as follows: public String getTime() { return time; }The getter will return a
String
value: the variable time
. Now when we want to change time
to an int, instead of changing all calls to the getter we can just change the getter function to change the int
data type into a String
data type. Read more: Quick Tip: The OOP Principle of Encapsulation
No comments:
Post a Comment