Chapter 12 Classes
12.10 Object Oriented Programming¶
Functions and classes are two of the most influential concepts in programming. Central to procedural programming, functions allow code to be modularized into sub procedures, so that complex functionalities are represented by simple function calls. Functions are so influential to computer programming that it is typically supported by hardware also.
Classes, on the other hand, offers modularized organization of both code and data. The concept of classes is central to object oriented programming, which has had a significant impact on programming languages over the past few decades, including C++, Java and Python. The two inventors of object oriented programming both won the Turing award, the most esteemed honor in the field of computer science.
There are three most important elements in object oriented programming, namely encapsulation, inheritance and polymorphism. Encapsulation refers to the aggregation of attributes and methods in a class, which represents a complex data type, and the hiding of implementation details by using methods as interfaces to operations on instances. Inheritance refers to the availability of base class attributes and methods in sub classes, which enables code reuse in a type hierarchy. Polymorphism refers to different behaviors of the same method between different objects. For example, when the ‘+’ operator is applied to two numbers, it calculates the sum of the two operands; but when applied to two sequence objects, such as strings, it calculates the concatenation of the two operands.
Another typical example of polymorphism is the shape hierarchy in a graphical user interface. Suppose that the shape type is a general type, and the square, circle and triangle types are its sub types. Each of the three sub types has a method, draw, which draws itself on the monitor. The behavior of draw is different when the sub type is different, drawing a different shape. However, as long as the user knows that an object is an instance of the shape type, she can call the draw method of the object, drawing it on the monitor. The drawing behavior is polymorphic.
It is a good habit to put frequently used sub routines into functions, and the most important data structures into classes. However, there is no simple formula for the best design of function and class interfaces, and a better design can often lead to significantly less cost in code maintenance, particularly when the software program becomes large. How to design the most readable code is an important subject in software engineering, and it takes practice to build experience on this skill.
© Copyright 2024 GS Ng.