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

Better way to write this code

17 posts in this topic

Hi,

   I wanted to know if there is a better way to write the code for this method that I am using in my project.

public Coordinates GetNodeCoordinates(int number)
        { 
            Coordinates coords = new Coordinates();
            foreach(Node node in nodes)
            {
                if (node.Number == number)
                {
                    coords = node.Coordinates;
                    return coords;
                }
            }
            return coords;   
        }

It basically goes through a 2 dimensional array and if the value in the array object matches the other value it returns a coordinate object. The way I have made my program is that it is impossible for the value being searched for to not be in the array. I do not want to have the second return statement after the foreach loop because I know it will never be called. But the compiler complains if I remove it. Can somebody tell me if there is any way to write this method so I don't have to write the second return statement.

0

Share this post


Link to post
Share on other sites

no you can't do that. Its a non-nullable value type. Also that instance construction must be there otherwise, the compiler will give an error on the second return statement complaining that I am using unassigned local variable. The compiler isn't sure whether my code will actually go inside the if statement or not.

The reason I care is because maybe somebody more experienced than I am might have a better way of going about this. Maybe I'll get to learn something.

Edited by frazchaudhry
0

Share this post


Link to post
Share on other sites

well I could have it return a null value, in C# you can make even primitive values take on the null value, e.g

int? nullableInt = null;

and do something like this with my code

public Coordinates GetNodeCoordinates(int number)
        {
            Coordinates? coords = null;
            foreach(Node node in nodes)
            {
                if (node.Number == number)
                {
                    return node.Coordinates;
                }
            }
            return (Coordinates)coords;   
        }

But it looks just as ugly as my original method. Your improved way looks much better so I am going with that for now. Thanks Boogyman

Edited by frazchaudhry
0

Share this post


Link to post
Share on other sites

I can't imagine why you care. If it's never executed, it's irrelavent.

 

 

This one is a classic.  You have an area of your code that is unreachable.  You think to yourself that "I'll just leave it".  Then you get an obscure bug.  After hours of debugging, you find that the code did indeed enter the area where it should be impossible to go.  It happens.  You can not always foresee all scenarios or bugs other places in code that may alter your logic. 

 

I would:

1. Put a break, as HScottH said, or

2. At least put a log entry telling you that "I should never be here!" so you know when the impossible happens, you know where to look right away.

 

EDIT:

3. Consider if this is eligible for refactoring as this may indicate that there is a simpler way to change your code to avoid this situation altogether.  It may not be, but it is worth looking into.

Edited by aregee
1

Share this post


Link to post
Share on other sites

Linq might work for you if nodes is IEnumerable.

public Coordinates GetNodeCoordinates(int number)
{
     return nodes.FirstOrDefault(n=>n.Number==number)
}

If you want to use Nullable Coordinates

public Coordinates? GetNodeCoordinates(int number)
{
     return nodes.Cast<Coordinates?>().FirstOrDefault(n=>n.Number==number)
}

(I'd only use .Cast if it isn't being called often)

 

If a node with the correct number is more likely to be in nodes than not it might be quicker to do something like

public Coordinates? GetNodeCoordinates(int number)
{
  try{
    return nodes.First(n=>n.Number==number);
  } catch{
    return null;
  }
}
0

Share this post


Link to post
Share on other sites

Linq might work for you if nodes is IEnumerable.


Anything that you can foreach is IEnumerable, so it will definitely work. smile.png
 
public Coordinates GetNodeCoordinates(int number)
{
     return nodes.FirstOrDefault(n=>n.Number==number)
}

This is similar to what I was going to write (above), but then I noticed that nodes in the collection contain the .Coordinates member, making First/FirstOrDefault not what you'd want (because you'd have to null check the node you get from that, then get .Coordinates from it, which ends up being one step more complex than doing the loop yourself). So I edited my post to agree with boogyman since that's exactly what I would write instead. Edited by Nypyren
1

Share this post


Link to post
Share on other sites

Ah, good point. I didn't notice that the node it's self wasn't the coordinate....

As far as to whether or not it is better at this point is debatable.. but here's a Linq query to do it.

 

return nodes.Where(n => n.Number == number).Select(n => n.Coordinates).Cast<Coordinates?>().FirstOrDefault();

0

Share this post


Link to post
Share on other sites


[quote name='Paragon123']
Linq might work for you if nodes is IEnumerable.
[/quote]
Anything that you can foreach is IEnumerable, so it will definitely work.

 

Apparently its not working. "nodes" is a 2d array and the linq methods First and FirstOrDefault are not available for this array. However, I have checked that these methods are available for 1D arrays. Although I am able to traverse my 2D array using a foreach loop, I am not sure if the 2D arrays are part of Linq.Enumerable. I checked the msdn documentation but couldn't find anything specific relating to multidimensional arrays and these methods.

 

I have settled on this code though

public Coordinates? GetNodeCoordinates(int number)
        {
            Coordinates? coords = null;
            foreach(Node node in nodes)
            {
                if (node.Number == number)
                {
                    coords = node.Coordinates;
                    break;
                }
            }
            return coords; 
        }

I have enclosed the code that calls this function in a try block and if a null value is received, an exception is thrown and the situation is handled.

1

Share this post


Link to post
Share on other sites

Apparently its not working. "nodes" is a 2d array


Ahh, I see. The primary set of LINQ methods work with IEnumerable<T>. 2D arrays appear to only implement IEnumerable but not the generic version of the interface. That's kind of strange considering the array rank doesn't affect whether it's homogenous or not...

In that case, you could add one more step if you REALLY wanted to do it this way:
 
return nodes
    .Cast<Node>() // Quick way to convert from IEnumerable to IEnumerable<Node>
    .Where(n => n.Number == number)
    .Select(n => n.Coordinates)
    .Cast<Coordinates?>()
    .FirstOrDefault();
(Personally, that's a lot of LINQ for such a simple operation. I would stick with the foreach loop.) Edited by Nypyren
1

Share this post


Link to post
Share on other sites

The proper course of action for code that should never be reached is to throw an exception, not return a random/meaningless value. Returning a nullable value, including all the hassle that will add to other parts of your code, for a section of code that SHOULD NEVER BE REACHED is damn stupid.

This!

An exception is self-documenting of the fact that the code should never be reached and it will be "in your face" should the assumption that it never runs ever change, thereby alerting you to the problem.
0

Share this post


Link to post
Share on other sites

HScottH, sorry for down voting you, I meant to up vote you, but my fat fingers pressed in wrong placed.

 

No worries; I'm sure I have deserved it other times where people were just too busy to "act."

I don't care about rep; it's chatting with my fellow geeks like you that makes this site good for me.

1

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