Static methods ?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • chandu

    Static methods ?

    hello,

    i want to know usage of static methods in a class.
    is it advantageous or disadvantage to use more static methods in a class.

    thank u


  • Bruce Wood

    #2
    Re: Static methods ?

    chandu wrote:
    hello,
    >
    i want to know usage of static methods in a class.
    is it advantageous or disadvantage to use more static methods in a class.
    Static methods are useful when all of the information needed in order
    to perform a calculation (logic) can be passed as arguments to the
    method. So, the method does not need any of the object's state (fields)
    in order to do its work.

    I prefer static methods when I have some business logic / calculation
    that needs only a few pieces of information (parameters), because when
    I see the keyword "static" I know that I don't have to read the method
    to see what bits of the object's state it uses (or modifies).
    Everything is in the parameter list.

    (Of course, a static method can make use of static state, but then IMHO
    a class with more than a few items of static state is starting to look
    more like something that should be a singleton.)

    That said, programming with lots of static methods and avoiding
    instance methods smacks of structured programming... someone who hasn't
    quite graduated into the object-oriented world. Many times what are
    written as static methods really belong as instance methods on one of
    the parameters' types. For example, a static method that takes as one
    of its parameters a class that you wrote... you should consider the
    possibility of making it an instance method of that class and see if
    that makes more sense. It's nicer to call myString.Trim() rather than
    String.Trim(myS tring), even though both implementations are possible. I
    usually ask myself, "Is this static method really an operation on some
    object?" Sometimes the answer is yes, sometimes it's no.

    Like any other tool, static methods have their uses. Don't be afraid of
    them, but then don't overuse them, either.

    Comment

    • Michael C

      #3
      Re: Static methods ?

      "chandu" <nareshv_chandr a@hotmail.comwr ote in message
      news:uF65rQz8GH A.3384@TK2MSFTN GP05.phx.gbl...
      hello,
      >
      i want to know usage of static methods in a class.
      is it advantageous or disadvantage to use more static methods in a class.
      Depends on the class, some classes have only static methods while others
      have none. Like any feature it's advantageous to use it appropriately.
      >
      thank u
      >

      Comment

      • Champika Nirosh

        #4
        Re: Static methods ?

        Static method cost performance, but can be thread safe.
        Static method preserve its previous state

        I would use static method, when ...
        I need to issolately allow other modules, systems to access a method without
        creating a instance of a class.
        I need to make a mehtod that store its previuos status
        When I deal with multithreaded application
        When Impliementing Singleton and factory pattern
        When I need to share many public methods accross multiple systems where each
        system may or may not use all the method of the class

        Nirosh.



        "chandu" <nareshv_chandr a@hotmail.comwr ote in message
        news:uF65rQz8GH A.3384@TK2MSFTN GP05.phx.gbl...
        hello,
        >
        i want to know usage of static methods in a class.
        is it advantageous or disadvantage to use more static methods in a class.
        >
        thank u
        >

        Comment

        • KH

          #5
          Re: Static methods ?

          Static method cost performance, but can be thread safe.
          Static method preserve its previous state
          ??????????????? ??????????????? ???

          How are static methods less performant than instance methods? They're the
          same, not just in performance, but literally - instance methods are just
          static methods with a pointer to the instance passed in behind the scenes.
          And all methods can be thread-safe -- see the MethodImplAttri bute attribute.

          Use static methods when you don't need to maintain state between calls --
          i.e. the method doesn't use any of the class's fields to do its work. The
          Math class is a good example.


          "Champika Nirosh" wrote:
          Static method cost performance, but can be thread safe.
          Static method preserve its previous state
          >
          I would use static method, when ...
          I need to issolately allow other modules, systems to access a method without
          creating a instance of a class.
          I need to make a mehtod that store its previuos status
          When I deal with multithreaded application
          When Impliementing Singleton and factory pattern
          When I need to share many public methods accross multiple systems where each
          system may or may not use all the method of the class
          >
          Nirosh.
          >
          >
          >
          "chandu" <nareshv_chandr a@hotmail.comwr ote in message
          news:uF65rQz8GH A.3384@TK2MSFTN GP05.phx.gbl...
          hello,

          i want to know usage of static methods in a class.
          is it advantageous or disadvantage to use more static methods in a class.

          thank u
          >
          >
          >

          Comment

          • Bruce Wood

            #6
            Re: Static methods ?

            Champika Nirosh wrote:
            Static method cost performance, but can be thread safe.
            Static method preserve its previous state
            Another poster has already pointed out that static methods have no
            performance benefits or drawbacks over instance methods. In fact,
            static methods can be _more_ performant than instance methods if the
            instance methods in question are virtual / overridden. Static methods
            never required a v-table lookup (sorry for the C++ terminology... you
            all know what I mean). Of course, if the instance method is not virtual
            / overridden then there is no difference at all.

            However, the idea that static methods preserve their previous state is
            not true at all.

            Any method, static or instance, can "preserve its previous state" if it
            wants to. Instance methods can alter the state (fields) of the object
            instance on which they're operating. Static methods can alter static
            state (static fields). The latter, however, is easily overused and
            should be employed with caution. That is to say, if you have a static
            class with lots of static fields (static state) then you're probably
            overusing the idiom and should be looking at an instance idiom instead.

            Most static methods do _not_, in fact, store static state from one call
            to the next. They are, instead, pure calculation on only the provided
            arguments. That is the way in which I find them most useful, personally.

            Comment

            • Champika Nirosh

              #7
              Re: Static methods ?

              See my comments

              I just wrongly directed myself thinking that he is asking about a more
              general question about Static modifier

              "Bruce Wood" <brucewood@cana da.comwrote in message
              news:1161235709 .114538.61030@k 70g2000cwa.goog legroups.com...
              Champika Nirosh wrote:
              >Static method cost performance, but can be thread safe.
              >Static method preserve its previous state
              >
              Another poster has already pointed out that static methods have no
              performance benefits or drawbacks over instance methods. In fact,
              static methods can be _more_ performant than instance methods if the
              instance methods in question are virtual / overridden. Static methods
              never required a v-table lookup (sorry for the C++ terminology... you
              all know what I mean). Of course, if the instance method is not virtual
              / overridden then there is no difference at all.
              Yes, correct but with the exception that you only have local variable in
              your static method.. if you have a static constructor to initialize some
              public fields and properties you will see a significant performance drop..
              However, the idea that static methods preserve their previous state is
              not true at all.
              >
              Any method, static or instance, can "preserve its previous state" if it
              wants to. Instance methods can alter the state (fields) of the object
              instance on which they're operating. Static methods can alter static
              state (static fields). The latter, however, is easily overused and
              should be employed with caution. That is to say, if you have a static
              class with lots of static fields (static state) then you're probably
              overusing the idiom and should be looking at an instance idiom instead.
              >
              Most static methods do _not_, in fact, store static state from one call
              to the next. They are, instead, pure calculation on only the provided
              arguments. That is the way in which I find them most useful, personally.
              >
              I was still answering again by thinking the question in general form

              What I said was ...
              Form C-Sharp Spec

              6 A static field identifies exactly one storage location. 7 No matter how
              many instances of a class are created, there is only ever one copy of a
              static field.




              Comment

              • Bruce Wood

                #8
                Re: Static methods ?


                Champika Nirosh wrote:
                >
                "Bruce Wood" <brucewood@cana da.comwrote in message
                news:1161235709 .114538.61030@k 70g2000cwa.goog legroups.com...
                Champika Nirosh wrote:
                Static method cost performance, but can be thread safe.
                Static method preserve its previous state
                Another poster has already pointed out that static methods have no
                performance benefits or drawbacks over instance methods. In fact,
                static methods can be _more_ performant than instance methods if the
                instance methods in question are virtual / overridden. Static methods
                never required a v-table lookup (sorry for the C++ terminology... you
                all know what I mean). Of course, if the instance method is not virtual
                / overridden then there is no difference at all.
                >
                Yes, correct but with the exception that you only have local variable in
                your static method.. if you have a static constructor to initialize some
                public fields and properties you will see a significant performance drop..
                Not to beat a dead horse, but... what gives you the idea that a static
                constructor will cause a "significan t performance drop"? Any given
                static constructor runs once and only once per AppDomain. Unless your
                static constructor is doing some hideous amount of work, or doing
                something terribly wrong-headed like going after database data--neither
                of which are performance problems in any way uniquely related to static
                constructors--I have no idea what you mean by this.

                Perhaps I misunderstand what you're trying to say, but to my
                understanding the statement, "...if you have a static constructor to
                initialize some... fields and properties you will see a significant
                performance drop" is simply wrong.

                Comment

                • Jon Skeet [C# MVP]

                  #9
                  Re: Static methods ?

                  Bruce Wood <brucewood@cana da.comwrote:
                  Yes, correct but with the exception that you only have local variable in
                  your static method.. if you have a static constructor to initialize some
                  public fields and properties you will see a significant performance drop..
                  >
                  Not to beat a dead horse, but... what gives you the idea that a static
                  constructor will cause a "significan t performance drop"? Any given
                  static constructor runs once and only once per AppDomain. Unless your
                  static constructor is doing some hideous amount of work, or doing
                  something terribly wrong-headed like going after database data--neither
                  of which are performance problems in any way uniquely related to static
                  constructors--I have no idea what you mean by this.
                  >
                  Perhaps I misunderstand what you're trying to say, but to my
                  understanding the statement, "...if you have a static constructor to
                  initialize some... fields and properties you will see a significant
                  performance drop" is simply wrong.
                  Not to actually agree with Champika's point, but there *is* a
                  performance cost involved with having a static constructor. There are
                  stricter guarantees about when a static constructor can be called than
                  just the static initializers in a class without a static constructor,
                  so the JIT isn't able to make as many optimisations. I have yet to see
                  a case where it will really make a significant performance difference,
                  but there *is* a slight one.

                  --
                  Jon Skeet - <skeet@pobox.co m>
                  http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
                  If replying to the group, please do not mail me too

                  Comment

                  • PS

                    #10
                    Re: Static methods ?


                    "chandu" <nareshv_chandr a@hotmail.comwr ote in message
                    news:uF65rQz8GH A.3384@TK2MSFTN GP05.phx.gbl...
                    hello,
                    >
                    i want to know usage of static methods in a class.
                    is it advantageous or disadvantage to use more static methods in a class.
                    Some comments:

                    1. Some people like to have the object creation code as part of the object.
                    E.g. Employee e = Employee.NewMan ager("Jim Smith"). The NewManager method
                    needs to be static.

                    2. Static methods can be easier to unit test as it does not require you to
                    instansiate the class to access the method. As a side note the Extract
                    Method refactoring in VS2005 will favor making the extracted method static
                    if it can.

                    3. I use static methods for utility methods that are accessed by many
                    classes. Even if a method can be static within a class, if it only makes
                    sense for that class to use the static method then I favor using an instance
                    method over the static method.

                    PS

                    Comment

                    • Jeff Louie

                      #11
                      Re: Static methods ?

                      Also the non-object oriented forms

                      clone(x)
                      equal(x,y)

                      is prefered over the "object oriented"

                      x.twin
                      x.is_equal(y)

                      for void/null

                      Regards,
                      Jeff

                      *** Sent via Developersdex http://www.developersdex.com ***

                      Comment

                      • Michael C

                        #12
                        Re: Static methods ?

                        "PS" <ecneserpegats@ hotmail.comwrot e in message
                        news:eO5Rd498GH A.788@TK2MSFTNG P05.phx.gbl...
                        1. Some people like to have the object creation code as part of the
                        object. E.g. Employee e = Employee.NewMan ager("Jim Smith"). The NewManager
                        method needs to be static.
                        This can be useful if 2 methods are needed with the same params, eg
                        NewManager(stri ng Name, string Department) or NewManager(stri ng FirstName,
                        string Surname)

                        Michael


                        Comment

                        • Truong Hong Thi

                          #13
                          Re: Static methods ?


                          Hi Chandu,

                          Static methods are most suitable for utility methods, like that of
                          Math or Marshal class. All that the method needs are passed as
                          parameters, and no need to worry about static states/constructor nor
                          threadsafe (making static methods threadsafe is recommended, but don't
                          need to do it if it is not going to be called by many threads at the
                          same time). Static methods are not object-oriented, but they are handy
                          in this case. Try avoid class name like Utililies or Utils if you have
                          many methods; group related methods in a properly named class.

                          However, most programs will need some piece of static data to share
                          between objects or just to cache because the cost of initialization is
                          high. I often find myself define classes like App or GlobalContext and
                          store cached/shared objects there. Heard that Dependency Injection
                          container does a good job on this.

                          Generally, if one class derives directly from Object, and not meant to
                          be inherited by other class, I find no advantage it should contains
                          instance rather than static methods (except to avoid long parameter
                          list).

                          Thi

                          chandu wrote:
                          hello,
                          >
                          i want to know usage of static methods in a class.
                          is it advantageous or disadvantage to use more static methods in a class.
                          >
                          thank u

                          Comment

                          Working...