• 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
TheChubu

Generic classes of generic classes?

6 posts in this topic

Hi! It is possible to make a generic class that contains an attribute that can be either an object of the same generic class or some other type?

Say, generic class X has the attribute A, that attribute A can be either an object of generic class X (that we don't know its attribute A type yet) or a string, depending on certain conditions that are evaluated at runtime.

In my quest for implementing a quad tree, I've reached the point where I can generate it but I now want to store something on it, thus the need of generics. Ideally, in my quad tree, only the leaves will store something, the rest of the nodes won't.

I've implemented it in a way I'm only using one class "QuadTree" for the whole thing. The simple solution is just add an attribute "storedThing" of type objT, initialize it with "null" if its a root or mid child node, if its a leaf I assign to it the object I'm storing and be done with it. But, I thought that I could use the child node attributes themselves to store things with some generics magic.

So my quadtree its like:
[code]class QuadTree
{
QuadTree Norheast, Southeast, Southwest, Northwest;
}[/code]
Each QuadTree object has four more QuadTree objects, until I reach the leaves, then I initialize those with null, and the time to store something comes. My idea was that those variables could be more nodes of class QuadTree<T> or objects that I want to store, depending on the location of the node that I'm creating. Something like:

[code]if (nextNodeisNotLeaf) //Next level on the tree is not the last.
{
// Each attribute is a new QuadTree object, and the process repeats.
NE = new QuadTree();
SE = new QuadTree();
SW = new QuadTree();
NW = new QuadTree();
else
{
// Its a leaf, so each attribute is of the class type I want to store.
NE = new objT();
SE = new objT();
SW = new objT();
NW = new objT();[/code]

But I don't know how to do that. Its like a recursive thing, except I need to unroll the whole thing on a single line if I want to do anything! (ie, quad tree of 4 levels: root.NE = quadtree<quadtree<objectToStoreType>>; and what if I want to make a 5 level quad tree later on the program? Can't modify the class's source on runtine! ).

I wan't to decide what type each object instance of that class is going to store. But can't figure it out how to do it all in a single generic class...
0

Share this post


Link to post
Share on other sites
Let's start with the most profound -and hard to follow- advice for software developers: [url="http://en.wikipedia.org/wiki/KISS_principle"]KISS[/url]. In that spirit you have already described your simple solution, so I would run with that.

Just for the challenge of it, let's explore the complex solution. Keep in mind that I strongly advice against this unless you have really compelling reasons to want to save on a single extra property of the QuadTree class.

Basically you want your node references to hold either a QuadTree class reference or a reference to your target class. The rules of inheritance state that in that case both must have some common super class or common interface, otherwise it will never work. So if you really really want to do this, you can have your target class implement a QuadTree interface. This seems a very intrusive way (as seen from the objects you want to store) to implement it, but it works.

There is an alternative solution. Use the one common superclass that all classes have: Object. Each node NE, NW, SE, SW is just of type Object. You can still use generics to restrict what goes into and comes out of the quad tree, but you use it in the getter and setter methods. Now inside the QuadTree you will have to do a lot of instanceof comparisons to find out what a node is (ugh!), but it should work as well.
1

Share this post


Link to post
Share on other sites
[quote name='TheChubu' timestamp='1348385421' post='4982842']
The simple solution is just add an attribute "storedThing" of type objT, initialize it with "null" if its a root or mid child node, if its a leaf I assign to it the object I'm storing and be done with it.[/quote]To be honest, I would probably just do that.

To store the data solely in the leaf nodes only then something like this could be done:

First, define an interface that allows for traversal of the tree plus detection and access to any stored data/ This interface lets us use the quad tree without really caring about the particular node implementation:
[code]public interface IQuadTreeNode<T> {
public boolean hasData();
public T getData();

public IQuadTreeNode<T> getUp();
public IQuadTreeNode<T> getDown();
public IQuadTreeNode<T> getLeft();
public IQuadTreeNode<T> getRight();
}[/code]

Now we can implement this interface for inner nodes which only need to store linkages to surrounding nodes but don't need to store data. Also note that the surrounding nodes are referenced via the above interface. This lets us wire up nodes to either another inner node or a leaf node:

[code]public class QuadTreeInnerNode<T> implements IQuadTreeNode<T> {

private IQuadTreeNode<T> up, down, left, right;

@Override
public boolean hasData() {
return false;
}

@Override
public T getData() {
return null;
}

@Override
public IQuadTreeNode<T> getUp() {
return up;
}

@Override
public IQuadTreeNode<T> getDown() {
return down;
}

@Override
public IQuadTreeNode<T> getLeft() {
return left;
}

@Override
public IQuadTreeNode<T> getRight() {
return right;
}

}[/code]

Also implement for leaf nodes, which don't store linkages, only data:

[code]public class QuadTreeLeafNode<T> implements IQuadTreeNode<T> {

private T data;

@Override
public boolean hasData() {
return true;
}

@Override
public T getData() {
return data;
}

@Override
public IQuadTreeNode<T> getUp() {
return null;
}

@Override
public IQuadTreeNode<T> getDown() {
return null;
}

@Override
public IQuadTreeNode<T> getLeft() {
return null;
}

@Override
public IQuadTreeNode<T> getRight() {
return null;
}

}[/code]
2

Share this post


Link to post
Share on other sites
Why not something like this then ???

[CODE]
public interface Element<T> {}

public interface Node<T> extends Element<T> {
Element<T> northEast();
Element<T> southEast();
Element<T> southWest();
Element<T> northWest();
}

public interface Leaf<T> extends Element<T> {
T data();
}
[/CODE] Edited by ppgamedev
1

Share this post


Link to post
Share on other sites
Thanks for your answers! Took me a while to understand all of your solutions (never thought about using Object as a type).

It looks like a common interface would do the trick nicely (had to look up interfaces since I'm kinda beginning in Java specifics). Anything that has to go inside the QuadTree has to implement that interface so the QuadTree knows how to handle it. And something similar could be made for the three different nodes the tree is going to deal with (root, middle, leaf).

The root and middle nodes would add to the inherited QuadTree class the four node references NE, SE, SW, NW (plus irrelevant things) while the leaf node would just add the data property. That would split the three constructors I'm using in a single class into three classes that inherit the common portion of QuadTree (I think it would also clarify the source code a little).

Now, are all of you telling me that I can't do what I want to do by solely using generics and a single class? I need inheritance/interfaces in the middle?

By the way, I'm not sure what the QuadTree could do with the data. I had thought about just storing (ie add(data, posx, posy)) something and retrieve something (ie data = retrieve(posx, posy)). The main program has to know what positions its handling, or at least just ask blindly (give some coords to the quadtree and let it show whats in there).

The quadtree should do something else besides that? I'm thinking that since im handling squares, asking it what is located inside the bounds of an arbitrary square and let the quadtree retrieve all the data inside it. It would simplify searching for things on a specific area. Or just handle the data, without positions, and let the quadtree determine if it exists, and what is its position. It shouldn't be too hard to implement (I guess). The node traversing is the hardest part as I see it, everything else is just checking coords against squares.
0

Share this post


Link to post
Share on other sites
[quote name='TheChubu' timestamp='1348636020' post='4983884']
Now, are all of you telling me that I can't do what I want to do by solely using generics and a single class? I need inheritance/interfaces in the middle?
[/quote]
It depends, as Verik said you could upcast it all to Object but then you have to somehow know, or test for, the type information.

Essentially you need some way to express the fact that a node can reference either another node or a piece of data. That means you either:[list]
[*]Abstract the difference behind an interface and handle uniformly through that interface.
[*]Use data to describe the difference between node types, so give all nodes an optional reference to some data and maintain an invariant that we will only set that reference if the node is a leaf-node.
[*]Give up type information with a lowest common denominator "Any" type (e.g. Object in Java, or void* or any<> in C++) and rely on downcasting type information back in later on.
[*]Use a discriminated union and model precisely the "either-node-or-userdata" concept. Discriminated unions aren't in Java's core language though.
[*]Specialise/overload the class implementation - Java can't really do this.
[/list]

Different languages make different options more or less practical. In Java I would say that the first and second options in that list are the most reasonable. Edited by dmatter
1

Share this post


Link to post
Share on other sites
[quote name='dmatter' timestamp='1348753306' post='4984346']It depends, as Verik said you could upcast it all to Object but then you have to somehow know, or test for, the type information.[/quote]Ah I see. Read a little about upcasting and downcasting, Wasn't getting if by "up" it meant the super-class or the sub class.

It shoulnd't be that hard I guess. I know for a fact exactly what nodes will have data, and since that data is a generic type, I could downcast the leaf node's attributes to the generic type I entered into the quadtree and I should get what I want.

That said, having all sub nodes of type Object would be a lot of hassle as you said. Creating them wouln't be a problem, but traversing through them would imply a lot of downcasting the Object NE,SE, etc to access their QuadTree properties each time I need to pass through one of them. In short, simplified types but over complicated methods.

[quote name='dmatter' timestamp='1348753306' post='4984346']Essentially you need some way to express the fact that a node can reference either another node or a piece of data. That means you either:[list]
[*]Abstract the difference behind an interface and handle uniformly through that interface.
[*]Use data to describe the difference between node types, so give all nodes an optional reference to some data and maintain an invariant that we will only set that reference if the node is a leaf-node.
[*]Give up type information with a lowest common denominator "Any" type (e.g. Object in Java, or void* or any<> in C++) and rely on downcasting type information back in later on.
[*]Use a discriminated union and model precisely the "either-node-or-userdata" concept. Discriminated unions aren't in Java's core language though.
[*]Specialise/overload the class implementation - Java can't really do this.
[/list]
Different languages make different options more or less practical. In Java I would say that the first and second options in that list are the most reasonable.
[/quote]Yep, looks like it. Heh, it would have been interesting to try to make it by using unions.

Thanks for your answers! I thought that by just using the generic type on the nodes (ie QuadTree<T> {T NE,SE,SW,NW} ) I could get something working (and I just lacked the middle mojo to make it work) but its not the case it seems.

I'm going with the inheritance/interface way, looks like the "prettiest" one and I'll avoid having to overload the constructor two times to get the nodes I want.
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