Is it a bad practice for a method to return a string inside another method?

So, I am writing some code for assignment in my Data Structures class, and I was wondering if using a method returns a value to another method, this is usually 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 spacecraftโ€™s location (*) only indent down to the next line and return to the PrintLocation method to repeat the loop. (This is my first question, please come to me :))

+5
source share
2 answers

In general, it is good practice to keep the methods short and have a specific purpose, otherwise they may be misused. (Your method determines if the place should be printed and format the output).
The method should return what it was intended for: if you want to ask if it should be printed, a more suitable way would be:

 public bool ShouldPrintLocation(MarsLander ml, int i) { return (i == ((ml.GetHeight() % 100) + 9); } 

PrintLocation() then actually prints the location, if 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(); } 

It makes sense for me to have output formatting in PrintLocation , since this method is designed to ... Print location, as opposed to doing some logic / calculation

+1
source

Not bad if necessary. This is practiced even by others. Maybe just change the method name for your code, like GetSpaceshipLocation(MarsLander ml, int i)

0
source

Source: https://habr.com/ru/post/1246838/


All Articles