Pages: [1]
Author Topic: Getters and Setters: why?  (Read 7160 times)
0 Members and 1 Guest are viewing this topic.
Paul Vickers
Programmer Analyst

Brians: 42
Offline Offline

Posts: 131


« on: March 30, 2012, 03:07:18 PM »

I was thinking about how getters and setters can be used effectively for abstraction and data hiding. I came across this hypothetical example in the book "Using UML: Software Engineering With Objects And Components" (Stevens and Pooley):

"As a simple concrete example, suppose a module provides an interface to a point in 2D space, and that the interface allows clients to get and set the position  of the point using either its Cartesian coordinates (x, y) or its polar coordinates (r, theta), whichever is most convenient to the client. Does the module store both sets of coordinates and keep them consistent or does it store one set and use that to calculate the other on demand? This information is of no interest to client programmers; the module interface should abstract away from it, and encapsulate the data structure inside the module."

So, I thought I'd implement something like this. In the attached project is a class called PolarObject which extends Sprite. Sprites have x and y properties for determining Cartesian location. My new PolarObject class also has properties 'r' and 'theta' to represent the radius and angle needed for a set of polar coordinates. (In fact, x and y are not properties at all but are, in fact, getters and setters.) But, if you look at the code you will see that r and theta aren't stored properties but are, in fact, getters and setters. The getter for r will just work out what r should be given the current x and y; likewise for the theta getter. The setters take the new r or theta and change the values of x and y accordingly. Note, though, that r and theta aren't actually stored anywhere. The neat thing about this is that changing x and y doesn't require any other changes: as soon as r or theta are inspected the getters will calculate what they should be.

So, we have a class that appears to have four properties: x, y, r, theta but which are all nothing more than getter/setter functions (x and y are inherited getter/setter functions too). I guess we could add _r and _theta properties and then override the x and y getters/setters to update _r and _theta when x and y are changed, but there's simply no need.

* (10.52 KB - downloaded 1068 times.)
« Last Edit: March 30, 2012, 03:10:42 PM by Paul Vickers » Logged
Pages: [1]
Jump to:  

Terms of service | Privacy policy

Paul Vickers is a participant in the Amazon Europe S..r.l. Associates Programme, an affiliate advertising programme designed to provide a means for sites to earn advertising fees by advertising and linking to

How to think like a programmer: problem solving for the bewildered pdf
How to think like a programmer: program design solutions for the bewildered pdf
Powered by EzPortal