- Read Tutorial
- Watch Guide Video
Through my years of teaching, one of the most common questions I get from developers is how to best understand object oriented programming. OOP development can seem a bit intimidating if you've never used it before so I wanted to take a step back and give a high level perspective of how it can be used to build applications.
My History with OOP
When I started programming over a decade ago I learned how to build applications procedurally with languages such as C and PHP. If you’re not familiar with procedural code, it simply means that you build programs in sequential order and call methods when you want shared behavior between pages in the application. For example, if I had an invoicing application, I’d have a page for creating a new invoice, another page for showing the invoice, etc. And each page would have scripts that would call methods such as ones connecting it to the database or rendering a date in a specific format.
How Does OOP Work?
Now that you have a high level view of how procedural programming works, how does object oriented programming work? I like to think of object oriented programming as a way of modeling a program, where all of the functionality is abstracted so it can be shared throughout the application. Let’s take a look at a real world case study.
Imagine that you’re building an application that allows users to create accounts and you also need to have the ability to make some people administrators. In object oriented programming you’d have a User class, in that class you’d have methods such as:
- Register
- Sign in
- Encrypt password
- Etc
Now we have the issue that you have two types of users: regular users and site administrators. For the most part both user types are pretty similar, the only differences will be things such as editing pages and admin type tasks. In procedural programming you’d need to create two different types of users which would lead to having quite a bit of duplicate code. However in object oriented programming you can simply create a User class, and then create RegularUser and AdminUser classes that inherit from the parent User class.
When child classes inherit from the parent class they get access to all of the methods and functionality of the parent class, and then you as a developer can give them custom behavior. So for our case study the AdminUser class would contain methods unique to it that the RegularUser class wouldn’t have, which would give it the administrator functionality.
Do you see how that works?
Object oriented programming, at at high level, is all about being able to structure code in a way where functionality can be inherited and behavior modified in any way that the developer sees fit. If done properly object oriented programming can lead to very elegantly written programs that have minimal code duplication.
I hope you have a better idea of how object oriented programming works.