Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Please don't direct me to this post:

I have read it and still have no answer.

I have programmed c++ for years and was taught that everything should be oop in design. i have recently started java and find it to very restricting in the way it makes everything a member or method of a class.

Though I agree reusable classed improve code but does everything need to be a class.

as an example in a simple space invader game there would be classes for the aliens, the ships and the bullets but there are things like the score and timer that are single instants.

I feel these work better as globals rather than a class that will only be used once.

I am starting to question whether I am an oop programmer and if I want to be one for that matter.

I am not really looking for an clear answer as this in not really a question, I am just wondering if I am doing it all wrong or just differently.



Showing my ignorance here but what the hell ... what difference does it make putting all the global stuff into a global class apart from access and duplicity(multiplayer)?

Is there an efficiency or memory angle I am not seeing?


migration rejected from Sep 15 '14 at 11:19

This question came from our site for professional and enthusiast programmers. Votes, comments, and answers are locked due to the question being closed here, but it may be eligible for editing and reopening on the site where it originated.

closed as primarily opinion-based by gnat, MichaelT, GlenH7, Kilian Foth, ratchet freak Sep 15 '14 at 11:19

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise.If this question can be reworded to fit the rules in the help center, please edit the question.

now thnk about making space invaders for 2 players on the same computer at the same time.. class – fazo Apr 5 '11 at 12:54
A class with only public static members is just a collection of globals. They might not need to be in a class conceptually, but it's not exactly a problem. – Jon Apr 5 '11 at 12:56
Java isn't a very good example for OOP. Java is restrictive by design. That is the major reason why it is so heavily used. The premise is that by imposing this restriction, programmer would be forced to write better code. – Let_Me_Be Apr 5 '11 at 12:57
If you're never going to reuse something, then why bother with OOP. But if you're going to ever need to use it again, or there is the slightest chance that you would need to juggle more than one instance of something, then OOP, imho, makes far more sense. – dmcnelis Apr 5 '11 at 12:58
Who taught you that everything should be pure OO? I'd start there - don't believe everything people try to teach you. – David Thornley Apr 5 '11 at 14:02

11 Answers 11

up vote 8 down vote accepted

No, this doesn't really have anything to do with it. OOP is a tool, nothing more, and many functions do better with the strong compile-time generic support in C++, like std::sort. Java's "everything MUST be an object and we MUST use run-time inheritance to solve every problem" approach is clearly wrong, just like if I suggested that you MUST use a macro, template, or floating-point for everything.

Global variables are still just as wrong, though. You should make a Game or Application class and put them in there, because it's impossible to control or even view the access of global variables, making them a maintenance nightmare. That's why classes with only one instance work far better to global variables (or Singletons!), because they're much more flexible and much easier controlled.

Not thinking the Java way does not in any way make you not an OOP programmer. Everything does not need to be a class, but it certainly does need to be organized- namespaces, functions, as well as classes, and the programmer, not the language, chooses whether or not he wants variance at run-time or variance at compile-time.

Java can be summed up as a language without choice. You're forced to use objects and inheritance to solve every problem. C++ has friend, why doesn't Java? Because James Gosling doesn't like it and will force you to program like he thinks you should, and woe betide you if it's not appropriate to the task at hand. That's why Java is a poor language, and you shouldn't take inspiration from it.

Java is not a poor language. It's less flexible than C++, but it's still a language of choice for many projects and companies which achieve great results with it. You can complain about its shortcomings, but so do people complain about the shortcomings of C++. – quant_dev Aug 10 '11 at 12:04
@quant_dev: Not offering the user a choice about the way he structures his code is the definition of a poor language. C++ has it's own problems and I'm not going to pretend that they don't exist. Java only exists because you can hack things together with it. – DeadMG Aug 10 '11 at 18:02
You are entitled to your own definition of a "poor language", but I disagree with it. Nobody forces you to use Java. Yes, it mostly exists because you can hack things with it (this can be said about any language), but the point is that often you can hack things with it faster and easier than with C++ or C. What Java takes away in freedom, it gives back in doing stuff for you automagically. You can choose Java or C++ or any other language, so why complain about the lack of choice? It's just ranting for the sake of ranting. – quant_dev Aug 11 '11 at 8:23
PS. I used both Java and C++ in commercial applications, and while the differences were obvious, and in my problem domain (quantitative finance) I'd prefer C++, I enjoyed coding in both of them. – quant_dev Aug 11 '11 at 8:24
But nor would you ever want to draw a picture comprised of only straight lines. – DeadMG Aug 20 '12 at 18:09

