41 ms·
Avoid getters and setters whenever possible
- mannykannot 9y agoI have sometimes wondered why none of the mainstream OO languages implemented an access class of publicly readable but only privately modifiable.
- akmarinov 9y agoDoes Swift count? private(set) is a thing
- mannykannot 9y agoSure, Swift counts - thanks for the correction. Maybe those with experience of it could comment on whether they found this feature useful in practice.
- hardwaresofton 9y agoSome do -- for example in C# you can do: public int member { get; private set; } That said, C# is very much my kryptonite and I hate it, so don't ask me any further questions.
- watwut 9y agoI prefer getters setters over Car1 example especially for large classes. I am quite used to use prefix to filter for methods in IDE - get<thing>, add<thing>, set<thing>, create<thing>, is<thing>, to<thing>, etc. Often you know which one of those subgroups you are interested in and can do ctrl-o or ctrl-space and filter irrelevant options out. The worst option of all is when there are both getters/setters and public fields. But most importantly, the real practical differences between these styles are minimal for all practical purposes. It is all mostly matter of habit. You might as well argue about which shade of blue is best for syntax highlighting.
- sigi45 9y agoI prefer actions over getter and setters. The object should take care of itself (ddd style). But xml and db to object mapper often need them :(
- nwatson 9y agoSome Java frameworks let class and interface authors use decorators on getters / setters to control how particular class/interface fields are used in some contexts ... e.g., one might have a field (due to an algorithmic consideration) in an entity that's useful when constructing POJOs (plain-old Java objects) that eventually are written to a database, but that particular field should should not be persisted to the database -- one can use decorators to control whether field goes to database, or the data type used to persist the field in the database, etc. It's sometimes useful to treat the getter and setter asymmetrically.
- ninkendo 9y agoI have trouble articulating this point, but I never understood the argument why you’d want getters or setters at all. From my point of view, your data structures are your API. Attempting to hide them behind methods so that you can do something clever doesn’t work when it’s not always you that constructs the data (I’m thinking of things like json deserialization and accepting data from outside your control.). All the arguments behind getters and setters seem rooted in this fear that maybe you’ll change your mind later about your data, but somehow you won’t have to change the function signatures of your getters/setters when that happens... this seems so contrived to me it’s insane to design entire frameworks and paradigms with this as a central idea. Maybe I’ve been using Go for a bit too long now but I really think the mixing of data and logic is a fundamental mistake.
- singularity2001 9y ago>> mixing of data and logic try lisp;) also in a language like java, where you can't upgrade a field to a property(function), these were placeholders, IF someday you want to be smart about that field.
- ninkendo 9y ago> someday you want to be smart about the field That’s the part I don’t get. Why would you suddenly decide one day that a field needs to be smart? What’s the use case for an API that promised something is just dumb data and then suddenly isn’t any more? If you need encapsulation, you shouldn’t be pretending to the downstream consumers that you have “fields” at all. A good rule of thumb to me seems that if all you’re writing is getFoo/setFoo, you’re just a struct in disguise, and when you want to start making these things “smart” you need to rethink your API because the thing has fundamentally changed from data to logic, and pretending otherwise seems a really bad idea. I guess what I’m saying is there’s a real place for dumb data in programming. And complicated behavior happening behind the scenes of a dumb-data facade sounds like an anti-pattern to me.
- acdha 9y agoI’m inclined to this position as well but consider cases where you need values to be restricted or linked. A setter would allow that to happen reliably every time without changing your API to require validation calls before doing anything else. Getters definitely seem less likely to have cases like that unless there’s some sort of ordering contract you need to enforce. How valuable this is will come down to audience: if it’s a small team which is very familiar with the app, there’s considerably less value than a large app with a huge team or a library intended for other people, especially non-experts.
- CodeArtisan 9y agoTo me, objects is a data abstraction technique which is about abstracting the said data under a set of operations known as the interface; You are no more thinking about the data but about the operations which then allows all kind of interface abstraction techniques known as design patterns. Once you break that abstraction, you break everything which is relying on. Even for small classes where there is no design pattern involved, it is important to think about the interface first then the data. take for example, a rectangle, you may think (g/s)etters would be pointless and be tempted to do class Rectangle: public x, y, w, h; public Rectangle(x, y, w, h): this.x = x; ... Then you need the area class Rectangle: ... public area(): return w * h; Then you need to cache the area class Rectangle: public x, y, w, h, cached_area; public Rectangle(w, h): this.w = w; this.h = h; cached_area = w * h; public area(): return cached_area; Problem here is that w and h being public, user can corrupt the area, you now need to rely on (s/g)etters. class rectangle ... private w; public setWidth(w): this.w = w; updateArea(); private updateArea(): cached_area = w * h; If you had start with an interface only having operations, you would never had that problem. interface Rectangle: getX(); setX(x); getWidth(); setWidth(w); area(); ... // implementations are irrelevant to the user. class RectangleCached implements Rectangle: ... class RectangleLazy implements Rectangle: ... class RectangleWhatever implements Rectangle: ... One of the great leaps in OO is to be able to answer the question "How does this work?" with "I don't care" (Alan Knight) Note that another solution in this case would be immutability but this is another discussion.
- laurent123456 9y agoThis is strange advice. There's no real drawback from using getter/setter and there are obvious benefits. And even if you mostly use public properties, there will still be cases where you'll need getter/setter so you'll end up with a messy mix of getter/setter and public properties. Better be consistent and always use getter/setter.
- LandR 9y agoGetters, yes. I would argue that everything that can be immutable should be immutable though unless you have good reason for it to be mutable.
- MrBuddyCasino 9y agoThats the right answer. Have immutable classes with constructor-injected fields, and getters. In Java Lombok makes this scalable to many members using the builder pattern, and in Kotlin its a non-issue anyway.
- davewritescode 9y agoAgreed but immutability can lead to builders and builders lead to lots of code bloat. Plus, from what I've experienced lots of frameworks depend on java bean conventions (i.e. getters/setters for everything). There's really two missing features of java that could solve 90+% of the use cases for getters/setters. - Attributes: annotation or keyword based directives for the compiler to generate getters/setters for a given instance variables - Default + named parameters which would reduce a lot of the pain of multiple constructors and constructors with a tremendous number of parameters.
- phkahler 9y agoInstead of attributes that lead to creation of getters/setters, how about the simple notion of private or public access to members? I'm not sure which should be the default, but it sounds like Java programmers would like them private unless otherwise specified. Why add code when all you want is to restrict access?
- simion314 9y agoI disagree with the author, getters and setters are a good tool to have and used in the right place. Setters are great when you want to do some validation and add an entry in a log when the setter is used. There are rules what not to do in getters or in setters so if you use does practices you are ok.
- striking 9y agoThe author admits you indeed cannot avoid using them sometimes and mentions exactly the validation case as one of the times you end up writing something similar to a setter anyway. You agree with the author but haven't realized it, I think.
- jonhohle 9y agoNo admission is necessary. There is an entire class of immutable languages (typically functional), which don’t allow mutation (and therefore don’t need setters).
- chopin 9y agoI try to avoid setters whenever possible in favor of constructors taking the dependency as parameter. That way, reasoning about the lifecycle of dependencies is much easier.
- simion314 9y agoI agree, if you can make the object imutable by setting all it's fields at construction time then it is great, if you have to update the object then is good to use setters or functions that can perform validation, it makes it easy to catch errors earlier.
- barrkel 9y agoThe argument for getters and setters is much stronger when you're writing libraries that are dependencies for projects you don't control. If you own all consumers of your code, and it's all part of the same project, then you can safely refactor from field access to getters and setters if and when you need to add extra semantics. If you own the consumers but they're not all part of the same project, you can refactor but it will take longer and be a multi-step exercise. If you don't own the consumers, then you need to break compatibility, which means major version bumps, which will leave some downstream consumers on older versions, and will probably increase version divergence in your userbase, fragmenting the ecosystem and increasing your support load.
- striking 9y agoFrom TFA: > * I would consider creating both a getter and a setter for the data use case in a public API, like let's say I am writing a library meant to be used as a dependency in a lot of other applications. But I would only consider it after exhausting all of these list items.
- benmmurphy 9y agoI think it is kind of insane not to recompile when your downstream dependencies change and the recompilation fixes this problem. Like presumably it makes sense to run your tests again when you change downstream dependencies and it is extra work to run tests independently of recompilation so I think most people's process would be update dependency -> recompile -> run tests. I just remember Java having lots of gotchas with binary compatibility and I assume C# has similar issues. It's just easier to not depend on binary compatibility and always recompile. I'm guessing this is a result of 'insane' processes where you have people upgrading dependencies in deployed applications without properly going through a test process. (EDIT: oops i thought this was a c# post. but this change in java breaks source compatibility as well as binary compatibility)
- jacques_chester 9y agoMy understanding is that C#'s properties were designed pretty much exactly for this situation.
- klmr 9y agotl;dr: “Don’t use getters and setters” shouldn’t be a goal to strive for. Good OO design should be the goal, and the reduction of getters and setters (and of public data members) is a consequence of that. I fundamentally agree with the author: Getters and setters often break Tell, don’t ask, increase the public interface of a class (and expose implementation details), and add mutable state, which makes reasoning about the program’s state harder — for getters, this is often mitigated by defensive copying, which has its own set of issues (it can introduce glaring inefficiencies in the code base, which, in many cases, could have been entirely avoided). The extreme case is when getters and setters lead to quasi-classes [1]. All this is uncontroversial when you think about it (and is backed by a vast consensus in the literature and by what little evidence we have in evidence-based software engineering). On the other hand, I agree with the author that accessors are sometimes a practical solution and shouldn’t be banned entirely. But I don’t think the author states the case well at all. There’s too much talk about feelings, which is a poor substitute for arguments. This starts with the first example that’s provided: Contrary to what the article claims, there’s of course a difference between `Car1` and `Car2`. Namely, `Car2` can add logic to its accessors without creating introducing API changes. `Car1` cannot do this: If I for instance need to ensure that `engine` is never set to `null` by the user, or I need to add logging, or I need to add deferred loading, etc, I need to make `engine` `private` and add public accessors. Future-proofing isn’t always relevant but it unfortunately tends to become relevant unexpectedly. Anyway, neither example is probably very good code and, conversely, either piece of code can be appropriate. But they’re emphatically not the same. I also don’t think the “list of options” at the end is particularly useful because it seems to be a substitute for properly thinking about the architectural design of the code (which doesn’t need to happen up-front, it can happen iteratively): Many accessors are simply never necessary and were instead added “just in case”, or because the programmer thinks about objects as “bags of data” instead of, more appropriately, “[black] boxes with a specific observable behaviour”. This simple change of perspective will drastically reduce the number of public accessors in a code base; but this happens as a side-effect of better OO design, rather than a goal in itself. [1] http://www.idinews.com/quasiClass.pdf http://www.idinews.com/quasiClass.pdf
- osullivj 9y agoIMHO getters & setters can be a bad smell, symptomatic of classes that are just dumb aggregations of data that have no significant behaviour. I've seen them most often in Java - a single paradigm lang that forces every method or data item to be a class member. And then, because our data item is a class member, it must be encapsulated. Multi paradigm langs offer better approaches to data aggregations. Python, for instance, gives us dictionaries and named tuples as well as classes.
- larzang 9y agoGeneric data types aren't necessarily a better approach. My primary language for many years has been PHP, where the default approach used to be just to pass generic maps around for all data, and it was hell. You cannot tell if a map passed to you has any of the members you expect, hasn't had additional unexpected members added, or anything else about it without parsing it, it's a mystery bag. There are times when a mystery bag is fine and you're going to be inspecting it anyway, but most of the time your code has at least some expectations about the structure of your data, and for that you need real specific types to maintain any kind of sanity. Otherwise, you're re-validating data over and over or writing code that relies on hope and faith instead of correctness.
- spdionis 9y agoWhy use actual objects and rely on static anlysis when you can write tens of unit tests that ensure the maps/tuples passed around always contain the correct data structures? And you get the added benefit of 100% test coverage.
- sgift 9y agoThe first point: > (...) My question is how often has the working programmer ever had to do that? I don't remember ever doing this in all my years of software. has that hollow ring of "I write my software the way it doesn't allow easy changes, so I don't do them, so there's no reason to do it." ... there probably would've been reason to do it more than once, the author just didn't want to do it because it would've been painful. Anyway: If you can make your class work without exposing anything then go ahead. That's great. But if you have to allow external access a getter will always be better than direct access. p.s.: Setter means mutable class. Mutable classes are a performance hack. Sometimes you have to do it, most of the time it's premature optimization.
- sakuronto 9y ago> Mutable classes are a performance hack. Could you please clarify this point? I have no idea what you're trying to say.
- jacques_chester 9y agoIt's often much faster to modify something in place than to create a modified copy. Suppose I have: Point point = new Point(50, 50); int x = 100; int y = 200; Point translatedPoint = point.plus(x, y); // new Point(this.x + x, this.y + y) This code suggests that Point is immutable. Once defined, a point never changes. This makes a lot of sense -- if you change the values of x and y, you have a different point, in a mathematical sense. But newing up an object is tremendously slower than integer arithmetic. Suppose I can do this: Point point = new Point(50, 50); point.translateX(100); // this.x += x point.translateY(200); // this.y += y Point translatedPoint = point; This is going to lead to translatedPoint much more quickly than the first code. But it's riddled with troublesome outcomes. Who else was relying on point? What happens if I change it again? Why am I able to mutate something that, mathematically, isn't mutable? The basic reason mutability improves performance is that you can change things in-place without making a new copy. Most of the stuff being done during the copy construction is overhead compared to the thing you're changing. The price might be too high in a performance-sensitive situation. There are workarounds based on using copy-on-write datastructures with clever shared bits, but they're not native idioms in Java-land or in most languages without a strong functional heritage.
- jacques_chester 9y agoOverlooked is how they became so ubiquitous: JavaBeans. It was well-meant, but it's left a lot of unintended pain in its wake (I'm looking at you, JPA constructors). Without that standard, Java code might feel quite differently today. While you can avoid making it worse with idioms like only using constructor injection, you can't unwrite the billions of lines written to date. Kotlin makes a great effort to atone for the sins of the past.
- sgift 9y ago> While you can avoid making it worse with idioms like only using constructor injection, you can't unwrite the billions of lines written to date. But you can fix them. One line at a time. So many years of atonement still to do ...
- meirelles 9y agoFor Java exists the Project Lombok, it works pretty well for this purpose, you can use getters and setters without polluting the code with auto-generated stuff. Have some other cool features like fluent accessors, builders, auto cleanups for close() and plugins for IDEs. IMHO every Java programmer should check it out.
- sgift 9y agoOr AutoValue (https://github.com/google/auto https://github.com/google/auto) for something a bit less involved - Eff. Java 3 recommends it as an alternative to writing equals/hashcode et. all by hand.
- MrBuddyCasino 9y agoNowadays its quite nice. There used to be some pain with regards to IDE integration, but the IntelliJ Plugin works very well. Just be aware that Lombok bleeds into other areas as well, e.g. you'll need a recent version of Sonar to properly calculate coverage.
- absove 9y agoMy favorite is immutables (https://immutables.github.io/ https://immutables.github.io/). It's really frictionless and at this point it feels like an extension of the language to me. It also lets you fall back to mutable types when you need them, despite the name.