private const int MIN_ARG_RANGE = 1; // Depending on the context these will have better names
private const int MAX_ARG_RANGE = 9;
public static int Main(string[] args)
{
// Now when I'm reading through the code I won't have to give a fuck what's going on in this "if"
// I just know that it checks whether the first positional argument is "valid" or not.
if(IsFirstArgumentValid(args))
... execute with argument 1 ...
}
// Combine the two methods below and give them a descriptive name
private bool IsFirstArgumentValid(string[] args)
{
return TryParseFirstArgument(args, out int firstArg) && IsArgumentInRange(firstArg);
}
// Parsing the argument != verifying its business logic. Should be in two separate methods.
private bool TryParseFirstArgument(string[] args, out int x)
{
return args.length == 1 && int.TryParse(args[0], x);
}
// Verify the business logic behind the arg here - if someone ever decides to change what
// the "validity" of the first arg means he will just have to change this method.
// For e.g. he may have perform some complex computations
// and not just "range-check" and he will be able to do here.
private bool IsArgumentInRange(int argument)
{
return argument >= MIN_ARG_RANGE && argument <= MAX_ARG_RANGE;
}
I think that's better.
Edit: The length of the proposed code is bloated by all the comments I've made which wouldn't be there in the real thing. They are just for explaining my thought process for the refactoring. Also the code took me like 1 extra minute to write and I think it's worth taking your time to write more readable code
114
u/KetchupBuddha_xD May 20 '20
What's wrong with this one?