Am I back in 1990's? :)

First of all, no-one really agrees what "pure OOP" even means. If you follow the definition of Alan Kay who came up with the term, OOP is pretty much supported only in languages like SmallTalk and Common Lisp and if you are using Java or C++ chances are you won't see too much "pure OOP" anyway. In C++ specifically it is often argued that free functions are a good thing because they improve encapsulation.

The bottom line is - try making your code robust, clean and organized; don't worry too much about meaningless labels such as "pure OOP".

Some sanity at last! – quant_dev Aug 11 '11 at 15:33

Whether the score itself is an int or an instance of a class is a completely independent issue from whether it's a mutable global (including a public static member) vs. a member of an instance of some class.

The Singleton OO design pattern provides a kind of globals, but it has two things wrong with it - it enforces a single instance of a class, and it provides global access to that instance, meaning that it's coupled with your entire program. Globals have the latter problem but not the former. Objects with static duration but restricted access reduce the coupling, although they still might not eliminate it if the result is that some of your functions are globally non-thread-safe, etc.

There's nothing wrong with creating a class like Player or GameProgress or Score, that contains a score instance member, and then just-so-happening to only ever create a single instance of that class per run of the game. Pass it around only to code that needs access to the score. Or perhaps put the "driving" code in the GameProgress class, and have it call out to other things which return score changes to it. Then only this code needs access to the current score - the code to establish that an alien has been shot can probably get by knowing how many points you get for shooting an alien, but not how many points the player has in total. So it probably doesn't need access to the score.

The purpose of globals is to obscure dependencies and coupling between different parts of your code. This is pretty much always a bad idea. It's fairly rare that you want to buy convenience at the cost of clarity.

If you're implementing an OS or an OS abstraction layer then you might need shared global data to represent the ongoing state of the system. At the lowest possible level, the hardware's physical memory map is non-negotiable. But application-level code generally doesn't need the maintenance headaches caused by mutable globals.

