So, I'm writing some code for an assignment in my Data Structures class, and I was wondering if using a method return a value into another method is generally bad practice
public void PrintLocation(MarsLander ml)
{
for (int i = 10; i >= 0 ; i--)
{
Console.Write("{0} m: {1}", i * 100, WheresTheSpaceship(ml, i));
}
Console.WriteLine();
}
public string WheresTheSpaceship(MarsLander ml, int i)
{
if (i == ((ml.GetHeight() % 100) + 9))
{
return " * \n";
}
else
{
return "\n";
}
}
The WheresTheSpaceship
method should return whether to print the location of the spaceship (the *) just indent down to the next line and return to the PrintLocation
method to reiterate the loop. (This is my first question please go easy on me :) )
In general it is good practice to keep methods short and to have a specific purpose, otherwise they may be misused. (Your method determines whether the location should be printed and formats the output).
The method should return what it was intended for: If you want to ask whether the location should be printed, a more appropriate method would be:
public bool ShouldPrintLocation(MarsLander ml, int i)
{
return (i == ((ml.GetHeight() % 100) + 9);
}
PrintLocation()
would then actually print the location if that is necessary:
public void PrintLocation(MarsLander ml)
{
for (int i = 10; i >= 0 ; i--)
{
string locationText = ShouldPrintLocation(ml, i) ? "*" : string.Empty;
Console.WriteLine("{0} m: {1}", i * 100, locationText);
}
Console.WriteLine();
}
To me it makes more sense to have the output formatting in PrintLocation
as this method is intended to.. Print the location, as opposed to doing some logic/calculation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With