- Feature Articles
- CodeSOD
- Error'd
- Forums
-
Other Articles
- Random Article
- Other Series
- Alex's Soapbox
- Announcements
- Best of…
- Best of Email
- Best of the Sidebar
- Bring Your Own Code
- Coded Smorgasbord
- Mandatory Fun Day
- Off Topic
- Representative Line
- News Roundup
- Editor's Soapbox
- Software on the Rocks
- Souvenir Potpourri
- Sponsor Post
- Tales from the Interview
- The Daily WTF: Live
- Virtudyne
Admin
Admin
Everyone argues that you could just change it from a public field to a property later when they are young and inexperienced. For some, it takes experience to change that point of view. For me, it took changing a public field to a property, then running make and ending up with a error count in the middling 5 digits. That was fun.
Admin
Admin
The real WTF is that some people think that public setters and getters are a form of encapsulation. They're not. They're a way of exposing the contents of an object through its API, which breaks encapsulation. Sometimes it's necessary, but extensive use of public accessors and modifiers is very often a sign of bad design.
Admin
[quote user = "Torus"]Everyone argues that you could just change it from a public field to a property later when they are young and inexperienced. For some, it takes experience to change that point of view. For me, it took changing a public field to a property, then running make and ending up with a error count in the middling 5 digits. That was fun.[/quote] What language were you using? What caused those errors? Will this issue occur in a language like C#?
Admin
Admin
Admin
Yes, but getters/setters can be a controlled break in encapsulation with validation and control of what gets changed rather than an all out do whatever you want type break.
You can always return a copy in a getter and validate like crazy in a setter.... Public field? not so much....
Admin
Admin
[quote Mike.D] I'm wondering how this is done in Perl? Just one way to do it, please, I'm sure there are more. ^_- [/quote]
It's quite long time since I've programmed perl ... but AFAIR, it was possible to define a generic method that would be executed when a non-existent method was called. I think I once wrote a class where a call to getName, getWeight, setName, setSomethingElse etc would be caught and would perform as a default getter/setter method.
Admin
Benefits of properties vs public fields:
Disadvantages:
If there are only potential advantages and no disadvantages, why not just make them all properties? You may not see much of a reason to do so, but you should see even less of a reason to not do so.
Admin
Admin
From reading that Python code earlier I'd definitely start with public fields in that language, if only because it would be readable then. ;)
Admin
Been a while since I used c++ but isn't inline incompatible with dynamic binding?
At any rate, great explanation.
Admin
Admin
The best way to do getters and setters is to have some dog-easy-to-set-up default getters and setters which you can install on your code for Absolutely Free or Pretty Darned Close, and then it's not a PITA either way.
Of course, some languages make this easier than others (hug perl).
Admin
If you're using the shorthand {get; private set;} then if you just have {get;} you'll never be able to set the field, not even in the defining class.
Admin
The question is - how does going from a field to a property affect consumers in that specific language. One thing I have learned (from reading this site if nothing else) is that the fewer changes you have to make later, the better. So perhaps it's better to put a bit more effort in now and know exactly how your properties will be accessed than leave it til later and possibly break things you weren't even aware of (back to reflection!).
Admin
It's interesting that no one has mentioned one of the main benefits of explicit get/set. I have been caught many times by a simple typo in code
if ( object.Value = "whatever" ) { ... }
As a public element, I have successfully set the value . . .
Admin
Another advantage of getters/setters is in multi-threading. If I need to access a field in multiple threads, then I can add the synchronization into the getter/setter. Otherwise I have to add in synchronization in every place that accesses the variable.
Admin
I don't know C#. But coming from C++, what about taking pointers of those fields having getters and setters? Can you do that?
Admin
Admin
You may have a naming convention that differs for public fields and properties, and don't want to have to change all the names later if a property becomes necessary.
You can more easily set a breakpoint to catch when a property is changing or being read. (Though in many IDEs/debuggers this is possible without using a property.)
Various frameworks may only bind to properties, so in general there could be features that are not accessible with public fields that would be accessible with properties.
If consumers of the class are using reflection to access properties and fields, changing a property to a field later on will affect them in unpredictable ways.
Of these, I find the 4th point the most convincing, as you seem to as well. Though even there, it would be a pretty stupid consumer that gets mixed up when you add a new property. I suspect such stupid consumers are also going to be surprised when you suddenly start throwing validation errors (and in general I expect throwing validation errors where you didn't before to be quite disruptive). So I'm still not completely convinced. But I admit the list is getting longer, and it's easy to see how someone could be convinced. And you're right, in C# it's just a few characters, it's hard to argue against it.
Admin
Admin
Wow, I can't believe nobody answered poor Michaels question, even though he asked it like 20 bloody times.
The reason you can't "just change it later" and the reason for all my errors is from OTHER CLASSES ACTUALLY USING THEM.
Sure, if you have a class that is not used at all, ever, then you can change it later without a problem. If, however, you have a thousand other classes, that all do something like
if (myClass.booleanFlag) { ....
and then you make booleanFlag private, and write getBooleanFlag and setBooleanFlag, then every single one of these other classes will not compile anymore because they are trying to access a private or possibly even nonexistant field. That's why you can't just change a field to a property later without sometimes tons of trouble. Again, that's only true if you actually use those classes.
Admin
Depending on the language and the use, have property getters/setters are needed for things like databinding because it uses reflection.
The fact that even if properties have private members to be used within the property makes it more maintable code in the long run.
Using code generation is smart... why wouldn't you want to?
Admin
The truly good ones have that effect on me.
Admin
I think Michael was probably assuming a language where switching from a field to a property could be done without changing the way the consumer accesses it. For example in C# I could do this:
public bool booleanFlag;
and you can access it as
if (myClass.booleanFlag) { ....
You can later change it a property like this
private bool _booleanFlag; public bool booleanFlag { get { return _booleanFlag; } set { // do some validation or whatever _booleanFlag = value; } }
Now you can still access it like this:
if (myClass.booleanFlag) { ...
So no difference for you as a consumer of the class.
However, for all the points that everybody else makes, I think it's still better to make it a property from the start.
Admin
Yes, but what if, instead of making booleanFlag private, you make it a property? i.e. public boolean booleanFlag {get; set;}? Now, obviously this depends on your language allowing such things, but assuming it does, myClass.booleanFlag would happily compile and run whether booleanFlag were a public field or a property.
Admin
Admin
This all depends on what the attributes and objects are.
For instance, if I have a 'telephone' object, what I shouldn't do is use a setter to dial -
Instead, I should use a method -
But, with the same phone object if I want to turn off the ringer, there's nothing wrong with
So, public accessors are fine, as long as not used as an alternative to good design.
Admin
I don't think context switching means what you think it means...
Admin
hmmm, I nearly fell for that one...my powers are weak...
Admin
I would have used String.IsNullOrEmpty(SearchParts), but there you go.
Admin
The only WTF here is ascribing an action to a getter which simply doesn't belong there. It conditionally changes the control flow of the program, as seen by the user at least. If I found my engineers doing this, I'd can them on the street faster than they can revert their changes.
In terms of static interpretation, a variable is a niladic function. Referencing a variable will always, to the code reader at least, return a value, whether computed or simply retrieved from a location in memory. Or, it might throw an exception if necessary (e.g., if searchParts == Null, and this violates the invariant of the class, then an exception is definitely the solution to use here). In either case, referencing a variable is taken to be a referentially transparent action. I'd hate to be the poor soul who has to debug this code months or years down the road.
Throwing an HTTP redirect inside of a getter is spaghetti code, plain and simple. It has no reason for existing there. When reading client code, there is NOTHING to indicate to the reader that a redirect might occur, or under which circumstances.
Admin
In my humble opinion:
A lot of posters are saying there are no disadvantages to get/set except a couple of extra lines of code, or that this doesn't even count as a disadvantage. I beg to differ. Every extra line of code is one more line that someone has to plow through to understand the program. That's why I write "x+=2" and not "x=x+2" or "x=x+1; x=x+1;". Sure, ONE unnecessary extra line of code in a program is no big deal. But what if my class has twenty fields that interact with the outside world? A minimal get or set function takes four lines on the page (the way I write it anyway, with the braces each on their own line), so twenty pairs of such functions is 160 lines. That's nothing to dismiss. (And yes, I don't like having that much data interacting with the outside world, but it happens. Often.)
So if I need validation or side effects every time a value is updated or retrieved, sure, I write getters and setters. If I don't need validation or side effects, and there's no reason to believe that I will in the near future, then I just declare the field public and use it.
Yes, someday the requirements may change and I will have to add getters and setters. Fine. I mostly write in Java, and Eclipse will change all the references to gets and sets with a few clicks of a mouse. If I was writing a package that I expected to distribute as a utility that programmers outside my organization would invoke from their own code, I'd lean a little more to using get/set because I then wouldn't have access to the calling code to do any refactoring.
In any case, I almost never have to turn a public field into a get/set property. Off the top of my head I can only think of one time in the past decade that I have done this. So sure, I try to write code that is flexible and extensible for future requirements changes. But you can't provide for everything. I plan for what's reasonably likely, and deal with the rest when it comes.
Admin
I disagree, I think properties with getters and setters can actually aid understanding of the code. For example, if a particular property has a public getter, but a private setter, then you can reasonably conclude that the original programmer explicitly did not expect anybody to set the value outside of this class. If they are both public, then you know that the programmer expected changes to come from outside (or, more likely, just didn't really think about it). Also, although I'd use x+=2; I'd argue that x=x+2; is much more explicit.
Admin
Because now all the consumers must be recompiled to CIL bytecode that uses the get/set functions instead of directly accessing the data. When the JIT compiler turns that bytecode into machine code, it will be inlined and turned into code just as fast as direct access, but the CIL bytecode itself will forever be changed from a stfld/ldfld to callvirt. Therefore, anything that uses it must be recompiled.
If this was a class library, now you have an unknown number of other class libraries or executables that you must recompile. If you had just used a property in the first place, no recompiling would be necessary, you would simply change the internal code without changing the external interface.
If this is inside an executable, now every compile unit that uses it must be recompiled. Usually compilers like to skip unchanged compile units for a shorter compile time.
Admin
Admin
Admin
Admin
Try learning how to use C#. You CANNOT set a memory change breakpoint when you're debugging C# code. Duh!
Admin
Thank you for not being helpless.
I don't know how python handles it, but if it were to use CIL (".net" is actually the Common Instruction Language standard, ECMA 335), for example IronPython, it must be automatically converting fields to properties. That's the only way it would be able to allow the later addition of accessors without recompiling everything dependent upon it.
You'd have the same problem in C++ even if you used MSVC's __declspec(property) compiler-specific functionality.
You always have special considerations when making DLLs.
Admin
What context switching? This is a function call or a data access - no context needed.
Admin
It seems like a few people are concerned about the extra lines of code added by getters and setters.
I've never had a problem with this, but I make extensive use of the code-block minimization feature that I can't recall the name of. Y'know, the little +/- that you click to expand or collapse a section of code.
I tend to code with related sections separated into regions and with most sections collapsed by default. I find that this helps me find relevant sections more quickly and consistently than searching through a few hundred lines each time.
I know that not everyone does it this way; so I'd like to hear some of the advantages that you feel I am missing out on.
Admin
Because changing from field to property (in C#/.NET) breaks the binary interface (ABI).
All compiled code using your class will break if you change - even if they have the same name. The compiler will convert
to
and
behind the scenes. Other (compiled) .NET code depends on this fact...
Admin
Admin
Don't laugh. I am working on a project right now where something similar is in place. . . or WAS until I saw it.
When you added a record you would get redirected to a page that contained only a message telling you that you did it right and it was successful.
I wonder what better way I could do that. . . ? Hmm. . .
Admin
Agree. Accessor methods reduce code complexity because they can provide guarantees about what users of the object can and can't do. Public fields are insane because any code anywhere could be doing anything with them. If someone has actually worked on a medium or large scale project and still thought public fields were a good idea (outside of edge cases) I'd say they were too retarded for software development.
Admin
That's just incorrect, but nice try. Conditional breakpoints are your friends. Among those conditions are "when changed" which most definitely can be set on a member variable. Check it out sometime.