When should I use OOP?

Hello, I have been thinking when I should use OOP but I still haven’t figured it out.

Could someone explain this to me and give me an example?

2 Likes

Hey there,

thinking is a great start.

What did you come up with?

Could you come up with an example when using OOP would be efficient?

You can write your code procedurally, one thing after another. Start, do this, then do that, now finish.

That’s fine, but as the program gets bigger, it becomes very difficult to write.

Dividing up the different parts of the program can help to mitigate this problem.

One way to do this is by describing parts of the program as self contained little packages of data and code that can share data/functionality, manipulate their own data, and talk to each other. The data relating to a specific part of the program is kept hidden in these packages, and the code attached to the package can be used to alter it.

So say you want to look in a folder on your computer and list all of a certain type of file (say images)

You could write a procedural script. Go to a folder, look at the files in it, writing the names of the image files to a list, print that list.

But say that’s only part of your program. That script will get unmanageable very quickly as more and more functionality is added.

So you could create something maybe called a FolderReader. It has some initialisation logic that creates the FolderReader object (maybe the path to the folder and the file type you’re looking for). Then maybe it has a list_files function attached to it. So you would do something like folder_reader = FolderReader.init("path/to/folder", ".jpg"), then to get the list you’d do folder_reader.list_files().

Lots of languages are built to make it easy to write programs in this style (Python, JavaScript, Java, C# etc).

1 Like