Which of these is a better programming practice?

Say you’re writing a small program. It runs a main method, executes a bunch of stuff, and spits out an output. Say it’s in Java for now, since that is what I am doing at the moment.

You have some main data structure that is going to be referenced by the main method a bunch of times and also a bunch of times by some supporting methods. Should the data structure be a global variable in the Main class, or should it be created inside of the main method and then passed to other methods as an argument?

I’d probably make it a singleton. Just reference it, and get the one instance.

So I guess what you’re saying is, if it’s going to be used a lot everywhere, make it global, but if it’s rarely used outside of the main method, just define it in the main method?

Or, make it its own thing. Self-instantiating upon reference. Doesn’t belong to the main.

On the other hand, testing of many smaller methods might be easier if you did pass in the data structure.

Is your methodology mostly procedural, it sounds like?

Yes, it is. This is a very small project. Actually a coding exercise for a job application.

There is no such thing as a “global” variable in Java. There are local variables, instance variables and there are class variables. If multiple methods depend on it then storing it as an instance method is the best bet. But typically you want to see the Main class being pretty lean, having just a main method, and delegating the heavy lifting to other objects.

Class variable. Sorry. Forgot the term.

It really depends on the problem. If this is something really fundamental to the problem, such that everything you’d conceivably be using this program with would also use it (or at least not confuse it with anything else), then make it global, or whatever your language’s equivalent of that is. If it’s just for bookkeeping between a few program modules, and you’d be fitting this piece in with other pieces that wouldn’t know nor care what that variable is, then keep it local and pass it through as needed. For anything in between, use your best judgment.

Given that this is just an exercise, you’ll probably never actually have to interface it with anything else, so either way should work just fine. But given that it’s for a job application, I’d recommend the local approach: That’s by far the one you’d want most often, and whoever’s hiring you is probably looking for whether you know how to do it. Plus, of course, if you’re programming professionally, modularity is important, and you’ll probably have to make your code work with code written by others, which will be a lot easier with everything local (or at most, the head programmer on a project will start off by deciding that a small number of variables will be global, and telling everyone which ones).

Agreed - I use the singleton for exactly things like this.

My rough rule is: If the supporting functions are going to use most of the fields of the data structure, then pass it around as an argument. If they are each going to access parts of the data structure, then make it a member variable.

If this was just a test app for personal use, then a singleton would be fine. Since it is a job interview, I would avoid a singleton at all costs. Some developers fiercely oppose singletons. And as Chronos mentioned, this example would demonstrate the mechanisms of working within a larger codebase.

For example steve yegge - singleton-considered-stupid

Thanks FoundWaldo. That was the article I was thinking of, but I couldn’t remember enough of it to find it.

If you are going to avoid something in an interview because *some *programmers may oppose it, don’t bother going, you won’t be able to say anything.

Programming is like that.

I just got a gig, so I have had some interviews recently. In at least two of them they tested my knowledge of patterns by asking me how to implement a singleton in C# (they also wanted to be sure it was thread safe and one programmer wanted to talk about lazy instantiation.)

In fact, the *patterns *book seems to be a popular place from which to snag interview questions (singletons and factories were two common ones.)

Having said that: I’m no longer sure I would use a singleton for this problem. As is (too) common for me, I only *skimmed *the original question… my apologies to the OP for that.

Yeah, yeah, using singletons is a religious argument, right up there with whether Macs are better than PCs. That article is no more right than my firm belief that Windows just sucks.

There are times when a singleton is perfectly appropriate, and will make everyone’s life easier than having to pass something around everywhere. Truly good software engineers do not subscribe to absolute, dogmatic rules like “Never use a singleton!” A good engineer realizes that the right answer to “Should we use a singleton for this?” is always: “it depends”.

For every one of his “what if’s” (“what if your Singleton has a handle to some limited resource”), there can easily be a case where it’s n/a (“In this case, our Singleton does not have a handle to anything”). Or “the Singleton design is syntactically noisy”; um, compared to requiring that nearly every single class constructor, and many methods, pass around the thing that otherwise would be a singleton? Or “It’s almost impossible to subclass a Singleton”; ok, but we don’t need to subclass it. Etc.

The bottom line is that good software engineering requires judgment, not dogmatic rules. In this particular case, the OP does not have sufficient information to be able to answer the question with any degree of certainty. So the answer, really, is “it depends.” (A tiny sample of the questions that it depends on: “What is going into this data structure?” “How big is your overall program?” “How many classes/methods will need access to this data structure?” “What are the chances that you will be adding to this data structure?” “What might you add to it?” “Will it reference some limited resource?” etc., etc., etc.)

This isn’t good advice in this case. In an interview, there is a dialog – you can make your assertions and back them up. You have an opportunity to overcome the interviewer’s bias.

But the OP isn’t asking about an interview; he is asking about a pre-interview program that is likely being used as a interview filter. For that, you want to do what you can to get in the door. Part of this includes avoiding obvious traps and pitfalls.

I outlined what I would use instead of a singleton. I mentioned that a singleton might be a pitfall. I am not sure why you exaggerated that to “If you are going to avoid something in an interview because some programmers may oppose it”.

[moderating]
There isn’t really a GQ answer for this (coding style is subjective), so I’ve moved the thread to IMHO.
[/moderating]

[moderating]
There isn’t really a GQ answer for this (coding style is subjective), so I’ve moved the thread to IMHO.
[/moderating]

Y’know, Gary, you could have used a singleton post there.

:wink:

I really need to create a [moderating] object, don’t I?

One thing that I’ve noticed from programming (especially in Java) is that void methods that alter the state of an argument are often very dangerous, even with proper contracting. Generally with an OO language, you want a method that’s a mutator to act on the object it’s attached to, not the objects its given.

Performing foo.bar(baz) (assuming it’s a mutator, and not to retrieve info) should use baz to alter foo with bar as a facilitator. For this reason, I wouldn’t pass the data structure into everything. There are, of course, exceptions to this, mostly in the case of static functions to be used as “library” functions, for instance, Collections.sort() isn’t going to modify Collections, that’s ridiculous, since Collections is a class*, but it is a library function meant to operate on Objects that implement the Collections interface. However, you usually want these to be defined in the super class, or the data structure itself, not in some random place like Main.

For this reason, I’d say use either an encapsulating mutator class with the methods you need, and pass the data structure in the constructor:

Foo bar = new Foo(dataStructure);
foo.doStuff(args)
foo.doMoreStuff()
System.out.println(foo.getStuff());

Or make the data structure itself a Singleton, or register it with a Blackboard**, and have the functions work within those confines. Obviously, like everything, there are situations where violating this may make things cleaner, but for a pre-interview question theory is often more important, you can pontificate on the drawback of a philosophy in an interview where you have a chance to debate.

If I misunderstood, and you’re simply using the data structure to calculate things, without mutating it, then it’s probably fine (and even encouraged) to pass it in.

  • Okay, let’s not deal with reflection.
    ** Well, okay, Blackboards themselves are usually Singletons, but that’s not the point.