Lesson Wednesday

Abstraction is one of the most important concepts in object-oriented programming. Abstraction is the process of hiding and encapsulating complex code so that it's easier to use. Because this concept is literally quite abstract and can be a bit difficult to grasp, let's look at an example.

When we drive a car, we only need to know a few things about the car. These things can be boiled down to a set of methods such as .start(), .steer(), .stop() and .go(). We don't need to know how these methods work behind the scenes in order to use them. Many things happen in a car's engine when we .start() the car but they are quite complex and we'd rather concern ourselves with other matters.

In other words, we could say the underlying complexity of the car's engine has been abstracted away to just a handful of methods which are easy to understand.

In computer programming, we encapsulate the complexity of our code in methods.

class Car
  def start()
    # A lot of complex stuff is happening in here but we don't need to understand it or 
    # even know about it in order to .start() a car. 
    # In fact, this method might need to call a dozen other methods, 
    # but we wouldn't want the user to have to call them all manually!

Now our method can be called outside the class:

car = Car.new()

We don't see any information about the .start() method is achieved. Nor do we need to know anything else about a Car in order for .start() to work.

We are already using abstraction regularly every time we write a well-encapsulated method that can be used outside a class. In fact, we can think of abstraction as being an important payoff of encapsulation.


Abstraction: The process of hiding and encapsulating complex code so that it's easier to use.

Lesson 18 of 22
Last updated August 7, 2022