Naming convention for accessor methods (get/set)

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Generic Usenet Account

    Naming convention for accessor methods (get/set)

    A lot has been said in this newsgroup regarding the "evil" set/get
    accessor methods. Arthur Riel, (of Vanguard Training), in his class,
    "Heuristis for O-O Analysis & Design", says that there is almost never
    an excuse for accessor methods. Personally, I do not go that far. I
    do feel that they serve a useful purpose (albeit in a limited manner).
    Personally I prefer dropping the "set" and "get" prefixes from the
    method names altogether. For example:

    class A
    {
    public:
    ...
    int xyz() { return _xyz; } // instead of get_xyz()
    void xyz(const int val) { _xyz = val; } // instead of get_xyz()
    ...

    protected:
    ...
    int _xyz;
    ...
    };


    This naming convention is also consistent with the IDL/C++ language
    binding, and I wanted to seek your opinion regarding this.

    Regards,
    KP Bhat

    [ See http://www.gotw.ca/resources/clcm.htm for info about ]
    [ comp.lang.c++.m oderated. First time posters: Do this! ]
  • Kevin Goodsell

    #2
    Re: Naming convention for accessor methods (get/set)

    Generic Usenet Account wrote:
    [color=blue]
    > A lot has been said in this newsgroup regarding the "evil" set/get
    > accessor methods. Arthur Riel, (of Vanguard Training), in his class,
    > "Heuristis for O-O Analysis & Design", says that there is almost never
    > an excuse for accessor methods. Personally, I do not go that far. I
    > do feel that they serve a useful purpose (albeit in a limited manner).
    > Personally I prefer dropping the "set" and "get" prefixes from the
    > method names altogether. For example:
    >
    > class A
    > {
    > public:
    > ...
    > int xyz() { return _xyz; } // instead of get_xyz()
    > void xyz(const int val) { _xyz = val; } // instead of get_xyz()
    > ...
    >
    > protected:
    > ...
    > int _xyz;
    > ...
    > };
    >
    >
    > This naming convention is also consistent with the IDL/C++ language
    > binding, and I wanted to seek your opinion regarding this.[/color]

    (Cross-post to comp.lang.c++.m oderated removed. Cross-posting to
    moderated groups slows down responses.)

    My opinion:

    I don't see a real problem with your naming scheme, but I wouldn't use
    it personally. Overloaded functions are generally used when multiple
    functions perform the same (or a similar) task using different
    arguments. In this case, the functions do rather different things, so I
    would prefer different names.

    Set/get member functions aren't inherently bad, but some beginners get
    the idea that they are a standard part of every class, which is
    completely wrong. Most classes shouldn't have a need for typical set and
    get functions (those that correspond to the actual data members in the
    class). The interface should be separate from the representation
    (obviously) so except in rather simple cases, you can't expect a
    well-designed interface to correspond to the members used to represent
    the class's state.

    One last thing, I would recommend not using names that begin with an
    underscore. It's OK in the context above, but there's a lot of cases
    where it's not. The easiest way to avoid problems is to get in the habit
    of never using identifiers (macros, variables, etc.) that begin with an
    underscore.

    -Kevin
    --
    My email address is valid, but changes periodically.
    To contact me please use the address from a recent posting.

    Comment

    • Gianni Mariani

      #3
      Re: Naming convention for accessor methods (get/set)

      Kevin Goodsell wrote:[color=blue]
      > Generic Usenet Account wrote:[/color]
      ....[color=blue]
      > (Cross-post to comp.lang.c++.m oderated removed. Cross-posting to
      > moderated groups slows down responses.)
      >
      > My opinion:
      >
      > I don't see a real problem with your naming scheme, but I wouldn't use
      > it personally. Overloaded functions are generally used when multiple
      > functions perform the same (or a similar) task using different
      > arguments. In this case, the functions do rather different things, so I
      > would prefer different names.
      >
      > Set/get member functions aren't inherently bad, but some beginners get
      > the idea that they are a standard part of every class, which is
      > completely wrong. Most classes shouldn't have a need for typical set and
      > get functions (those that correspond to the actual data members in the
      > class). The interface should be separate from the representation
      > (obviously) so except in rather simple cases, you can't expect a
      > well-designed interface to correspond to the members used to represent
      > the class's state.
      >
      > One last thing, I would recommend not using names that begin with an
      > underscore. It's OK in the context above, but there's a lot of cases
      > where it's not. The easiest way to avoid problems is to get in the habit
      > of never using identifiers (macros, variables, etc.) that begin with an
      > underscore.[/color]

      Opinion seconded.

      Comment

      • Samuel Krempp

        #4
        Re: Naming convention for accessor methods (get/set)

        le Friday 19 September 2003 13:08, usenet@sta.sams ung.com écrivit :
        [color=blue]
        > int xyz() { return _xyz; } // instead of get_xyz()
        > void xyz(const int val) { _xyz = val; } // instead of get_xyz()[/color]

        There is one small factual inconvienence I can think of.
        While you can do :

        vector<A> v;
        int x;
        for_each(v.begi n(), v.end(), bind2nd(mem_fun _ref(&A::set_xy z), x) );

        You need specific code to reach the overloaded 'xyz' membre function :

        void (A::* pmf)(const int) = &A::xyz;
        for_each(v.begi n(), v.end(), bind2nd(mem_fun _ref(pmf), x) );


        oh, and it's easier to search for 'set_xyz' in a file. (the overloaded one
        can be searched using a regexp like 'xyz([^)]*)' , it's not too complicated
        either)

        except for those details, I think it does'nt make much of a difference.

        --
        Samuel.Krempp
        cout << "@" << "crans." << (is_spam ? "trucs.en.trop. " : "" )
        << "ens-cachan.fr" << endl;


        [ See http://www.gotw.ca/resources/clcm.htm for info about ]
        [ comp.lang.c++.m oderated. First time posters: Do this! ]

        Comment

        • Le Chaud Lapin

          #5
          Re: Naming convention for accessor methods (get/set)

          Gianni Mariani <gi2nospam@mari ani.ws> wrote in message news:<bkfj8d$gm k@dispatch.conc entric.net>...[color=blue]
          > Kevin Goodsell wrote:[color=green]
          > > One last thing, I would recommend not using names that begin with an
          > > underscore. It's OK in the context above, but there's a lot of cases
          > > where it's not. The easiest way to avoid problems is to get in the habit
          > > of never using identifiers (macros, variables, etc.) that begin with an
          > > underscore.[/color]
          >
          > Opinion seconded.[/color]

          How about ending with underscore?

          -Chaud Lapin-

          Comment

          • Kevin Goodsell

            #6
            Re: Naming convention for accessor methods (get/set)

            Le Chaud Lapin wrote:[color=blue]
            > Gianni Mariani <gi2nospam@mari ani.ws> wrote in message news:<bkfj8d$gm k@dispatch.conc entric.net>...
            >[color=green]
            >>Kevin Goodsell wrote:
            >>[color=darkred]
            >>>One last thing, I would recommend not using names that begin with an
            >>>underscore . It's OK in the context above, but there's a lot of cases
            >>>where it's not. The easiest way to avoid problems is to get in the habit
            >>>of never using identifiers (macros, variables, etc.) that begin with an
            >>>underscore .[/color]
            >>
            >>Opinion seconded.[/color]
            >
            >
            > How about ending with underscore?[/color]

            That's fine as long as it's not immediately preceded by another
            underscore. Identifiers containing a sequence of two underscores are
            also reserved (though I don't know what for off the top of my head). So
            this:

            identifier_

            is OK. These are not:

            _identifier (well, it's OK in some places)
            _Identifier (pretty much never OK)
            _IDENTIFIER (also never OK)
            identifier__
            __identifier
            foo__bar

            -Kevin
            --
            My email address is valid, but changes periodically.
            To contact me please use the address from a recent posting.

            Comment

            • Julián Albo

              #7
              Re: Naming convention for accessor methods (get/set)

              Generic Usenet Account escribió:
              [color=blue]
              > Personally I prefer dropping the "set" and "get" prefixes from the
              > method names altogether. For example:[/color]

              (snip)
              [color=blue]
              > This naming convention is also consistent with the IDL/C++ language
              > binding, and I wanted to seek your opinion regarding this.[/color]

              In Spain we say: "aunque la mona se vista de seda, mona se queda". "A
              monkey is a monkey even if dressed in silk" can be a translation. It is
              the same thing wheter you use or not set and get prefixes. Personal
              preference, as you say.

              Regards.

              [ See http://www.gotw.ca/resources/clcm.htm for info about ]
              [ comp.lang.c++.m oderated. First time posters: Do this! ]

              Comment

              • Marcin Vorbrodt

                #8
                Re: Naming convention for accessor methods (get/set)

                How about:

                class A {
                public:
                int& EVIL() { return _evil; }
                const int& EVIL() const { return _evil; }
                };

                This really is a horrible design... because you are exposing the underlying
                implementation of your class. Which implies that if the implementation
                changes, then the interface may need to be changed as well. That is more
                evil than Sadam, Bin Laden, Stalin and Hitler put together. If you need to
                be able to create setters and getters, why not just make the variable
                public. If you need to have some other unrelated class access
                private/protected elements of some other class, use friends instead. At
                least you will not be breaking encapsulation.

                GRRR

                Martin


                "Generic Usenet Account" <usenet@sta.sam sung.com> wrote in message
                news:90e5135.03 09181203.cb6bee 0@posting.googl e.com...[color=blue]
                > A lot has been said in this newsgroup regarding the "evil" set/get
                > accessor methods. Arthur Riel, (of Vanguard Training), in his class,
                > "Heuristis for O-O Analysis & Design", says that there is almost never
                > an excuse for accessor methods. Personally, I do not go that far. I
                > do feel that they serve a useful purpose (albeit in a limited manner).
                > Personally I prefer dropping the "set" and "get" prefixes from the
                > method names altogether. For example:
                >
                > class A
                > {
                > public:
                > ...
                > int xyz() { return _xyz; } // instead of get_xyz()
                > void xyz(const int val) { _xyz = val; } // instead of get_xyz()
                > ...
                >
                > protected:
                > ...
                > int _xyz;
                > ...
                > };
                >
                >
                > This naming convention is also consistent with the IDL/C++ language
                > binding, and I wanted to seek your opinion regarding this.[/color]



                [ See http://www.gotw.ca/resources/clcm.htm for info about ]
                [ comp.lang.c++.m oderated. First time posters: Do this! ]

                Comment

                • Mike Wahler

                  #9
                  Re: Naming convention for accessor methods (get/set)


                  "Generic Usenet Account" <usenet@sta.sam sung.com> wrote in message
                  news:90e5135.03 09181203.cb6bee 0@posting.googl e.com...[color=blue]
                  > A lot has been said in this newsgroup regarding the "evil" set/get
                  > accessor methods. Arthur Riel, (of Vanguard Training), in his class,
                  > "Heuristis for O-O Analysis & Design", says that there is almost never
                  > an excuse for accessor methods. Personally, I do not go that far. I
                  > do feel that they serve a useful purpose (albeit in a limited manner).
                  > Personally I prefer dropping the "set" and "get" prefixes from the
                  > method names altogether. For example:
                  >
                  > class A
                  > {
                  > public:
                  > ...
                  > int xyz() { return _xyz; } // instead of get_xyz()
                  > void xyz(const int val) { _xyz = val; } // instead of get_xyz()
                  > ...
                  >
                  > protected:
                  > ...
                  > int _xyz;
                  > ...
                  > };
                  >
                  >
                  > This naming convention is also consistent with the IDL/C++ language
                  > binding, and I wanted to seek your opinion regarding this.[/color]

                  I also prefer to overload a single meaningful name for this.

                  This is typically (but not always) feasible since one usually
                  takes an argument and the other does not. This form has worked
                  well for me so far.


                  -Mike



                  [ See http://www.gotw.ca/resources/clcm.htm for info about ]
                  [ comp.lang.c++.m oderated. First time posters: Do this! ]

                  Comment

                  • apm

                    #10
                    Re: Naming convention for accessor methods (get/set)

                    usenet@sta.sams ung.com (Generic Usenet Account) wrote in message news:<90e5135.0 309181203.cb6be e0@posting.goog le.com>...[color=blue]
                    > A lot has been said in this newsgroup regarding the "evil" set/get
                    > accessor methods. Arthur Riel, (of Vanguard Training), in his class,
                    > "Heuristis for O-O Analysis & Design", says that there is almost never
                    > an excuse for accessor methods. Personally, I do not go that far. I
                    > do feel that they serve a useful purpose (albeit in a limited manner).
                    > Personally I prefer dropp[/color]

                    So do I. Here's why:

                    The Uniform Access Principle espoused by Betrand Meyer states that all
                    services offerd by a module should be available through a uniform
                    notation which does not betray whether they are implemented through
                    storage or through computation. Get get/set convention violates this.

                    -Andrew Marlow

                    [ See http://www.gotw.ca/resources/clcm.htm for info about ]
                    [ comp.lang.c++.m oderated. First time posters: Do this! ]

                    Comment

                    • Francis Glassborow

                      #11
                      Re: Naming convention for accessor methods (get/set)

                      In article <bkfe5j$mfp$1@u ni00nw.unity.nc su.edu>, Marcin Vorbrodt
                      <mvorbro@eos.nc su.edu> writes[color=blue]
                      >How about:
                      >
                      >class A {
                      > public:
                      > int& EVIL() { return _evil; }
                      > const int& EVIL() const { return _evil; }
                      >};
                      >
                      >This really is a horrible design... because you are exposing the underlying
                      >implementati on of your class. Which implies that if the implementation
                      >changes, then the interface may need to be changed as well. That is more
                      >evil than Sadam, Bin Laden, Stalin and Hitler put together. If you need to
                      >be able to create setters and getters, why not just make the variable
                      >public. If you need to have some other unrelated class access
                      >private/protected elements of some other class, use friends instead. At
                      >least you will not be breaking encapsulation.[/color]

                      But you snuck in return by reference which is a quite different issue.
                      Consider the following public interface for a class:

                      class point2d {
                      public:
                      // constructor:
                      explicit point2d(double xval=0, double yval=0);
                      // read access functions
                      double x()const;
                      double y()const;
                      double modulus()const;
                      double argument()const ;
                      // write access functions
                      point2d & x(double xval);
                      point2d & y(double yval);
                      point2d & modulus(double mod);
                      point2d & argument(double degrees);
                      private:
                      // data choice irrelevant

                      };
                      Note that the user has no need to know how the data locating a point on
                      a plane is organised. However there is a great deal of benefit from
                      being able to select using Cartesian or Polar co-ordinates according to
                      what you are doing.


                      --
                      Francis Glassborow ACCU
                      64 Southfield Rd
                      Oxford OX4 1PA +44(0)1865 246490
                      All opinions are mine and do not represent those of any organisation


                      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
                      [ comp.lang.c++.m oderated. First time posters: Do this! ]

                      Comment

                      • WW

                        #12
                        Re: Naming convention for accessor methods (get/set)

                        apm wrote:[color=blue]
                        > usenet@sta.sams ung.com (Generic Usenet Account) wrote in message
                        > news:<90e5135.0 309181203.cb6be e0@posting.goog le.com>...[color=green]
                        >> A lot has been said in this newsgroup regarding the "evil" set/get
                        >> accessor methods. Arthur Riel, (of Vanguard Training), in his class,
                        >> "Heuristis for O-O Analysis & Design", says that there is almost
                        >> never
                        >> an excuse for accessor methods. Personally, I do not go that far. I
                        >> do feel that they serve a useful purpose (albeit in a limited
                        >> manner). Personally I prefer dropp[/color]
                        >
                        > So do I. Here's why:
                        >
                        > The Uniform Access Principle espoused by Betrand Meyer states that all
                        > services offerd by a module should be available through a uniform
                        > notation which does not betray whether they are implemented through
                        > storage or through computation. Get get/set convention violates this.[/color]

                        Without going to quoting authority opinions and theories I would rather
                        tackle the problem from a T word point of view. A class (be it any class)
                        represents a concept in a problem domain. if that concept suport the
                        existence of things called getXxx setXxx then you should have them. If not,
                        you should not.

                        Furthermore a class is either just a representation of some simple storage
                        facility (in which case getters and setter might be appropriate) or it is
                        not. IMHO it is very very rare in real life design when you need such a
                        class. And if you feel you do, you really have to defend the idea, because
                        unless that class provides an adapter or facade to an exteranl storage
                        system they seem to have absolutely no function whatsoever.

                        Just let me give one example of a place where get/set might be appropriate
                        (as a name):

                        struct Radio {
                        xxx setVolume()...
                        xxx getVolume()...
                        private:
                        ....
                        };

                        --
                        WW aka Attila



                        [ See http://www.gotw.ca/resources/clcm.htm for info about ]
                        [ comp.lang.c++.m oderated. First time posters: Do this! ]

                        Comment

                        • Jerry Coffin

                          #13
                          Re: Naming convention for accessor methods (get/set)

                          In article <0uPab.10501$BS 5.8503@newsread 4.news.pas.eart hlink.net>,
                          usenet1.spamfre e.fusion@neverb ox.com says...

                          [ ... ]
                          [color=blue]
                          > That's fine as long as it's not immediately preceded by another
                          > underscore. Identifiers containing a sequence of two underscores are
                          > also reserved (though I don't know what for off the top of my head).[/color]

                          Just in case you happen to really care: it's reserved because some
                          compilers used that as the separator between the name and the name
                          mangling -- this was (and may still be) particularly widely used among
                          compilers that produced C as output, since the result had to be a legal
                          C identifier.

                          --
                          Later,
                          Jerry.

                          The universe is a figment of its own imagination.

                          Comment

                          • Ben Liddicott

                            #14
                            Re: Naming convention for accessor methods (get/set)

                            "Generic Usenet Account" <usenet@sta.sam sung.com> wrote in message news:90e5135.03 09181203.cb6bee 0@posting.googl e.com...[color=blue]
                            > A lot has been said in this newsgroup regarding the "evil" set/get
                            > accessor methods. Arthur Riel, (of Vanguard Training), in his class,
                            > "Heuristis for O-O Analysis & Design", says that there is almost never
                            > an excuse for accessor methods.[/color]

                            Accessor methods can become neccessary when you have several properties of a class which are really different views/transformations of the same underlying property. An example already given was polar vs. cartesian coordinates.

                            Here's another:

                            class P{
                            public:
                            // directory
                            std::string GetDirectory();
                            void PutDirectory(co nst std::string& newDir);
                            // filename = basename.extens ion
                            std::string GetFileName();
                            void PutFileName(con st std::string& newFileName);
                            // full path
                            std::string GetFullPath();
                            void PutFullPath(con st std::string& newPath);
                            // now add BaseName and Extension.
                            };

                            // example:
                            // this/is/the/directory/basename.extens ion


                            It may perfect sense to Get/Put any of these five properties independently; depending on what the program intends to do with the information. If it wants to create a sibling file, it can use GetDirectory. If it wants to name a known sibling file according to some convention, it might want to set the extension only. If it wants to name a companion file in a different folder, to set the directory, and so forth.
                            [color=blue]
                            > Personally I prefer dropping the "set" and "get" prefixes from the
                            > method names altogether. For example:[/color]

                            (deleted)
                            [color=blue]
                            > This naming convention is also consistent with the IDL/C++ language
                            > binding, and I wanted to seek your opinion regarding this.[/color]

                            You are talking about the CORBA IDL C++ language binding of course... as opposed to the many other IDL's, such as DCE/RPC, MIDL, MACH, Sun RPC and so forth.

                            It is time to invoke the concept of Least Surprise. If the code is intended or likely to be mixed with CORBA objects and calls, this would be a good convention to use. If it is intended or likely to be used together with with some other convention, you may wish to use that convention.

                            Personally I prefer Get/Put as prefixes, because one day you will need an indexed property.

                            class A{
                            public:
                            std::string GetValue(const std::string& name);
                            void PutValue(const std::string& name, const std::string& value);
                            };

                            Some times it is appropriate to use more than one convention:


                            class B{
                            public:
                            long get_Value(const std::string& name, std::string& value) throw();
                            long put_Value(const std::string& name, const std::string& value) throw();
                            std::string GetValue(const std::string& name) throw(MyExcepti on){
                            std::string tmp; long lErrCode = get_Value(name, tmp);
                            if(lErrCode)thr ow MyException(lEr rCode);
                            return tmp;
                            }
                            void PutValue(const std::string& name, const std::string& value) throw(MyExcepti on){
                            long lErrCode = put_Value(name, value);
                            if(lErrCode)thr ow MyException(lEr rCode);
                            }
                            };


                            This gives more flexibility to the user of the class. The verbosity and duplication involved mean that it is only really appropriate for very small or very stable libraries which are frequently used and thoroughly tested, or of course, for machine-generated code, for example from some sort of IDL.


                            --
                            Cheers,
                            Ben Liddicott


                            [ See http://www.gotw.ca/resources/clcm.htm for info about ]
                            [ comp.lang.c++.m oderated. First time posters: Do this! ]

                            Comment

                            • Ed Avis

                              #15
                              Re: Naming convention for accessor methods (get/set)

                              apm35@student.o pen.ac.uk (apm) writes:
                              [color=blue]
                              >The Uniform Access Principle espoused by Betrand Meyer states that
                              >all services offerd by a module should be available through a uniform
                              >notation which does not betray whether they are implemented through
                              >storage or through computation. Get get/set convention violates this.[/color]

                              Could you explain what you mean - it seems that wrapping everything in
                              get_x() and set_x() would indeed hide what was stored and what was
                              computed (though it's not clear what it means to call set_x() if x is
                              a computed value).

                              --
                              Ed Avis <ed@membled.com >

                              [ See http://www.gotw.ca/resources/clcm.htm for info about ]
                              [ comp.lang.c++.m oderated. First time posters: Do this! ]

                              Comment

                              Working...