Programming: Objects and Classes

    Programming: Objects and Classes

      Most modern programming languages have objects. Whether or not those objects are central to the language's preferences is another story. Despite that fact, objects can be really important for making good, reusable code.

      An object in general is a tangible, visible thing. That’s a great definition, but (you may have noticed) programming isn't usually so tangible, and you need to work pretty hard to make it visible. So the entire object definition kind-of goes out the window when we try to apply it to computers. It’s there, inside the memory. But you can't see it—unless you're the computer whisperer. The program can see it, though, and that's all that really matters.

      Now that we know just how painfully different an object in programming is from a real-world object, let's talk about what it actually is. Every object has two different types of characteristics: state and behavior.

      Say you have a light bulb. The bulb has one state: glow state. The behaviors can be turning the bulb on or off.

      "Glow state," or "on state" or "did I leave the light on in the hallway again?" are only names for the states and behaviors: they can be just about anything. There are definitely more states and behaviors for the light bulb like:

      • Shattered
      • On fire
      • Disassembled in the name of science

      but for our simple light bulb program, we don't need to worry about it going down in a burning ring of fire.

      A state can be called a

      • field 
      • variable

      and behavior can be called a

      • function.
      • method.
      • message.
      • subroutine. 
      • procedure.

      A class is a blueprint for creating objects, so any state and behavior belonging to the object should also belong to the class. If an object is a specific light bulb, then a class is the general idea of a light bulb (sorry if we cause Platonic flashbacks) and tells us what every light bulb should have/do.

      Objects, classes, and functions organize code to make it more readable and easy to modify. Imagine a big blob of code. No classes, no functions, just line after line of variables and operators.

      Makes us shiver just thinking about it.

      It could take years—literally years—to understand where and when the code calculates the sum of two numbers. But when we add objects and functions, the code's given a description—at least if we name things well. On the same vein, the code is modular (divided into modules). It’s very clear what happens where and what, exactly, the code as a whole does.