Is it a good programming practice to not use getters and setters in trivial parts of code?

That depends on your definition of "trivial". It also depends on how you intend to use the class and how much control you want over the data that is contained within an instance of the class. Care to provide some sort of example for discussion purposes?

IMO the greatest advantage of getters and setters is that there is only one place in the entire program that accesses the class variable. If something has to be changed than you can change is in only one spot instead of hundres of places throught the program. Make the variables private to enforce that position even for trivial cases. Once you start writing larger and more complex programs you will learn to appreciate those get/set methods.

class X
{
int data_;
void f()
{
 int cached = data_;
if (cached >= 0 && cached < 1000 || cached < 0 && cached > -1000)//second version     
{
       //do something       
}     
else       
{       
//do somegthing else       
}
}
};

Was there a question or comment? I think you should use more parentheses for clarity if ( (cached >= 0 && cached < 1000) || (cached < 0 && cached > -1000) )//

As to the original question

Is it a good programming practice to not use getters and setters in trivial parts of code?

If you can you should avoid the getters and setters and create a function that already does what the user would do by using the getters and setters. Of course that doesn't mean that you should get rid of getters and setters altogether, because sometimes its not possible, just minimize it.

And as to your last post, I have no idea what you want with that.

>>If you can you should avoid the getters and setters and create a function that already does what the user would do by using the getters and setters

Huh??? Sounds like a contridiction. How do you avoid getters and setters by creating a function that uses them??

No you are reading it wrong. This is what I mean :

class Point{
 int x_,y_;
public:
 Point(int x = 0, y = 0) : x_(x) , y_(y) {} 
 int getX(){ return x_; }
 int getY(){ return y_; }
 void setX(int x) { x_ = x; }
 void setY(int y) { y_ = y; }
};

//users code
Point p(0,0);
int dx = 5;
int dy = 5;
 //translate the point
p.setX( p.getX() + dx );
p.setY( p.getY() + dy );

notice how the user is using get/set function to achieve translation. So I am suggesting that the class Point just have a translate(int dx, int dy) function so that it reduces the need for get/set. Thats the general idea. Of course in the class Point it might not be wise to remove getX/setX and getY/setY altogether.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.