Very informative, Thank you – Skeith Apr 5 '11 at 13:36
+1, but IMHO, the Singleton pattern is not about providing global access to anything. It is about instantiation control. Calling SomeClass.getInstance() is not meant to replace someGlobal but to replace new SomeClass(), thus leaving the responsibility to the programmer (to enforce that only one instance is created, or to use pooling or what not). The Singleton is a special case of a Factory. – back2dos Apr 5 '11 at 14:44
@back2dos: that would certainly be sensible, but AFAIK it's not the Singleton pattern described in the GoF book. – Steve Jessop Apr 5 '11 at 14:56
Ok, that might be the case. Admittedly, I never read the book, but on wikipedia summary, it is classed as a creational pattern and summarized as 'Singleton restricts object creation for a class to only one instance.' ( – back2dos Apr 5 '11 at 15:14

Your over-arching question really has no appropriate boolean answer.

OOP is a methodology that solves a lot of issues well and some less well. You can create any number of applications with OOP and any number without it.

Sure, C++ will compile just fine with a mixture of classes and base code, since its built on C, but as you keep working on a piece of code, extending and maintaining it you will realize that the organizing principles (classes, interfaces, etc) really help you out.

In your specific example, the score and timer seem like they could just be unassociated globals, but in truth they are better of inside a 'Game Mode' or 'Game State' class that encapsulates the rules and status of the full game. With a more complicated design (multiple players, rules for extending your time based on achievements) you will very quickly bloat your global space or realize how much you really need (and hopefully want to) better organize your 'more abstract' classes.

More generally, functional programming works great for certain applications but games (since you mention it in your example) are so focused around maintaining and manipulating 'state' that an OO approach is much more appropriate.

So do you think this is a size issue. none of my projects have evolved far enough for me to see the difference between a set of globals and a game state class? – Skeith Apr 5 '11 at 13:29
Scope of projects and experience in general, probably. – Tim O'Neil Apr 5 '11 at 13:36
Also possibly the experience of working with designers that change their mind on core decisions after you've implemented it another way... and then once you've tried something else want to try a mix of the two. – Tim O'Neil Apr 5 '11 at 13:40
Not trying to boast just get an idea of my level but have been programming for 4 years and am now working on embedded system interfaces. Would you still class me a a beginner and how would I go about assessing my experience ? – Skeith Apr 5 '11 at 13:43
I didn't mean to imply you're a beginner, just conveying my perspective after 13 years and a half dozen published console games (and a few more unpublished ones). It's completely reasonable to disagree or have a different perspective. – Tim O'Neil Apr 5 '11 at 13:53

Globally shared data (singletons included) leads to increased coupling and dependencies, which is the main reason why software turns into big balls of mud.

Having said that, one needs to keep YAGNI in mind at all times. Going overboard with OO leads to extreme decoupling, which in turn leads to increased complexity and other problems, so there must be a balance between purity and good enough.


Looking at your list perhaps you need the concept of a 'Game' class which is a composite of the items you've listed, it could maintain the single instance of score/timer whatever as members. It could also contain useful methods that modify those.

I guess the answer to the question ' Is pure oop necessary?' is of course it's not, there is plenty of great code (heck, not just code, languages) out there that thumbs it's nose at OOP principles and plenty of OOP code that is an unmaintainable nightmare.

For me personally designing and writing code in an OOP 'forces' me to structure things better the much touted cohesion of OO design and create things in such a way as when something changes that was not predicted/designed for it's easier to refactor and reuse because good OO design enforces loose coupling.

Does this mean "yes", pure OOP is a good idea? – S.Lott Apr 5 '11 at 14:08
I guess it does. I was really just offering an solution to the OPs posed question that remained OO and still gave the advantages that a Global would give, I'll elaborate a little. – TygerKrash Apr 6 '11 at 11:38

There are a number of programmers, from the functional school, that claim that not only is pure OOP unnecessary, but probably harmful when looked from a multi-processor architecture. I'm seeing a trend toward using more and more final properties even in supposedly OOP designs, as these are being influenced by this trend. I've read a lot, and worked on a lot of code from "Strong Object" proponents, where an object has no getters and setters, it must know how to render itself, lots of stuff like that, its a HUGE pain to work on, and doesn't work well in practice in my experience. As far as the functional stuff...all of the examples I've seen are either web servers, which lets face it, are "get the request, return the file", not exactly complex behavior, and telephone switches. I did telephone switches for a LONG time, and can state pretty definitively that they are little more than state machines. I've yet to see a "functional" word processor, spreadsheet, or really anything that I would think of as having fairly complex behaviors, and THAT is the problem that OOP was supposed to solve, encapsulating data and behavior together in order to help we fallible programmers keep track of which functionality is changing what data. So, short answer, "Pure OOP" No. "Pure" anything...probably no as well.


There is nothing wrong with classes that only one instance is created in a program. Using global variables does not really provide any advantages, in fact just disadvantages as you provide more access than is typically required.

but is there really a difference as in the class they would have getters and setters to access them ? – Skeith Apr 5 '11 at 13:30
@Skeith, the getter and setter is not required and could possibly do more than just retrieve a value stored in an attribute. The class gives you the control and benefits of encapsulation. – jzd Apr 5 '11 at 13:41

No, everything does not have be OO. In a language like Java, it forces you to have objects and while you can write non OO type code, you will still have alot of the boiler plate code. In a language like C++ you can create a file with just a main function and write purely procedural code without touching the OO features of the language. In Java, avoiding the OO features is difficult because it forces a minimum level on you.

OO in general does provide some nice abstractions which can work well with many types of problems, but it is not required in all cases.


The problem with global mutable state is, that out of sheer lazyness, programmers build everything around it. As soon as something is needed in more than one module, it is made global. In the end, this breaks modularity, because every module depends on dozens of globals and if you need to change those, you need to change ALL the modules using them.

OOP suggests, all state be encapsulated and no object make assumptions about the state of another object. Letting one object retrieve another object globally embeds the assumption, that this is the only object that will ever be dealt with. This is unneccessary and unflexible.

There are some objects, that will probably be instantatiated only once, but passing them to the objects, that really need them is much better than simply making them global, because you create a clear and well defined control and information flow, rather than just throwing your core data out into the wild.


In Java, you typically implement global variables with public static fields in a final non-instantiatable class:

public final class Globals {
    public static int playerCount = 1;
    public static Background theBackground = null;
    // ...

    // Prevent instantiation of this class
    private Globals() {}

Global variables are often considered bad practice in OOP because they violate the encapsulation paradigm. Note that global constants (implemented in Java with public static final fields) are usually OK.


Not the answer you're looking for? Browse other questions tagged or ask your own question.