How useful it could have been if...

| 4 Comments

I'm writing tests for some code. I have a function that I'm testing that looks something like this:

bool CAsyncSocket::Read(bool throwOnFailure = false);

If C++ allowed us to overload a function call based on return type then we wouldn't need the horrible throwOnFailure wart and the compiler could pick the right version depending on if we try to use the return value or not... So a call like this: bool ok = pSocket->Read(); would return errors and a call like this: pSocket->Read(); would throw exceptions...

I know why C++ doesn't support overloads on return type and I accept that the above could be confusing but...

I suppose the way around it is to call the functions different things;

void CAsyncSocket::Read();
bool CAsyncSocket::TryRead();

Hmm... Undecided...

4 Comments

I definitely prefer the second way. Passing in flags that say, "behave as if you are a different function" are one of my pet peeves. If it's a different function, write a different function. IMO it's easier to read that way. Otherwise, next year when you look at:

socket.Read(true);

you have to go peek at the source to remind yourself what that "true" means.

Eddie,

Yeah, I agree. If someone else had wrote the code that way I'd have jumped on them ... Sometimes I just need a kick when it's me that wrote the code originally ;) Thanks for kicking, I've just adjusted the code.

Interestingly the change to the function interfaces didnt affect any of the calling code, none of the call sites were saying "throw when there's an error" and none of them were testing the return value either :(

The new version of the functions are of the form void DoThing() and they throw on failure... All the tests pass, I guess the codebase just got fractionally easier to understand...

Glad I could be of service. :)

I find that it's worthwhile to fix even the little things like that. It's like the "No Broken Windows" philosophy from The Pragmatic Programmer - you don't want to create a culture where it's okay to overlook "minor" problems.

Of course, I'm much better at telling other people to do that than I am at doing it myself...

I agree re the "No Broken Windows" thing; it's just this time I was having difficulty accepting that it was a problem. It's interesting that now that I've fixed and simplified those calls I have noticed a few other places where some cleanup would be useful...

Leave a comment