• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
PixelPrime11

Static self referencing classes, a good idea or not?

6 posts in this topic

This is a general OOP question, as I didn't know if this is an 'accepted' practice in programming!

I have some classes in my application that only ever get instantiated once - for example, a class that defines application settings and properties. However, when I want to reference this class instance from another class, I'm kinda stumped because I don't have a visible reference to my class instance.

Sure, I could pass the class instance reference into the functions that need it, but that seems ugly.

Instead, I've added a static reference to the class instance, and can therefore refer to that instance from any other class.

Example:

[source lang="java"]public class Settings
{
// static reference to a settings object
public static Settings ref;

public Settings()
{
// apply a self-reference
settings = self;
}

private void doSomething()
{
...
}
}[/source]

So, from another class file entirely, I can refer to my single Settings class instance by using the in-built static reference, giving me access to its private methods:

[source lang="java"]Settings.ref.doSomething();[/source]

Is this an acceptible method of doing this? Or is this type of self-referencing frowned upon? Should I just make all required 'public' members and methods in the class static instead?

[source lang="java"]public class Settings
{
public Settings()
{
// do nothing
}

public static void doSomething()
{
...
}
}[/source]

I'm looking forward to some insight on this!

Thanks all!
0

Share this post


Link to post
Share on other sites
Thanks, I can see your point about it potentially closing the door to using further instances of the class for other reasons.

It might help to give some background on the class. It's a Canvas for a drawing / modelling application, so I know for a certainty that there can only ever be one instance of the class active at any time (this isn't a multiple-workspace type of project). A workspace can only have one canvas.

Perhaps I need to think about reorganising the communication of data between the classes outside of the workspace so that rather than relying on a call directly to a static method inside of the Canvas object, I can pass a reference to the (only) instance of the Canvas to the required classes as an argument.

It'll just mean a bunch of refactoring - but eh, if we had a few bucks everytime we did that... [img]http://public.gamedev.net//public/style_emoticons/default/biggrin.png[/img] Edited by PixelPrime11
1

Share this post


Link to post
Share on other sites
I really don't like singletons, but there's a pattern I developed for a large scale project to overcome the lack of testabillty and the implementation coupling that the singletons usage brings :

[source lang="java"]public abstract class Settings {
private static final SingletonHolder <Settings> HOLDER = new SingletonHolder<Settings>("implementation.property");
public static final Settings getInstance() {
return HOLDER.getInstance();
}
public abstract void foo();
}

public class DefaultSettings extends Settings {
public void foo() {
// Do your thing
}
}

public class SingletonHolder <Type> {
private final <Type> instance;
public SingletonHolder(String property) {
this.instance = Class.forName(System.getProperty(property)).newInstance();
}
public Type getInstance() {
return instance;
}
}
[/source]

For the sake of brevity, I didn't write the exception handling code, and the SingletonHolder should be aware of changings on the value of the system property used to fetch the implementation's class name. Edited by Bubsy
0

Share this post


Link to post
Share on other sites
Yes, as has been stated (though I'll state it again to make it super clear), one of the biggest problems with global variables (which is what this is) is you get too many things dipping their fingers into stuff they really shouldn't be. Systems that really shouldn't be coupled grow complex dependencies on each other, all because the programmer didn't design the program well.

The argument that "you might need more than just one" is true, but I think it pales in comparison to the huge pain in the butt the complex, overly coupled system that grows from global variables. Debugging gets complicated (as changes to global variables are hidden by the fact they're buried deep in some code), and overall the design goes to crap as the global variable tumor begins to spread and more objects start referring to other objects that they really, really have no need to. At least they wouldn't have such a need if things were designed well.

And for what does need to be accessed and shared, thankfully we have parameters we can pass to function calls. This makes program control flow much easier to follow and much less error prone (because you, the programmer, may forget part A changes global variable B, which affects part C; passing a parameter makes this relationship and dependency explicit and hopefully you'll have less brain farts).
1

Share this post


Link to post
Share on other sites
Just pass the object's reference you need. And make up some "default behavior" if the reference turns out to be null (which could happen).

If the function that needs the reference is a method in some other object, you could make it so the object stores the reference. That way you can set it up in the constructor of said object or change it with a setter method later.

Besides, it gives you a good insight into your code when you think "Well, this object always used a single instance of this class... What happens if I switch it along the road? Is it safe? It crashes? It keeps working?"
0

Share this post


Link to post
Share on other sites
[quote]
It's a Canvas for a drawing / modelling application, so I know for a certainty that there can only ever be one instance of the class active at any time (this isn't a multiple-workspace type of project). A workspace can only have one canvas.
[/quote]

You mean you don't have multiple canvases for layer effects? For undo/redo? For offscreen loading/saving? For multiple screens/multiple windows for model merging?

Having this sort of side effect in the constructor is decidedly undesirable even if you want a single common/default instance.
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0