Tech Off Thread

20 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

Are Static Methods Evil?

Back to Forum: Tech Off
  • User profile image
    phreaks

    Some of my co-workers keep advising me to "just use a static method"

    I generally don't use them too often because they are tied to a type and not an instance which usually screws me up when thinking about how to define the base and derived structures.

    Are there any penalties or pitfalls to using static methods?

    Would something like this even make sense?

    This is a simple class of static data that an app calls all over the place, would it be better to make this a non-static method, if so why? (I have about 10 similar classes, the only difference is the data)

    I was thinking about refactoring it out to an interface, so that I could easily pass arounf the instances without worrying about the specific type, but then it would have to be derived from Dictionary<Object, Object> to be flexible. Arrrgh, I'm confusing myself more as I type.

    public class SomeData : Dictionary<String, String>
    {
    
        public static Dictionary<String, String> GetDictionary()
        {
            SomeData sd = new SomeData()
            {
                {"1", "Billy Bob Thorton"},
                {"2", "Bob Barker"},
                {"3", "Ben Bernanke"}
            };
            return sd;
        }
    
    }
    



    I also did some expirementing and just realized today, that Interfaces can't contain a static definition.
    Could someone also explain the reason for that?

  • User profile image
    lensman

    A static object is by definition a single instance occurrence.  That fact along is why interfaces cannot have them.  I have seen them referenced as "Singleton" in some circles.

    I personally feel static objects are evil.  They do have their uses however I find the idea of instances too promising to give it up easily.

  • User profile image
    longnightmo​on

    I'd say they're only evil if they cause you no end of grief.
    As in your example they're good for creating objects, like

    String[] s = System.IO.File.ReadAllLines("MyFile.txt");

    In my experience it’s usually more important that you get from point A to point B in a timely manner than it is how you get there. Just so long as it doesn't bite you in the end.

  • User profile image
    Ion Todirel

    all internal methods not using the this operator should be static

  • User profile image
    spivonious

    I think they're fine as long as the method/property is totally disconnected from an instance of that object.

    What you posted looks to be a factory class that produces Dictionary objects. I don't know why you're inheriting from the Dictionary object though.

  • User profile image
    magicalclick

    If you don't need member variables for that function, static function is fine. Something like Math.Power(x,y) should be static because there is no need for member variables.

    Leaving WM on 5/2018 if no apps, no dedicated billboards where I drive, no Store name.
    Last modified
  • User profile image
    Dr Herbie

    magicalclick said:

    If you don't need member variables for that function, static function is fine. Something like Math.Power(x,y) should be static because there is no need for member variables.

    If a method or function does not affect the state of an object, I would consider making it static.
    I would also consider moving it to a service class as opposed to a domain class, as if it doesn't affect the object's state why is it in the object?

    Herbie

  • User profile image
    Cupiditas

    Dr Herbie said:
    magicalclick said:
    *snip*
    If a method or function does not affect the state of an object, I would consider making it static.
    I would also consider moving it to a service class as opposed to a domain class, as if it doesn't affect the object's state why is it in the object?

    Herbie

    Because the domain class offers context and no unnecessary duplication of classes.

    This is how the .Net framework does it (especially XNA1).

    1This is for those pedantic people who are going to make a point of telling me that XNA isn't technically a part of the .Net framework. I hate you.

  • User profile image
    Sven Groot

    Static methods aren't evil. As to when you should use them, this flowchart I just made shows my thoughts on the matter:



    Wink

  • User profile image
    vesuvius

    They [static types] certainly have their uses. Think MessageBox.Show() in windows forms.

    C# is a static typed language, insofar as Main() being the starting point of the program.

    I use them in DataAccessLayers the most, where typically you don't need an instance.

    The new dynamic keyword in C#  4.0. is a static type


  • User profile image
    stevo_

    A static member certainly isn't evil or wrong, I think you may be infering that common problems suggest their wrong, such as static methods being less 'flexible', but thats the choice, not every method needs to be polymorphic.. additionally I think that static members will tend to highlight more so than instance members, problems with shared state and resource contention.. but this isn't a problem with static members, thats a problem with .. shared state and resource contention Wink.

  • User profile image
    Dr Herbie

    Cupiditas said:
    Dr Herbie said:
    *snip*

    Because the domain class offers context and no unnecessary duplication of classes.

    This is how the .Net framework does it (especially XNA1).

    1This is for those pedantic people who are going to make a point of telling me that XNA isn't technically a part of the .Net framework. I hate you.

    I guess it's more of a code smell, that a rule : if I see static methods that doesn't alter object status I immediately re-examine the design to see it it makes sense for it to be there.

    You're right that the domain class can give context and I think Sven's flowchart above hits the spot.

    Herbie


  • User profile image
    phreaks

    Wow. Thanks for all the excellent replies.

    Whoever said, "Not every method needs to be polymorphic" hit it on the head for me, that's where I tend to "over-think" a solution.

    I'm always trying to create the most flexible design, even when there really isn't a need; which wastes alot of time and energy.

    I'm going to print Sven's flowchart out and tape it to my cube Wink

  • User profile image
    evildictait​or

    Static methods are good - the only thing to watch for is static *variables*. If you're not careful with static data and making sure it's readonly you can seriously screw over any future prospect of making your program parallelisable, and you can introduce all sorts of wacky bugs later when someone uses your method. Static methods on the other hand are generally ok - after all, any instance method can be made static by passing the left-hand-side of the "." to the method and calling the parameter "this".


    The reason you can't have a static method on an interface is beacuse interfaces are a way of grouping common objects together, not common classes. To invoke a static method you need to know the class name that the static method is attached to, and if you have to know the name, then the interface static method doesn't add anything. If you need simmilar functionality you can always use delegates.

  • User profile image
    BitFlipper

    vesuvius said:
    They [static types] certainly have their uses. Think MessageBox.Show() in windows forms.

    C# is a static typed language, insofar as Main() being the starting point of the program.

    I use them in DataAccessLayers the most, where typically you don't need an instance.

    The new dynamic keyword in C#  4.0. is a static type


    I hate MessageBox.Show(). No matter whether I pass in a window as the parent (or owner?), it always puts the messagebox at the center of the screen, not at the center of my form.  I wish there was a way to tell it to do that, like you can do with your own dialogs.  Am I missing something maybe? Yes, I can create my own dialogs for every possible message I want to display, but that seems a bit heavy...

    [/rant]

  • User profile image
    Sven Groot

    BitFlipper said:
    vesuvius said:
    *snip*
    I hate MessageBox.Show(). No matter whether I pass in a window as the parent (or owner?), it always puts the messagebox at the center of the screen, not at the center of my form.  I wish there was a way to tell it to do that, like you can do with your own dialogs.  Am I missing something maybe? Yes, I can create my own dialogs for every possible message I want to display, but that seems a bit heavy...

    [/rant]
    That's not really a .Net thing though, that's how the underlying Win32 MessageBox function behaves. Fwiw, Vista's task dialog (which you can use in .Net with my dialogs library) can be centered to either the parent or the screen, but this dialog is only available on Vista and up so it doesn't help you for apps targetting XP.

  • User profile image
    figuerres

    evildictaitor said:
    Static methods are good - the only thing to watch for is static *variables*. If you're not careful with static data and making sure it's readonly you can seriously screw over any future prospect of making your program parallelisable, and you can introduce all sorts of wacky bugs later when someone uses your method. Static methods on the other hand are generally ok - after all, any instance method can be made static by passing the left-hand-side of the "." to the method and calling the parameter "this".

    The reason you can't have a static method on an interface is beacuse interfaces are a way of grouping common objects together, not common classes. To invoke a static method you need to know the class name that the static method is attached to, and if you have to know the name, then the interface static method doesn't add anything. If you need simmilar functionality you can always use delegates.
    "Static methods are good - the only thing to watch for is static *variables*. If you're not careful with static data and making sure it's readonly you can seriously screw over any future prospect of"

    YOW!!!  that recalls a bad nightmare / Past bug....

    I had a large class with several related classes that together do a task......  by accident I made like 3-4 variables static....
    3 months later we saw the bug in the database where some records would get the wrong data at times....
    on a carefull reveiw I saw the static items and saw my error.... not fun!

    this class is called like 10,000 times a day often dozens / hundreds of times in a few seconds.... random shared state !
    Sad  very very bad thing.... I really had a slice of "Humble Pie" on that one.




  • User profile image
    Charles

    What an awesome thread. Thank you!
    C

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.