Microsoft Interview Question
Software DevelopersTeam: Cloud + Enterprise
Country: United States
Interview Type: Written Test
What about redundant conversion code, isn't it a waste of resources to parse string just in order to figure out whether it's parsable?
The tryParse solution is great. If we still using Int16.Parse, we can similarly modify the code. If the number cannot be parsed an exception will be thrown and caught by the catch block. Otherwise we have successfully parsed the number and we can return true.The code should be:
public static bool ConvertToNumber(string str)
{
try
{
int n = Int16.Parse(str);
}
catch (Exception ex)
{
cout<<"Invalid number\n"<<endl;
}
return true;
1. ConvertToNumber – Find Flaws and Limitations
Identify the flaws / limitations in the following ConvertToNumber method
public static bool ConvertToNumber(string str)
{
bool canConvert = false;
try
{
int n = Int16.Parse(str);
if (n != 0)
{
canConvert = true;
}
}
catch (Exception ex)
{
}
bool retval = false;
if (canConvert == true)
{
retval = true;
}
return retval;
}
First, the name should be something like IsConvertibleToNumber, since the number isn't returned. Either that or the number should be returned, whichever is more useful. But if we want to return the number plus a boolean saying whether the conversion was successful, there are already standard library methods for this, such as Int16.TryParse.
Furthermore, we might be inclined to question whether this method is supposed to handle things that are not Int16. If yes, we're missing a lot of logic. If not, the method should be named IsConvertibleToInt16.
Try-catch should not be used for ordinary control flow. Testing for n != 0 doesn't make sense because the parsed number could be a zero.
Everything here can just be replaced with
The best way to write this method would have been as a thin wrapper around TryParse. In that case, the method saves you from having to declare a temporary variable.
- eugene.yarovoi March 14, 2015