Jump to content

Why its a bad practice to directly access data members?


dpacmittal

Recommended Posts

I think you're referring to using getter and setter methods as better practice than accessing the data directly.  By providing a method with 1 course of action (viewing) or (changing) the data, it is usually prone to less mistakes.  It's about controlling the integrity of the data afaik.

I think you're referring to using getter and setter methods as better practice than accessing the data directly.  By providing a method with 1 course of action (viewing) or (changing) the data, it is usually prone to less mistakes.  It's about controlling the integrity of the data afaik.

Thanks for the info.

A big pro with using getter/setter methods is that it provides a bit of future-proofing. Say a few months down the line you need to make an update to your code and modify what happens to the variable.

 

For example:

<?php
class Robot{
var $numFingers = 5; 

}

 

Directly accessing the member would give you the right answer, until you decided that you were adding the arms functions. Now, $numFingers is the number of fingers on each arm. So the total number of fingers would actually be $numFingers*$numArms.

 

If you were directly accessing the data then you would have to apply the multiplication outside the scope of the class. However, if you had a getter/setter method, you could just update your setter method to multiply $numArms*$numFingers and then you wouldn't need to change any code that required those values.

 

I hope the example helped visualize it a little.

A big pro with using getter/setter methods is that it provides a bit of future-proofing. Say a few months down the line you need to make an update to your code and modify what happens to the variable.

 

For example:

<?php
class Robot{
var $numFingers = 5; 

}

 

Directly accessing the member would give you the right answer, until you decided that you were adding the arms functions. Now, $numFingers is the number of fingers on each arm. So the total number of fingers would actually be $numFingers*$numArms.

 

If you were directly accessing the data then you would have to apply the multiplication outside the scope of the class. However, if you had a getter/setter method, you could just update your setter method to multiply $numArms*$numFingers and then you wouldn't need to change any code that required those values.

 

I hope the example helped visualize it a little.

Yes, it helped. Thanks

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.