- 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
if(MyComment != null){ return MyComment.Split('|'); } else { Response.Redirect("ForgotToIncludeComment.aspx"); return null; }
Ooo and First!
Admin
I notice that searchParts is written with and without initial capital. But for the rest it: aSearchParts is just a bad name, nothing else.
About the getter/setter: the friend was right. It is nonsense in quite a few cases.
Admin
A good code based WTF that made me laugh... ahh.. just like the good old days.
Admin
Agreed, and in the process of pointing out im not as "l337z Coderz" as some of you, How large is the performance hit for doing it with get/set over not bothering.
I have noticed I am doing the same with some of my projects and there is alot of them that could simply be removed.
Admin
If you are a little bit careful with a get/setter, then the compiler should inline and optimize the code away entirely. If you later have to mess with an objects internals (oops - we have to account in hundredths of cents - didn't we send you the memo? - sorry about that!), you'll be glad if you have used get/setters!
Admin
I Figured that would be the case, But it never hurts to ask for help and all that stuff.
Thanks Robbak :)
Admin
Accessors can be used to fire events when a property change, you can not do that with a public field.
Yes, you can do it with a method, but thats not the matter in hands..
Admin
A boring comment here I am afraid.
Encapsulation is of course right.
We use getters & setters to perform validation on the setting and, erm, getting (well, it could be getting an item in a list and we want to check they're not asking for one we haven't got). Also as future-proofing in case the underlying data structure changes or validation becomes necessary.
BTW, why is my CAPTCHA always illum?
Admin
Which language? In C++, you just declare the accessors and mutators as inline which enables you to maintain the benefits of encapsulation, but still removes the context switching.
However, the real benefits for this practice is that it allows the implementation of that value to change which maintaining the definition. Sure, looking at something like
private: CString m_name; public: inline void SetName( const CString& name ) {m_name = name;} inline CString GetName() {return m_name;}
An you might wonder why you simply don't just let m_name be public. The reason is that by using the 2 functions, you've enabled someone to inherit your class, redefine the Set and Get functions, and still allow C++ to dynamically bind members of the class. You've also made it so that you change what happens when those functions are called and have that change impact nothing outside of the class itself.
Admin
I suppose I should just consider myself lucky that I rarely have to search for my parts.
And I'm yet to get a null from that search.
Admin
And that is the real point, spend a bit of time now with things like getters and setters (heck Eclipse auto generates them even), and the almost certain future demands of your code to do things that you never would have dreamed it be asked to do are a bit easier.
Oh and for those that hate this... my CAPTCHA was duis
Admin
It's considered bad practice to use the inline keyword often.
Admin
Well C# let's you just do:
public int SomeProperty {get; set; }
And then you can add any logic later on as the need arises.
Also, people are overlooking a very useful thing about using public properties instead of public fields: You can set a debugger breakpoint in the property setter to determine when and by what it's being set. Try doing that with a public field...
Admin
Yeah, TRWTF is the original poster not having a good answer. Sounds like a good interview question.
Admin
Well it does insulate you from changes in the internal structure of the class that may lead to what were once member variables becoming derived values.
More than once I've said ...these are just public fields only to regret that later when I decided to redesign the class ..and those fields wanted to disappear in the redesign.
Admin
You're both right. It is extra code, which takes up time and space and can make tings less clear. But those get/sets can be life savers if you ever need to instrument the code to count accesses or you need to scale or audit the data before returning it.
Admin
Watch?
Admin
setters and getters are really, really valuable in Objective C.
Check out the concepts of delegates and key-value observing.
Then again, you really have to write close to zero code to get them:
Admin
Public getters aren't too much of a concern but public setters would make me consider their purpose. I'd prefer to keep setters internal, at worst, on all but the aggregate root. The client then uses the aggregate root to interrogate the object graph. You can then either fully hide the rest of the classes behind this facade, or ensure that the objects you return are immutable.
Btw, would love for someone to try to defend the redirect from a domain object's getter/setter.
Admin
Admin
Ahh I see the WTF, he's using Request.Redirect rather than Server.Transfer...
Admin
Takes up space? You mean in the source code? Am I really concerned that my source files are a few kb larger? And if you were meaning the final executable files are larger, they shouldn't be if you write them properly have your compiler optimize stuff.
Takes up time? Not if you do it as mentioned above and the compiler optimizes trivial ones away.
Less Clear? I fail to see why a = object.myVal is more (or less for that matter) clear than a = object.getVal()
I'm not saying that for every single bit of data in a class there should be a getValue { return _myVal; } setValue(value) { _myVal = value; } but if you have anything accessible from the outside it doesn't at all hurt to add a get/set. Takes all of about 8 seconds to type out, no performance loss and you have the ability to redesign things later if the situation changes.
Admin
Because in order to make them gets/sets, you have to rewrite all the code that ever accesses that public variable to account for it. If you used gets/sets to begin with, you change the get/set and you're done.
Admin
There isn't a performance hit if the getters / setters are inlined.
Admin
But what about when you need to validate data, or perhaps remove a property and make it derived instead of stored?
Edit: hrm I forgot about re-writing the code that uses this class. So even in the best case you're still not even correct :-)
Admin
Not all languages have properties, which means you're far better off writing them as accessor methods ahead of time.
C# offers properties, so you can start something's life as a public data member named as a property (AuditLog instead of mAuditLog, for instance), and replace it with a similarly-named property as necessary. Naming conventions may make this operationally impossible, though, and eschewing conventions just so you can avoid five lines of code is operationally dumb.
In languages without this ability, though, depending on your environment, it may be prohibitive to modify the data member into a getter/setter at a later date.
Keep in mind, changes that include every code file in the project are going to be a lot more difficult to get signed-off and deployed than changes that add a single line to a single function in a single file. Also, your coworkers having to modify the same files will grow to hate you.
Fake Edit: In before the first "I don't see the WTF".
Admin
"removes the context switching. "
you are doing multi threaded getters and setters?????
WTF????
Admin
Getters/Setters make debugging a helluva lot easier when you can't figure out how member data got set. Yes, you can do memory watchpoints to see how the data changes, but that usually isn't as simple as a code breakpoint in most modern IDEs.
Admin
So are SBaynham and others saying that in languages with properties like C#, the only reason to write as a property ahead of time is so you can use a naming convention that distinguishes properties from public fields? If not for naming conventions, I don't see why making a field a property would affect multiple files, or am I missing something?
Admin
Try doing Lazy Loading without getters. :D
Admin
prop[TAB][TAB]
Code snippets are awesome.
Admin
3.. 2.. 1.. fanboi replies that M$ has "watch" too!
Yeah, stole it like everything else.
Admin
Using getters/setters lets you "do things" (like redirect the client!) when someone accesses one of your properties. As far as I know they're normally used for validation, so for example let's say you had a maximum limit on salaries for a person, you could validate it when it's set like this (lots of things omitted for the sake of my fingers...):
If you then tried to do e.g. somePerson.Salary = 200000; it would throw an exception. So you've moved validation to where it belongs - on the field itself.
Admin
I think validation, sanity checking and recalculations are the best reasons for doing it.
In PHP I generally have an array global to the class, and the get/set can only set values of that array. If an external source tries to set a value that doesn't already exist (array keys are pre-declared) it'll throw a warning. It certainly beats having a massive case statement to handle every possibility, or let the external code blindly change any value it feels like.
This way you can use a case statement only for the values that need special treatment or checking on import.
Admin
Admin
You have forgotten one of the most immediate benefits: Keeps others from messing with your internal fields.
For example, if you have a method that defines a string. Using setters you can insure that the string is never set to an invalid valid. So the string might never be null, or it might always be twelve characters long. The setter can enforce the restrictions.
The rest of the class no longer has to check that the string is not null before using it. The rest of the code can assume that the string will be valid.
Getters and setters allow your method to protect itself from other programmers who will end up on this site someday.
Admin
Admin
Won't work in C#.
Admin
I really think getter/setters are ugly, and code consistently using getter/setters almost screams for code generation. IMHO, if one actually wants to generate code, it means the programming language is not sufficiently sofisticated.
At this stage, I of course have to promote my favorite language, python. The pythonic way to do it is to always use attributes for things that, from the caller side, should look and feel like attributes. In those very few cases where one later would like to add some special getter or setter logics, one can do that without changing the API.
As long as it's not abused, I think it's just perfect :-) All the benefits of the getter/setter design pattern without the need of code generation :-)
Admin
Many people are posting many useful things that can be done with properties. I know all that, you can do all sorts of great things with them. But suppose you have a field in an object that you need to access like a regular public field with no validation rules. It's true, maybe someday I'll want to do some fancy tricks with the field and may want it to be a property, but not today. Is there any reason to go ahead and make this field a property right now? So far the valid reasons (for languages with properties like C#) I've seen are:
Naming conventions are sometimes different for properties and public fields, so you don't want to go changing them later.
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.)
I don't find either of these arguments completely convincing, though people have different programming styles and I'm not saying they're completely UNconvincing, so I understand if people want to use poperties for these reasons. I want to know if there are any other reasons to make a normal public field into a property preemptively? Is there something else I'm missing?
Admin
FTFY
Admin
Admin
Look, it's quite obvious when using .Net.
A field is stored in the metadata as a Field and a property is a Property.
Changing a Field to a Property changes the metadata (which is part of the external interface of your class) thus potentially affecting consumers of your class.
Design properly and avoid any potential issues. Is it really that much harder to type
public string Name {get;set;};
than
private string _name;
???
Admin
For me I'd add another reason
Also, another consideration, which I don't think fits with the field that you defined, but if you need to have an event fired when something changes, you can do it with a field.
Admin
Another major issue is that you cannot use a public field for databinding (in .net anyway).
ie.
The above will compile but will fail at runtime when adding the databinding to numericUpDown2
Admin
Yeah, I like the Python way, too. Start off just making things attributes.
If you need a getter and/or setter, just define them as a property.
Works just as well as the getter/setter combo, looks just like an attribute.
I'm wondering how this is done in Perl? Just one way to do it, please, I'm sure there are more. ^_-
Admin
With Eclipse, you can choose to write your code so that you access public fields directly. A quick refactoring will then change every write to the field to a call to a new setter, every read from the field to a call to the getter.
Admin
I'll join the chorus of "properties can be life-savers" chanters. Properties aren't any real hassle (as most IDEs generate those getters and setters for us), and they can be easily changed when some moron up the management chain tells you "Why, it's OBVIOUS there has to be a check whether <insert silly logic here> . It is so logical that I didn't even bother to tell you back then. And it won't take long to fix because it is very simple, right?" Too bad your class is used everywhere by now.
And some whined that getters and setters take up some space. Why, are you so bothered that you'll hit 'page down' a few more times?
Admin
I have occasionally created public fields in a class, especially smaller ones that I only use as if they were C structs, but I always felt dirty doing so, as if the Great Programmer in the Sky was looking down on me and shaking his head in disapproval.
I feel its a good habit to get into though, since you never know when you could use some error checking, pre or post processing, or other sorts of limitations on a variable. If your IDE creates get/set's automatically, there isn't much in the way of wasted time.
Admin
The real WTF is that you guys are actually advocating using public fields over public accessor methods.
I've seen enough ugly code in my time to know to provide the encapsulation before everybody and their dog depends on the public interface I've provided (yeah - that contract I've promised to keep with the clients).
That being said, public fields and properties in your goofy language have the same syntax, so I suppose all you have to do is recompile everything that depends on you....