Why setters and getters




















What is ASP. NET Core? How to iterate through ArrayList in jQuery? What is the difference between TempData keep and peek function? A class provides a default constructor for me.

Python's syntax to achieve the effect is just simpler. Show 1 more comment. Now here is almost 10 almost good reasons NOT to use getters and setters: When you realize you need to do more than just set and get the value, you can just make the field private, which will instantly tell you where you've directly accessed it. Any validation you perform in there can only be context free, which validation rarely is in practice.

You can change the value being set - this is an absolute nightmare when the caller passes you a value that they [shock horror] want you to store AS IS. You can hide the internal representation - fantastic, so you're making sure that all these operations are symmetrical right? You've insulated your public interface from changes under the sheets - if you were designing an interface and weren't sure whether direct access to something was OK, then you should have kept designing.

Some libraries expect this, but not many - reflection, serialization, mock objects all work just fine with public fields.

Inheriting this class, you can override default functionality - in other words you can REALLY confuse callers by not only hiding the implementation but making it inconsistent.

StackedCrooked 33k 41 41 gold badges silver badges bronze badges. I think the crucial argument is that, "if you were designing an interface and weren't sure whether direct access to something was OK, then you should have kept designing. In real OOP, however, an object is more than a container of data fields. It encapsulates state and algorithms to manipulate that state. What's crucial about this statement is that the state is supposed to be encapsulated and only to be manipulated by the algorithms provided by the object.

Jorge Aguilar Jorge Aguilar 3, 28 28 silver badges 34 34 bronze badges. I know it's a bit late, but I think there are some people who are interested in performance. I've got the following result: Time 1: ms, Time 2: ms Time 1: ms, Time 2: ms Time 1: ms, Time 2: ms Time 1: ms, Time 2: ms Time 1: ms, Time 2: ms Time 1 is the direct way, Time 2 is the getter You see, the getter is almost always a bit faster.

The results: 10 million cycles: Time 1: ms, Time 2: ms Time 1: ms, Time 2: ms Time 1: ms, Time 2: ms Time 1: ms, Time 2: ms Time 1: ms, Time 2: ms With 10 million cycles, the times are almost the same.

Nick 6, 16 16 gold badges 36 36 silver badges 44 44 bronze badges. There's a "noticable" overhead having a function call to access the memory instead of simply loading an object's address and adding an offset to access the members.

Chances are the VM flat-optimized your getter anyway. The two main ones are polymorphism, and validation. Even if it's just a stupid data structure. Thanks for the first half-decent explanation of interfaces I've read, sans any references to "remote controls" or "cars" — djvs. But anyways, nice idea to present it! We use getters and setters: for reusability to perform validation in later stages of programming Getter and setter methods are public interfaces to access private class members.

Encapsulation mantra The encapsulation mantra is to make fields private and methods public. Getter Methods: We can get access to private variables. Setter Methods: We can modify private fields. Even though the getter and setter methods do not add new functionality, we can change our mind come back later to make that method better; safer; and faster.

Anywhere a value can be used, a method that returns that value can be added. Qantas 94 Heavy 15k 31 31 gold badges 62 62 silver badges 80 80 bronze badges. Devrath Devrath I spent quite a while thinking this over for the Java case, and I believe the real reasons are: Code to the interface, not the implementation Interfaces only specify methods, not fields In other words, the only way you can specify a field in an interface is by providing a method for writing a new value and a method for reading the current value.

Those methods are the infamous getter and setter Okay, second question; in the case where it's a project where you're not exporting source to anyone, and you have full control of the source In any non-trivial Java project you need to code to interfaces in order to make things manageable and testable think mockups and proxy objects.

If you use interfaces you need getters and setters. Think simple, easy, add complexity when needed. Mohamed Mohamed 1 1 silver badge 2 2 bronze badges. So then does the getter call the setter? I've added a code sample of how I've done it in the past - essentially, you store the actual class in a protected member, then return that protected member in the get accessor, initializing it if it is not initialized.

It's C docs. One aspect I missed in the answers so far, the access specification: for members you have only one access specification for both setting and getting for setters and getters you can fine tune it and define it separately. John Millikin John Millikin k 38 38 gold badges silver badges bronze badges.

Re: C. I meant that clients of the class will have to be recompiled. Adding validation logic to a setFoo method will not require changing the interface of a class at the language level , but it does change the actual interface , aka contract, because it changes the preconditions.

Why would one want the compiler to not treat that as a breaking change when it is? MartinhoFernandes how does one fix this "broken" problem? The compiler can't tell if it's breaking or not.

This is only a concern when you are writing libraries for others, but you're making it out as universal zOMG here be dragons! Requiring recompilation, as mentioned in the answer, is one way the compiler can make you aware of a possible breaking change. And almost everything I write is effectively "a library for others", because I don't work alone. I write code that has interfaces that other people in the project will use. What's the difference? Hell, even if I will be the user of those interfaces, why should I hold my code to lower quality standards?

