Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Creating an instance of a class within a static method of the same class

Posted on 2012-09-21
5
Medium Priority
?
485 Views
Last Modified: 2012-09-26
So I came across some code recently that confused me. Here's an example of the structure...

public class Foo
{
  public static void Bar()
  {
    Foo fooInstance = new Foo();
    fooInstance.DoStuff();
  }
  public void DoStuff()
  {
    //stuff
  }
}

Open in new window


It's obviously more complex than the above example but you get the point. This struck me as awkward, even bad coding but I can't put my finger on why. Can anyone give me a reason why it isn't? Can anyone explain why it is?
0
Comment
Question by:Russ Suter
  • 2
  • 2
5 Comments
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 1600 total points
ID: 38423313
The singleton pattern uses static methods/properties to ensure that only one instance of a class can ever be created. For your example, I agree that the logic doesn't make much sense. What you posted is not the singleton pattern, though.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 38423331
A (non-thread-safe) Singleton implementation:

public class Singleton
{
    // Keep this static since the static property Instance
    //  needs access to the reference
    private static Singleton _instance;

    // Do not expose a constructor to the outside world
    //  This means no one except this class can create
    //  an instance of the class
    private Singleton()
    {
        _instance = new Singleton();
    }

    // Return the only living instance of this class
    //  If there is no instance (i.e. the private
    //  variable is null), then initialize the
    //  private variable
    public static Singleton Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new Singleton();
            }

            return _instance;
        }
    }
}

Open in new window

0
 
LVL 20

Author Comment

by:Russ Suter
ID: 38423335
Agreed. I'm familiar with the singleton pattern and immediately recognized that this wasn't it. Theoretically I could call the static method repeatedly and get multiple instances in memory. The class contains absolutely no static variables so there's no benefit to it. I just can't figure out what was going through the programmer's head when he decided this was a good idea. I'm really trying to find a good reason to hang my hat on so I can tell him why it isn't a good idea.
0
 
LVL 86

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 400 total points
ID: 38423662
"The class contains absolutely no static variables"

--> But does it contain instance variables?

"I'm really trying to find a good reason to hang my hat on so I can tell him why it isn't a good idea."

Essentially you can this:

    Foo.Bar()

Instead of:

    Foo fooInstance = new Foo();
    fooInstance.DoStuff();

So he's (or she's) made it more convenient to use DoStuff().  

It really boils down to whether this is a utility method/class that doesn't require any external variables to execute, and whether DoStuff() is creating any resource intensive (memory or CPU usage) objects.

We don't have enough information to deem this bad or good in my opinion...

I'd agree with your statement of "awkward" though.  If it is a utility class, then I'd declare DoStruff() as private so you can only access it via the static method with "Foo.Bar()", thus removing any doubt as to how it should be used.  Perhaps it's just the fact that it can be called in two different ways is what bothers your head!  =)
0
 
LVL 20

Author Closing Comment

by:Russ Suter
ID: 38437471
Actually as I looked at this more closely the comment about the singleton pattern led me down the path I needed to go. The implementation isn't thread safe. I hung my hat on that and got my way. Thanks guys!
0

Featured Post

Get your Disaster Recovery as a Service basics

Disaster Recovery as a Service is one go-to solution that revolutionizes DR planning. Implementing DRaaS could be an efficient process, easily accessible to non-DR experts. Learn about monitoring, testing, executing failovers and failbacks to ensure a "healthy" DR environment.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
High user turnover can cause old/redundant user data to consume valuable space. UserResourceCleanup was developed to address this by automatically deleting user folders when the user account is deleted.
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…
Suggested Courses

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question