6

Possible Duplicate:
When are Getters and Setters Justified

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

5
  • I asked a somewhat similar question: stackoverflow.com/questions/2225065/… Jan 20, 2011 at 16:36
  • 1
    This would be easier to answer if we knew what "trivial parts of code" meant, and what would be used instead of getters and setters. Jan 20, 2011 at 16:57
  • @David Thornley also if we knew what language, since some, like ActionScript, can be migrated to getters/setters without changing how the property is accessed or set - function get myVar():int { ... }
    – Nicole
    Jan 20, 2011 at 17:02
  • This depends on the language. In Python, for instance, I believe setters and getters are discouraged. Also, a non-object-oriented language (such as ... Scheme, Clojure, Haskell, assembly, Brainfuck - someone correct me if I am wrong) getters and setters may not be a natural concept, or at all possible. So, there is no way to objectively answer the question as stated - you need to get down to specific language with examples. See programmers.stackexchange.com/questions/21802/…
    – Job
    Jan 20, 2011 at 17:11
  • @Job: For what it's worth, in Common Lisp a defstruct defines something like a struct, but the only access to the members is via functions. The getter/setter distinction doesn't really work here either, due to how the setf macro works. So, yes, the answer would be different in Java vs. Common Lisp. Jan 20, 2011 at 19:02

8 Answers 8

9

Not in my opinion. (Why would you think otherwise?)

At the very least, consistency should be an important factor across a code base, so I'd have thought that if getter/setters are used they should be used globally.

Also, what's trivial now might end up being a great distance from trivial in six months time, so it would be naive to assume otherwise and treat such code segments differently.

1
  • 1
    +1 for the future. Today's trivial part of code is tomorrow's mission-critical part of code. Jan 20, 2011 at 16:49
7

It is good programming practice not to use getters and setters in classes that are intended to be more than bundles of data (like a C struct). They expose the internal structure of the class, violating encapsulation and greatly increasing coupling. Public methods should be used to express operations meaningful according to what the class represents, not according to the implementation.

For classes that are fundamentally bundles of data, they're more complicated than simply making the class data public, but offer slightly more control. Sometimes I prefer public variables because they're cleaner, but setters allow inserting hooks into the modifications, which saved me a lot of work once.

1
  • +1 Recognizing there are two distinct types of object groupings that each have their own techniques for access. Jan 20, 2011 at 18:54
4

A class with extensive getter/setter pairs may be poorly designed (in that it may be poorly encapsulating it's implementation detail). But the getters/setters themselves are not usually the problem in such a scenario, the simple fact that the data is public often is, so in such a scenario a big list of public variables might be just as bad.

It's really hard to say without seeing concrete examples; I would personally shy away from making such generalizations as the one in your question (instead favoring weaker assertions involving "might," "could be", "possibly," et cetera). If a class is intended to be a very high level abstraction, it should probably have fewer trivial get/set pairs versus something modelling a lower level concept.

If, in particular, you mean "trivial" code to be specific one-off code for testing an idea or very small programs, there's probably no need to overabstract or overengineer the solution.

3

I'd argue that you want to TDD (And by that I mean Test Driven Design) your objects. You'l quickly realise whether you really need those setters and getters. I personally only write the code that I have to.

Oh, and if your design later on says I need all of those getters and setters, then that's what modern IDEs are for :)

1
  • +1 For "only write the code that I have to"
    – Mayank
    Jan 20, 2011 at 17:29
3

No code is trivial

If, at runtime, the CPU executes it, then it is non-trivial because it is having an effect.

It's all about encapsulation

If you want to violate pretty much every piece of advice about data encapsulation in the OOP book then just expose the internal state of your object to all and sundry. Simply make the field public and off you go. Before long all those references you're handing out will get modified by some distant call of a call of a call and your object is none the wiser - until it comes to perform some operation that results in epic failure.

Epic fail? I don't want that...

If you want to make sure that only your object is changing it's own internal state then getters/setters are the way to go. The getter/setter guards the internal state making sure that external classes have no other way to get at it. (OK, I hear your subclassing, reflection yada yada ...)

Got an example to clinch it?

Consider exposing arrays. If you do it directly through a getter, such as this (in Java)

public byte[] getRedBackgroundPDF() {
  return this.redPDF;
}

you get an epic fail because the byte[] is passed by reference and so external classes can modify the internals of your class, bypassing the purpose of the getter. The PDF can be modified in some manner (say to make it have a blue background) and your class has no idea.

To overcome this, you need to clone so that the external classes effectively get a read-only version of the byte[].

public byte[] getRedBackgroundPDF() {
  return Arrays.copyOf(this.redPDF,this.redPDF.length) ;
}

External code may change this to be blue, but every time anyone else visits the getRedBackgroundPDF() method they'll always start off with a red background.

It seems unnecessary and ugly, but it protects your internal state.

2
  • 2
    Getters/Setters may guard against unhindered modification of internal state but they still expose the implementation details of the internal state. You are now tightly coupling the implementation of your object to have particular state (Which makes changing or upgrading the class nearly impossible for all but the most trivial classes). Methods should be verb that indication actions that are performed on the object. If you have a getter/setter you need to ask why am I exposing this implementation detail is it because my class lacks an interface to manipulate the object that my users need. Jan 20, 2011 at 18:52
  • @Martin York Although you make some good points, I'm afraid that I disagree. In my getter I've chosen to represent the internal state using the same external type (byte[]). I could just have easily wrapped it up within an object, but that would just have added complexity to the simple example. Even if the internal representation changes, the getter can act as an adapter to maintain the external interface. Also, I disagree that methods should always be verbs. In my opinion encapsulation trumps naming conventions every time.
    – Gary
    Jan 20, 2011 at 21:59
1

According to Jon Skeet (of StackOverflow fame) -

What is a trivial property ? It's one that’s read/write and that stores its value in a straightforward private variable without any validation or other custom code. Trivial properties only take a few lines of code, but it’s still a lot when you consider that you’re only expressing a very simple concept.

Where previously you might have been tempted to use a public variable for the sake of simplicity, there’s now even less excuse for not using a property instead. This is particularly true for throwaway code—which we all know tends to live far longer than anticipated.

EDIT - I would recommend using to use Automatic properties wherever possible. To me it lets me know at a single glance that this property is not doing anything fancy. Also it makes the code more readable.

-1

Yes. I don't use get/set for private attributes if they are not used outside the class and the class can't be inherited.

If you need to access the attribute outside the class, a get/set is in order. A get without set for an immutable class, a get/set for mutable.

When I need to have a bunch of these I grab my IDE and let it generate them for me.

-1

The notion of getters and setters is utterly stupid extremism, so you shouldn't use them. Here's why:

If you have a product type such as a struct in C, then you are provided the categorical projections (getters) as part of the language and you should use them. In C they're also useful for setting a value and also read/modify/write operations. Products are concrete data types, there's nothing abstract about them, and their data should be public. Some idiot languages hide data by default, or allow reading but not writing.

Abstractions should be avoided at all costs. Abstraction is expensive computationally, and I don't mean for the computer (although this is usually the case): I mean for the human brain. Just look at all the ridiculous garbage in OO languages compared to the simple coding in a functional language: even poor languages like C can be very expressive.

Abstraction is useful when you have invariants and are sure of them and would like to enforce them. In this case typically constructors establish the invariant, the data is hidden to prevent use of the projections to break the invariant, and then you need accessors to get information about the object value.

If the object is mutable, clearly you need some way to modify it.

However these are not "getters and setters" in the sense of setting components of a product type, because that's what you're trying to prevent, since some values of the private data structure do not represent values of the abstract type.

Not the answer you're looking for? Browse other questions tagged or ask your own question.