C #: Refactoring the Reynolds number calculator
I am trying to learn some C # over the weekend and am following 15 exercises found here: http://www.jobsnake.com/seek/articles/index.cgi?openarticle&8533
Yesterday I asked a similar question for the Fibonacci sequence and got great answers that brought me into C # elements that I hadn't encountered before: Refactoring the Fibonacci algorithm
Today I would like to see how C # Jedi refactor the following code:
static string Reynolds(int d, int v, int rho, int mu)
{
int number = (d*v*rho) / mu;
if (number < 2100) return "Laminar Flow";
else if (number < 2100 && number < 4000) return "Transient Flow";
else return "Turbulent Flow";
}
It's easier than yesterday, but is there a good way to deal with multiple conventions?
Hello,
Chris
source to share
I think there is a bug in your code, but I made an assumption. Your second "if" will never evaluate the tree as a number <2000 already makes the first branch true.
I would create an ENUM:
enum FlowType
{
Laminar
, Transient
, Turbulent
};
static FlowType Reynolds(int d, int v, int rho, int mu)
{
int n = (d*v*rho) / mu;
if(n < 2000)
{
return FlowType.Laminar;
}
else if(n < 4000)
{
return FlowType.Transient;
}
else
{
return FlowType.Turbulent;
}
}
source to share
Using the C # ternary operator,
static string Reynolds(int d, int v, int rho, int mu)
{
int number = (d*v*rho) / mu;
return number < 2100? "Laminar Flow":
number >= 4000? "Turbulent Flow":
"Transient Flow";
}
or, (to give my sarcastic side a little bit of freedom) if you find it unreadable you can add comments to make it more readable,
static string Reynolds(int d, int v, int rho, int mu)
{
int number = (d*v*rho) / mu;
return /*IF*/ number < 2100? /*Then*/ "Laminar Flow":
/*IF*/ number >= 4000? /*Then*/ "Turbulent Flow":
/*Else*/ "Transient Flow";
}
Does anyone really think this helps?
source to share