Jump to content
  • Advertisement
Sign in to follow this  
Nicholas Kong

Advice on this array implementation

This topic is 1934 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

While this code is syntaxically possible, is it generally advised or should I create the dog and cat object reference outside of the array?
 
I am curious if this array implementation is actually used in practice.
 
Pet[] petStorage = {new Dog("doggy","male"),new Cat("kitty","female")};

Share this post


Link to post
Share on other sites
Advertisement
In C# I have seen constructs like that in some situations. We use C# as our scripting language.

So short answer, yes, it is used in practice in real games.


The pattern is cleaner than other potential solutions.

Consider one alternative:
Create a magic number indicating the array will be length 2.
Create an array of the above length.
Create and assign the objects independently.

That creates some issues. You now have a magic number for the length -- in C# you don't need the number since arrays have a .Length property, so that is redundant. You have a maintenance issue to ensure that the constant matches the number of items actually added -- imagine if someone removed an object from the creation sequence leaving your array an item short.

Or another pattern:
Create a List<> container object
Add the items individually

Creating a fixed array with elements like that consumes less resources than a List<> container object, and it comes with a much faster initialization since you avoid the creation of the container, allocation of space, and the myList.Add() calls.

For a collection of items known at build time, it can be a great pattern.

Share this post


Link to post
Share on other sites

What it is exactly "discouraged" in here? (if it has ever been a discouraged practice that is) At first I thought you meant the anonymous objects.

Edited by TheChubu

Share this post


Link to post
Share on other sites

One thing that might be discouraged is hard coded data. It depends on the circumstances, but the example you gave would probably be a candidate for a more data driven approach.

 

The other is that if you happened to have non-memory resources in the classes. There would not be a way to clean up the resources allocated by one of the objects if another happened to throw an exception during construction.

Share this post


Link to post
Share on other sites

What it is exactly "discouraged" in here? (if it has ever been a discouraged practice that is) At first I thought you meant the anonymous objects.

discouraged as in having creating objects inside an array instead of outside of the array. 

Share this post


Link to post
Share on other sites

One thing that might be discouraged is hard coded data. It depends on the circumstances, but the example you gave would probably be a candidate for a more data driven approach.

 

The other is that if you happened to have non-memory resources in the classes. There would not be a way to clean up the resources allocated by one of the objects if another happened to throw an exception during construction.

can you give an example or examples of a data driven approach? I thought all programs are data driven.

 

I do not understand what you mean by non-memory resources. I thought every variable or any object created takes up memory.

 

That is true about the exceptions.

Edited by warnexus

Share this post


Link to post
Share on other sites

can you give an example or examples of a data driven approach? I thought all programs are data driven.

In this context, data driven means that instead of being hard coded, data is loaded from a file:

Pet parsePet(String line) {
    String tokens = line.split(" ");
    if(tokens.length != 2) {
         throw /* bad line */;
    }
    String type = tokens[0];
    String name = tokens[1];
    String gender = tokens[2]; // TODO: sanity check gender
    if("dog".equals(type)) {
        return new Dog(name, gender);
    } else if("cat".equals(type)) {
        return new Cat(name, gender);
    }
    throw /* unknown type ... */;
}
 
List<Pet> pets = new ArrayList<Pet>();
FileInputStream file = new FileInputStream("pets.txt");
try {
   BufferedReader reader = new BufferedReader(file);
   String line;
   while( (line = reader.readLine()) != null) {
       Pet pet = parsePet(line);
       pets.add(pet);
   }
} catch (IOException e) {
    log.error("Failed to load pet data, falling back to defaults", e);
    return Arrays.asList(new Pet [] {
        new Dog("doggy","male"),
        new Cat("kitty","female")
    });
} finally {
    file.close();
}
return pets;

(Code for illustrative purposes only, not compiled or tested).

 

The data file would look like:

dog,Rex,male
cat,Mittens,female
dog,Dixie,female

 

I do not understand what you mean by non-memory resources. I thought every variable or any object created takes up memory.

Conceptually, all objects and variables use memory. In practise, some memory locations may be optimised away, the variable will live in registers, or in extreme cases all uses of the object can be precomputed and the runtime can avoid allocating any space, even in a register.

 

As for a non-memory resource, see the FileInputStream above. It uses memory, but also handles a OS file handle. Java's garbage collection will handle the memory, but the may not close the file handle (the finalizer may cause the file handle to be closed eventually, if the VM has noticed the stream is garbage), which could cause the process to run out of file handles. Here, we are safe as the try ... finally block ensures the file handle will be closed.

 

Other examples which might be more relevant in a game context include graphics card resources, such as textures.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!