There is this famous quote that says
Procedural code gets information then makes decisions. Object-oriented code tells objects to do things. — Alec Sharp
The subject of the post is precisely about that.
Let's assume we are developing a game in which we have a Game
where there is a Board
.
When facing the problem of deciding which methods are we going to implement on the Board
class, I always think of two different ways:
The first approach is to
populate the Board
class with getSize()
, getPieceAt(x, y)
, setPieceAt(x, y, piece)
. This will seem reasonable and is what is generally found in libraries/frameworks. The Board
class has a set of internal features that wants to share and has a set of methods that will allow the client of the class to control the class as he wishes. The client is supposed to ask for the things he needs and to decide what to do. If he wants to set all board pieces to black, he will "manually" iterate over them to accomplish that goal.
The second approach is about
looking for Board
's dependent classes, and see what they are "telling" it to do. ClassA
wants to count how many pieces are red, so I'd implement a calculateNumberOfRedPieces()
. ClassB
intends to clear all the pieces on the Board
(set all of them to NullPiece
, for example), so I'd add a clearBoard()
method to the Board
class. This approach is less general, but allows for a lot more flexibility on other aspects. If I "hide" Board
behind an IBoard
interface, and decide that I'd want to have a board with infinite size, doing in the first way, I'd be stuck, as I'd have to iterate over an infinite number of items! On the other hand, in this way, I could do fine (I could, for instance, assume all pieces are null other than the ones contained in a hashtable!).
So...
I am aware that if I intend to make a library, I am probably stuck with the first approach, as it is way more general. On the other hand, I'd like to know which approach to follow when I am in total control of the system that'll make use of the Board
class -- when I am the one who is going to also design all the classes that'll make use of the Board
. Currently, and in the future (won't the second approach raise problems if later I decide to add new classes that are dependent on the Board
with different "desires"?).