Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I am very curious as to thoughts and industry best practices regarding static me

ID: 644325 • Letter: I

Question

I am very curious as to thoughts and industry best practices regarding static members, or entire static classes. Are there any downsides to this, or does it participate in any anti-patterns?

I see these entities as "utility classes/members", in the sense that they don't require or demand instantiating the class in order to provide the functionality.

What are the general thoughts and industry best practices on this?

See the below example classes and members to illustrate what I am referencing.

// non-static class with static members
//
public class Class1
{
    // ... other non-static members ...

    public static string GetSomeString()
    {
        // do something
    }
}

// static class
//
public static class Class2
{
    // ... other static members ...

    public static string GetSomeString()
    {
        // do something
    }
}
Thank you in advance!

Explanation / Answer

In general, avoid statics - especially any sort of static state.

Why?

Statics cause trouble with concurrency. Since there is only one instance, it is naturally shared amongst concurrent execution. Those shared resources are the bane of concurrent programming, and often do not need to be shared.

Statics cause trouble with unit testing. Any unit testing framework worth it's salt runs tests concurrently. Then you run into #1. Worse yet, you complicate your tests with all of the setup/teardown stuff, and the hackery you'll fall into to try and "share" setup code.

There are a plenty of small things too. Statics tend to be inflexible. You can't interface them, you can't override them, you can't control the timing of their construction, you can't use them well in generics. You can't really version them.

There are certainly uses of statics: constant values work great. Pure methods that don't fit in a single class can work great here.

But in general, avoid them.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote