Sunday, April 1, 2012

Avoiding Setters and Getters

For the novice programmer who is just beginning to delve in the world of object-oriented programming, setters and getters are typically the goto method of manipulating data fields of objects. Sometimes it is difficult to program without using setters and getters, specifically getters. It is often necessary to ask an object what kind of state it is in, or the value of some data field it holds. This is nice and all for testing and quick/dirty class creation, but it fails to shield the programmer and other objects from its implementation. Ideally all classes should hide all of the dirty details of the class and instead perform the computation that another class would use the value for in the first place.

In the current project in OOP, this has been a real chore, but this one of those projects that can be a disaster if designed poorly or a lot of fun if designed with good object-oriented design practices in mind. The project basically consists of a grid that holds creatures of different, or equivalent species. These species can turn, move around, and infect other creatures such that they are now the same species. In this picture, it is easy to see that there should be a grid, creature, and species class, in which the creature holds some form of a species.

The question is: How does the grid communicate with the different creatures on the board without simply asking for different data fields? How will the grid know which direction they are facing? How the instructions of the different creatures be passed around? The easy approach would be to have the grid simply ask for different data fields of the creatures and do all of the computation itself, but this is ugly and can lend itself to debugging disasters. It is much cleaner to give the creature some information based on what is in front of it and have it do some computations based on its own data to figure out what to do next , and then relay that information to the grid.

It is just lately that I have been forced to program without the use of getters and setters. While they do have their purposes in some cases, I am beginning to see how objects can communicate in a much more elegant and purposeful fashion if they are avoided.

No comments:

Post a Comment