DEV Community

Sana Mohiuddin
Sana Mohiuddin

Posted on • Updated on

Object Oriented Programming

As a beginner programmer, it is important to understand what object-oriented programming is and how it can make your program better. Object-oriented programming is a paradigm that centers around using real life by using objects, as the name suggests, and basing the code around these objects. There are languages like Java or Ruby that are OOP languages and are created to be used as such. To better understand object-oriented programming and how to utilize it and the important qualities that come along with it, we will be using Ruby in the examples.

The Basics of OOP

It may seem scary to tackle a new concept that seems so daunting, but it is actually quite simple once it is broken down and with practice. In fact if you have already been using Ruby, you have most likely been using objects and have not known. String, Integer and Array are all examples of different types of objects that are pre-defined for us by Ruby.

str = "This is an object"
Enter fullscreen mode Exit fullscreen mode

The above example is how you may be used to creating a new string, but you can also do it by writing the following:

str = String.new("This is an object")
Enter fullscreen mode Exit fullscreen mode

This may look a bit different but it is doing the same thing. The first example is just using a bit of syntactic sugar to make it cleaner and more visually appealing since Strings are a very commonly used object, Ruby helps us out a bit. What we are doing in this example is creating a new instance of the String class and assigning the value to be what is inside the parentheses. You may be wondering what a class is and that is what we will discuss in the next section.

Classes

A class is how you are able to create your own objects. They are essentially a template that will define the properties and methods of an object. Imagine you are building a library, you would need a lot of books. You could create each book individually, and add all the necessary methods and properties. However, all books are essentially the same minus the details. They have a title, authors, number of pages, you can read them, bookmark them, etc. It would be much easier to create a book class, and you create as many book objects as you need to fill your library, with overly repetitive code. Let's start with how to declare a class.

class Book
#code describing class here
end
Enter fullscreen mode Exit fullscreen mode

It is quite straightforward, you simply use the class keyword following the name of you class with the first letter capitalized. If your class name is a combination of multiple words use camel cases to separate the other words. For example, if your class is describing dog toy objects the class name would be DogToy. To signal the end of the class use the end keyword. Between those two elements is where all your code will go. In order to create a book object you would do the following:

mistborn = Book.new
Enter fullscreen mode Exit fullscreen mode

There is that new word again. Whenever you are creating an instance of a class you use the class name followed by the new keyword, and that will create a new instance.

Important elements to have in a class are getter and setter methods for the instance variables. The setter method allows us to set or change the variable, whereas the getter method allows us to retrieve the value of the instance variable. You can type these out or you can use ruby macros that do the heavy lifting for you. They are the attr_writer, attr_reader and attr_accessor macros. attr_writer will define a setter method for a variable, attr_reader will define a getter method, attr_accessor is an even shorter short cut for when you need a getter and setter method for a particular variable. The code snippet below is an example of how you would use these. Each instance variable is separated by a comma.

attr_accessor :title, :author, :num_of_pages, :current_page
Enter fullscreen mode Exit fullscreen mode

The next important item to discuss about classes is the initialize method. The initialize method is not called by its name like you are used to, but instead it is called when you create an instance using the new keyword. You can even use parameters to initialize your instance variables within the method.

def initialize(title, author, num_of_pages)
   @title = title
   @author = author
   @num_of_pages = num_of_pages
   @current_page = 0
end
Enter fullscreen mode Exit fullscreen mode

The @ refers to the instance variable and allows you to set it with the values passed in. If you wanted to create a new book object and pass in those values you would simply add those values after the new keyword.

mistborn = Book.new("Mistborn", "Brandon Sanderson", 792)
Enter fullscreen mode Exit fullscreen mode

Now let's look at an example of all of those elements put together along with some instance methods.

class Book
   attr_accessor :title, :author, :num_of_pages, :current_page

   def initialize(title, author, num_of_pages)
      @title = title
      @author = author
      @num_of_pages = num_of_pages
      @current_page = 0
   end

   def read
      puts "I am reading #{self.title}"
   end

   def bookmark(page)
      self.current_page = page
   end

   def finish
      puts "I am finished reading #{self.title}"
   end
end
Enter fullscreen mode Exit fullscreen mode

We have a fully functional Book class. You should now have an understanding of what almost everything above means and does. The only thing you may not understand is the self keyword. The self keyword allows you to refer to that particular instance.

mistborn = Book.new("Mistborn", "Brandon Sanderson", 792)
mistborn.read
#will output: I am reading Mistborn
Enter fullscreen mode Exit fullscreen mode

The self keyword allows you to access the value within the instance variable in the class. So you can do things like shown above.

Conclusion

You should now be able to create basic classes and have a better understanding of what object-oriented programming is and how it can help your code be less repetitive and more modular. There is still a lot more to OOP, like inheritance and polymorphism, but you are now equipped to tackle those topics.

Resources

Top comments (5)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Languages like Javascript were not designed with OOP in mind, but have added features that support it, when demand called for it.

Err... JS has been object oriented since it was created. Pretty much everything in JS is an object, or is wrapped in an object. It's a core part of the language

Collapse
 
smohiudd1688 profile image
Sana Mohiuddin

Thank you for your feedback, I have updated the post!

Collapse
 
jlee1546 profile image
Jonathan Lee

Very informative! Thank you for the info

Collapse
 
aminmansuri profile image
hidden_dude

Historically there have been 2 types of OO languages:

  • Class based languages (based on Smalltalk)
  • Prototype based languages (based on Self)

Most languages followed the Smalltalk way (though usually very poorly), while JavaScript did it the Self way.

OO is about objects. If objects are editable at runtime (as in JavaScript) then classes are just a convenience. There are other ways you can "inherit" or essentially do the same trickery as you did with classes.

One could argue that it's more dynamic and more straightforward. But most programmers are more familiar with the concept of classes than with protoypes.

Collapse
 
scottmichaud profile image
Scott Michaud

For beginners:
It's convenient to use object-oriented to represent "real objects" in some cases, such as having "weapon" objects represent weapons in a video game.

As you move forward, it's good to know that all of these tools are designed to simplify problems. What OOP is really good at is a bit more abstract than modeling the real world, though. Its goal is to wrap a chunk of data into an isolated unit. You create types with a specific set of actions. This does not have to relate to anything in the real world.

For example, a video game character could have a variable for "AI logic". If you can boil down your AI code into a handful of methods (such as an update method) then you can freely swap the AI code and know that, once you reassign the variable, the old AI code cannot affect the current state of the character. This means that you can look at each AI state (be it persona, mood, or whatever criteria you use to separate the specific AI Logic components) individually.

That's the goal of OOP. Use the analogy of "types" to wrap state (data) into the smallest set of interactions required to have a full set of features. Externally, people know the features that you can use. Internally, you know the features that you need to support. No-one stomps on each other.

Two problems can arise, though:

  • Your internal representation is complex because, inside your class, your methods are all stomping on "this" (which is a read/write/friend variable auto-injected into every non-static method). Using a handful of parameters is generally better than using this, especially if your language allows you to not write to some of them, because you can just look at the top and know everything that function could possibly read from or write to, rather than scanning the function body for anything stealthily used.
  • Thinking about things as objects can sometimes confuse your actual goal. It might make you want to change your problem to match your mental model of your system. Changing your problem is bad. You're solving something that feels like, but isn't, what your real problem is. Your system should just be a very simple solution to your actual problem.