• (cs)

    if(MyComment != null){ return MyComment.Split('|'); } else { Response.Redirect("ForgotToIncludeComment.aspx"); return null; }

    Ooo and First!

  • (cs)

    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.

  • Shambo (unregistered) in reply to fusspawn

    A good code based WTF that made me laugh... ahh.. just like the good old days.

  • (cs) in reply to TGV

    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.

  • (cs) in reply to fusspawn

    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!

  • (cs) in reply to robbak

    I Figured that would be the case, But it never hurts to ask for help and all that stuff.

    Thanks Robbak :)

  • Anonymous (unregistered)

    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..

  • Warren (unregistered)

    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?

  • Delmania (unregistered) in reply to fusspawn
    fusspawn:
    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.

    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.

  • (cs)

    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.

  • duis (unregistered) in reply to Warren
    Warren:
    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?

    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

  • AB (unregistered) in reply to Delmania

    It's considered bad practice to use the inline keyword often.

  • Matthew Watson (unregistered)

    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...

  • Anon (unregistered)

    Yeah, TRWTF is the original poster not having a good answer. Sounds like a good interview question.

  • Me (unregistered) in reply to TGV

    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.

  • Don't get it (unregistered)

    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.

  • Misha (unregistered) in reply to Matthew Watson
    Matthew Watson:
    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...

    Watch?

  • John (unregistered)

    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:

    @interface Person : NSObject {
    	NSString *personName;
    	float expectedRaise;
    }
    @property (readwrite, copy) NSString *personName;
    @property (readwrite) float expectedRaise;
    @end
    
    @implementation Person
    @synthesize personName;
    @synthesize expectedRaise;
    
  • Gary Hall (unregistered)

    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.

  • Michael (unregistered) in reply to Don't get it
    by Don't get it:
    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.
    Why can't you make them properties later, when you find out there's a need to count accesses or whatever? What advantage is there to writing them as properties ahead of time?
  • Jason (unregistered)

    Ahh I see the WTF, he's using Request.Redirect rather than Server.Transfer...

  • (cs) in reply to Don't get it
    Don't get it:
    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.

    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.

  • Patrick (unregistered) in reply to Michael

    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.

  • (cs) in reply to fusspawn
    fusspawn:
    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.

    There isn't a performance hit if the getters / setters are inlined.

  • (cs) in reply to Michael
    Michael:
    by Don't get it:
    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.
    Why can't you make them properties later, when you find out there's a need to count accesses or whatever? What advantage is there to writing them as properties ahead of time?
    You'd be 100% correct if the only change would ever be adding a intChangeCount++; to the setter.

    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 :-)

  • SBaynham (unregistered) in reply to Michael

    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".

  • Jorge (unregistered) in reply to Delmania

    "removes the context switching. "

    you are doing multi threaded getters and setters?????

    WTF????

  • BlindedByTheCode (unregistered)

    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.

  • Michael (unregistered) in reply to SBaynham

    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?

  • Drew (unregistered)

    Try doing Lazy Loading without getters. :D

  • Alan (unregistered)

    prop[TAB][TAB]

    Code snippets are awesome.

  • Bills Bitch (unregistered) in reply to Misha
    Misha:
    Matthew Watson:
    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...
    Watch?
    Ooh, you must have one of those real computer thingamajiggies that I'm proud to say I can't learn. We're all still using Micro$haft.

    3.. 2.. 1.. fanboi replies that M$ has "watch" too!

    Yeah, stole it like everything else.

  • Jon (unregistered) in reply to Michael
    Michael:
    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?
    Nooo..

    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...):

    public class Person
    {
    ...
        public decimal Salary
        {
            get { return _salary; }
            set
            {
                if (value > 100000)
                    throw new FatCatException(value);
                _salary = value;
            }
        }
    ....
    }
    

    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.

  • (cs)

    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.

  • NeoMojo (unregistered) in reply to Jorge
    Jorge:
    you are doing multi threaded getters and setters?!
    mmmmmmmm Sounds enterprisey!
  • Anonymous Coward (unregistered) in reply to Michael

    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.

  • ashmud (unregistered) in reply to Jason
    Jason:
    Ahh I see the WTF, he's using Request.Redirect rather than Server.Transfer...
    Unless it's used in an async postback on an AJAX page.
  • Matthew Watson (unregistered) in reply to Misha
    Misha:
    Matthew Watson:
    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...

    Watch?

    Won't work in C#.

  • Tobias Brox (unregistered)

    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 :-)

  • Michael (unregistered) in reply to Jon

    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:

    1. Naming conventions are sometimes different for properties and public fields, so you don't want to go changing them later.

    2. 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?

  • Anon (unregistered) in reply to Jon
    Jon:
    public class Person
    {
    ...
        public decimal Salary
        {
            get { return _salary; }
            set
            {
                if (value > 100000 && !AIGExecutive)
                    throw new FatCatException(value);
                _salary = value;
            }
        }
    ....
    }
    

    FTFY

  • Michael (unregistered) in reply to Tobias Brox
    Tobias Brox:
    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.

    A post after my own heart, and python is my preferred language as well. I wonder why I never meet anyone else who argues like this though? I guess I'm working in the wrong place. I'm still interested to see any responses to my other post/question though.

  • CaptainObvious (unregistered) in reply to Michael
    Michael:
    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:
    1. Naming conventions are sometimes different for properties and public fields, so you don't want to go changing them later.

    2. 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?

    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;

    ???

  • Anon (unregistered) in reply to Michael
    Michael:
    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:
    1. Naming conventions are sometimes different for properties and public fields, so you don't want to go changing them later.

    2. 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?

    For me I'd add another reason

    1. WPF (and also probably other frameworks) will only bind to properties, not fields (I think)

    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.

  • John (unregistered) in reply to Anonymous Coward
    Anonymous Coward:
    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.

    Another major issue is that you cannot use a public field for databinding (in .net anyway).

    ie.

    public class Foo {
      private int i;
      public int J;
    
      public int I {
        get { return i; }
        set { i = value; }
      }
    }
    
    private void Bar() {
      BindingList<Foo> foo = new BindingList<Foo>();
      dataGridView1.DataSource = foo;
      numericUpDown1.DataBindings.Add("Value", foo, "I");
      numericUpDown2.DataBindings.Add("Value", foo, "J");
    }
    

    The above will compile but will fail at runtime when adding the databinding to numericUpDown2

  • Mike D. (unregistered) in reply to Tobias Brox

    Yeah, I like the Python way, too. Start off just making things attributes.

    class Parrot(object):
      def __init__(self):
        self.alive = True
    

    If you need a getter and/or setter, just define them as a property.

    class Parrot(object):
      def __init__(self):
        self.alive = True
      def _GetAlive(self): return self.alive
      def _SetAlive(self, stillAlive):
        if not stillAlive:
          print "This parrot has expired!"
        self.alive = stillAlive
      alive = property(_GetAlive, _SetAlive, None, "Is the parrot alive?")
    

    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. ^_-

  • Lamah (unregistered)

    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.

  • (cs)

    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?

  • (cs)

    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.

  • Farleigh (unregistered)

    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....

Leave a comment on “Try Doing That with a Field”

Log In or post as a guest

Replying to comment #:

« Return to Article