I don't like working with troublesome interfaces, even if I'm the one writing them. One of the basic principals of OO design: Encapsulation! Justin Niessner Justin Niessner k 37 37 gold badges silver badges bronze badges. The encapsulation getters and setters offer are laughably thin. See here. If your public interface states that 'foo' is of type 'T' and can be set to anything, you can never change that.

You can not latter decide to make it of type 'Y', nor can you impose rules such as size constraints. If you have a constraint, such as the object can be set to null, or the value has to be within a range, then yes, a public set method would be required, but you still present a contract from setting this value that can't change — thecoshman.

Why can't a contract change? Why should things keep on compiling if contracts change? You should use getters and setters when: You're dealing with something that is conceptually an attribute, but: Your language doesn't have properties or some similar mechanism, like Tcl's variable traces , or Your language's property support isn't sufficient for this use case, or Your language's or sometimes your framework's idiomatic conventions encourage getters or setters for this use case.

Getters and setters are used to implement two of the fundamental aspects of Object Oriented Programming which are: Abstraction Encapsulation Suppose we have an Employee class: package com.

Pritam Banerjee Pritam Banerjee To me having tons of getters and setters that do nothing unique is useless. Having just the three variables public then keeping getFullName will make the program easier to read but still have that fullname thing hidden. Generally I'm completely fine with getters and setters if a. The benefit with this is that you can change the internals of the class, without changing the interface. Say, instead of three properties, you had one - an array of strings.

But if you just used public properties, you would also have to change every class accessed Employee, because the firstName property they've been using no longer exists. AndrewHows from what I've seen in real life, when people change the internals of the class they also change the interface and do a big refactoring of all the code — Heetola.

Sumit Singh Sumit Singh GeZo GeZo 51 4 4 bronze badges. Pete Pete 11k 4 4 gold badges 38 38 silver badges 53 53 bronze badges. I suppose that changing the behaviour of the getter or setter isn't a breaking change then.

MartinhoFernandes doesn't always have to be. TBYS — Phil. Jason Baker Jason Baker k gold badges silver badges bronze badges. I'd never expect a getter or setter to be an expensive operation.

In such cases better use a factory: use all setters you need and then invoke the expensive execute or build method. Rakesh Singh Rakesh Singh 41 2 2 bronze badges. Usama Tahir 8 8 silver badges 14 14 bronze badges. Antz Antz 1 1 silver badge 5 5 bronze badges. It would be implemented at runtime with "trivial methods". Actually, probably non-trivial. Today this can be done with an annotation preprocessor. The Overflow Blog. Does ES6 make JavaScript frameworks obsolete?

Podcast Do polyglots have an edge when it comes to mastering programming Featured on Meta. Now live: A fully responsive profile. Linked See more linked questions. Related Hot Network Questions. Get certified by completing a course today!

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:. Report Error. Your message has been sent to W3Schools. W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. You're stumbling in the dark. It's not an accident that every chapter in the Gang of Four's Design Patterns book includes a "Consequences" section that describes when and why using a pattern is inappropriate.

Stating that some language feature or common programming idiom like accessors has problems is not the same thing as saying you should never use them under any circumstances. And just because a feature or idiom is commonly used does not mean you should use it either.

Uninformed programmers write many programs and simply being employed by Sun Microsystems or Microsoft does not magically improve someone's programming or design abilities. The Java packages contain a lot of great code. But there are also parts of that code I'm sure the authors are embarrassed to admit they wrote. By the same token, marketing or political incentives often push design idioms.

Sometimes programmers make bad decisions, but companies want to promote what the technology can do, so they de-emphasize that the way in which you do it is less than ideal. They make the best of a bad situation. Consequently, you act irresponsibly when you adopt any programming practice simply because "that's the way you're supposed to do things.

EJB-based technology is great technology when used appropriately, but can literally bring down a company if used inappropriately. My point is that you should not program blindly. You must understand the havoc a feature or idiom can wreak.

In doing so, you're in a much better position to decide whether you should use that feature or idiom. Your choices should be both informed and pragmatic. The purpose of these articles is to help you approach your programming with open eyes. A fundamental precept of OO systems is that an object should not expose any of its implementation details. This way, you can change the implementation without changing the code that uses the object. It follows then that in OO systems you should avoid getter and setter functions since they mostly provide access to implementation details.

To see why, consider that there might be 1, calls to a getX method in your program, and each call assumes that the return value is of a particular type. You might store getX 's return value in a local variable, for example, and that variable type must match the return-value type. If you need to change the way the object is implemented in such a way that the type of X changes, you're in deep trouble.

If X was an int , but now must be a long , you'll get 1, compile errors. If you incorrectly fix the problem by casting the return value to int , the code will compile cleanly, but it won't work. The return value might be truncated. You must modify the code surrounding each of those 1, calls to compensate for the change.

I certainly don't want to do that much work. One basic principle of OO systems is data abstraction. You should completely hide the way in which an object implements a message handler from the rest of the program.

That's one reason why all of your instance variables a class's nonconstant fields should be private.



0コメント

  • 1000 / 1000