• Create Account

Better way to write this code

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

17 replies to this topic

#1frazchaudhry  Members

Posted 19 February 2014 - 09:03 PM

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.

#2HScottH  Members

Posted 19 February 2014 - 09:53 PM

POPULAR

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

But if you must: just replace the first return line with break;

Oh, and don't construct a wasted instance on this line:

Coordinates coords = new Coordinates();

Just set it to null:

Coordinates coords = null;

#3DoctorGlow  Members

Posted 19 February 2014 - 10:01 PM

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

#4frazchaudhry  Members

Posted 19 February 2014 - 10:04 PM

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, 19 February 2014 - 10:09 PM.

#5boogyman19946  Members

Posted 19 February 2014 - 10:22 PM

POPULAR

The second return statement is necessary because the compiler can't just assume the first return statement will execute. There is no guarantee that a node in the list matches the argument key.

Therefore, the return statement in question should return a value that one would expect if there was no entry matching the given key. If you can't return null, you could write it like this:

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


But you won't be able to tell if you actually found a valid set of Coordinates unless you save that state somewhere. The above code is pretty much the same as yourself, with the exception that it only creates a new Coordinates at the last minute and only when needed. Not a great improvement, but some start.

I don't know C# very well. I thought it would have a reference system more similar to Java, but in Java you can return a null value for just about anything that's not a primitive.

Edited by boogyman19946, 19 February 2014 - 10:25 PM.

- Java API Documentation - For all your Java info needs
- C++ Standard Library Reference - For some of your C++ needs ^.^

#6frazchaudhry  Members

Posted 19 February 2014 - 10:36 PM

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, 19 February 2014 - 10:36 PM.

#7Nypyren  Members

Posted 19 February 2014 - 11:41 PM

I would write it how boogyman19946 does.

Edited by Nypyren, 19 February 2014 - 11:43 PM.

#8aregee  Members

Posted 20 February 2014 - 06:08 AM

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, 20 February 2014 - 06:10 AM.

#9Paragon123  Members

Posted 20 February 2014 - 10:03 AM

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;
}
}


#10Nypyren  Members

Posted 20 February 2014 - 11:44 AM

Linq might work for you if nodes is IEnumerable.

Anything that you can foreach is IEnumerable, so it will definitely work.

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, 20 February 2014 - 11:44 AM.

#11Paragon123  Members

Posted 20 February 2014 - 01:30 PM

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();

#12Aurioch  Members

Posted 20 February 2014 - 03:47 PM

EDIT: Ignore, misunderstood question and code :/

Edited by Aurioch, 20 February 2014 - 04:07 PM.

#13frazchaudhry  Members

Posted 20 February 2014 - 10:22 PM

Linq might work for you if nodes is IEnumerable.

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.

#14Nypyren  Members

Posted 20 February 2014 - 11:03 PM

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, 20 February 2014 - 11:13 PM.

#15frazchaudhry  Members

Posted 20 February 2014 - 11:11 PM

Thanks Nypren, but yeah I'm sticking with that code. I found this link http://stackoverflow.com/questions/275073/why-do-c-sharp-multidimensional-arrays-not-implement-ienumerablet that basically explains why 2D arrays can't use linq for anyone that is interested.

Thanks to everyone that helped. Cheers.

#16Washu  Senior Moderators

Posted 21 February 2014 - 12:43 AM

POPULAR

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.

public Coordinates GetNodeCoordinates(int number)
{
foreach(Node node in nodes)
{
if (node.Number == number)
{
coords = node.Coordinates;
return coords;
}
}
throw new InvalidOperationException(string.Format("Expected to find a node with number: {0}, but instead found nothing", number));
}


Edited by Washu, 21 February 2014 - 12:46 AM.

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.
ScapeCode - Blog | SlimDX

#17dmatter  Members

Posted 21 February 2014 - 09:33 AM

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.

#18HScottH  Members

Posted 19 March 2014 - 10:23 PM

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.

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.