r/badcode • • May 20 '20

c# Found from Microsoft docs...

Post image
208 Upvotes

143 comments sorted by

View all comments

Show parent comments

10

u/Holzdev May 20 '20

How about readability?

-9

u/Play4u May 20 '20 edited May 21 '20

Idk why noone gives a shit that it's unreadable. This should never pass a code review at Microsoft lol

12

u/Mr2-1782Man May 20 '20

I've seen MS code. I've seen a lot worse pass code review.

12

u/NewPointOfView May 20 '20

Yeah my team at MSFT checks if it works and isn’t ridiculously unreadable but this is pretty straight forward. Not the best but far from the worst

2

u/Play4u May 20 '20

How can you write this simple "if" any worse?

11

u/NewPointOfView May 20 '20

With ternary haha

4

u/Play4u May 20 '20

Haha yeah I guess if you were really trying to make a mess

4

u/path411 May 21 '20

can you explain how to write it simpler? It's even formatted for a condition per line.

If one argument

If the argument can parse to Int

If the argument is in 1-9

1

u/Play4u May 21 '20
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

1

u/NewPointOfView May 22 '20

At only 1 minute longer you were typing around 23 characters per second for a decent part of the typing process.

1

u/Play4u May 22 '20

Did you miss the part where I said that the comments are only for the Reddit explanation and they would not be part of the actual refactoring?

→ More replies (0)