advantage of using getters and setters in OOP??

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
PHPycho
Forum Contributor
Posts: 336
Joined: Fri Jan 06, 2006 12:37 pm

advantage of using getters and setters in OOP??

Post by PHPycho »

Hello forums !!
I would like to know
1> the advantage of using getters and setters in class ?
2> is directly accessing the properties of class harmful ?
3> good techniques for designing the robust class ?

Thanks in advance to all of you!!
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

  1. Getters (accessors) and setters (mutators) give you control over the information placed into the properties. There are many times where very specific information needs to be in properties. If access wasn't controlled someone could place an unexpected value and potentially break the class' code.
  2. Read #1
  3. Methods should, with little exception, do one thing. Classes should, with little exception, do one thing too, but at a more macro level than methods. Each method should generally be a verb that the noun (class) does.
Consider a car. It's a kind of vehicle, which is made up of many components. Some of these components are wheels, windows, doors, a steering wheel, seats, engines, "fuel" sources, etc. In turn, those components are made of components. A car can carry people and many arbitrary objects.
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

However, in ActionScript (Flash), we avoid traditional get and set functions. The horrible thing about ActionScript 2.0 is that running a method consumes a lot more memory than just performing the operation. But every other language that supports OOP, use getters and setters. ActionScipt is like, the only exception. (Although they have a built in set/get setup that feels like you're not using them, but you are. It's weird, really.)

Just thought I'd throw that in. ^_^
Post Reply