State and Behavior

Dear Computer

Chapter 5: Objects

State and Behavior

A playwright drives a plot forward by assembling a cast of interesting characters and having them interact with one another. Each character has a unique personality and fulfills a certain role in the narrative. Similarly, an object-oriented programmer drives a computation forward by assembling a cast of interesting objects and having them interact with one another. Each object has certain state and behaviors that guide its interactions.

An object's state is its data. Sometimes this state is called properties, attributes, or instance variables. The state of a treasure chest object in a video game is its location and contents. The state of a forum post is its author, subject, body, time of publication, and number of upvotes. The state of an array-based list is an array holding its elements and the number of cells that are occupied.

The behaviors of an object are the services that it can perform. You can open a treasure chest or remove it once its contents have been extracted. You can upvote or edit a forum post. You can add or get items from a list. These behaviors are implemented as methods. They often have names that start with verbs, particularly in the Java community. If a behavior only returns an object's state or some value derived from its state, the behavior is a getter. If a behavior updates an object's state, the behavior is a setter. Together the getters and setters form an object's accessors.

In this chapter, we will explore how programmers form and choreograph objects in Ruby and other object-oriented languages. By its end, you'll be able to answer the following questions:

Object-oriented programming took the software development industry by storm in the 1990s and 2000s thanks to C++ and Java. People championed it as the way to build big software. But it didn't fix all the problems that its proponents said it would, and it may even have introduced some new ones. Nevertheless, objects have proved useful as a modeling tool and are here to stay. Many newer languages offer a hybrid of object-oriented and function-oriented programming.

Object Syntax →