Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Learning OOP Design

Tags:

oop

I've read Head First Java, and I understand how OOP works. Here's my problem: I'm a PHP programmer, and while I've used OOP in PHP, I'm having trouble figuring out what should be an object and what methods to give it.

For example, let's say I have a app that allows people to log in and edit a document. Why should the document be an object if there will ever only be one instance? Should I give the deleteDocument() method to the document object or the admin object? The document is the one being deleted, but the admin is the one performing the action.

So my real question is, coming from a procedural background, how do I figure out what should be objects and what should have what methods?

like image 277
waiwai933 Avatar asked Mar 21 '10 22:03

waiwai933


2 Answers

Well in your example, I'm not sure why in your design there's only one document, but it should still be an object in case at a later point you want more than one.

As far as the delete function, there's really no straightforward answer; you're likely to find arguments on both sides. Myself, I would put the lower level delete functionality (things like deleting database entries) inside the document class, but any other functionality may go in the parent. If all documents are owned by an admin, the admin should have a DeleteDocument which calls delete on the document, and also removes all associations from the database.

In general, coming from procedural, if you ever find yourself passing around a big array of state variables or declaring lots of globals, then turn that related functionality into a class. Try to keep the functionality that an object contains as closely related as possible, or you may find your classes bloating way out of control.

like image 136
Tesserex Avatar answered Sep 22 '22 15:09

Tesserex


There's no answer that always holds. If you're interested in object-oriented design, I recommend this book.

As for your question of how to figure out what should be objects and what methods they should have, a good heuristic is to ask yourself if having some ability is essential to being some thing. Here's an example I remember from my OOP class... You're keeping track of people and pets in an application. Should the person class have a getPets() method? Well, is having a pet essential to being a person? No. A better solution might be to have a separate relationship class representing the pet ownership.

like image 43
miorel Avatar answered Sep 19 '22 15:09

miorel