What are advantage and disadvantages of accessors and mutator method?

1 answer

Answer

1024063

2026-04-27 15:45

+ Follow

Accessors and mutators are advantageous when you want to run some code as part of setting or retrieving a member. A classic example is a class for a window in a program. You might want to store the left,right,top,bottom values, but you also want methods that set the width and height. Accessors/mutators let you store the data any way you want (left,right,top,bottom or left,right,height,width) and keep the interface the same. In fact, a future version of the class might CHANGE the way you store the data. If you're using accessors and mutators, then you can do this without requiring class's users to change also.

Continuing with the window, when you set any of these properties, you want the window to resize automatically. So there might be a lot of code that gets run.The disadvantage is that they add some complexity.

a.setsize(b.getsize())

is a lot uglier than

a.size = b.size

and it takes more typing. And all the accessors and mutators take a lot of space in the class declaration. And if the accessors/mutators simply set/get a private member variable then they don't add any functionality. And they might add a bunch of unnecessary code if the optimizer doesn't take care of it.

In my opinion, accessors and mutators are grossly overused. If your class is used by one or to client applications that are developed in-house and all they do is set/get private member data then I think they shouldn't be used. In this case, you are trading certain complexity for an uncertain future benefit (that you'll need to run some code when setting/getting those members some day). If the code is all in-house then you can just modify the client code if you ever change the class.

So the bottom line is that they certainly have a use, but they come at a cost. Use accessors/mutators when

  • You are sure you need to run some code when setting/getting member data, or
  • there's a reasonable chance that you'll need to run some code in a future release and changing the client code will be difficult or impossible.
ReportLike(0ShareFavorite

Copyright © 2026 eLLeNow.com All Rights Reserved.