Hacker News new | ask | show | jobs
by patrick451 1580 days ago
I'm not really a fan of this pattern in python. As far as I can tell, it's all done in the name of duck typing: if the returned object appears to have the right property, that's good enough. But the problem comes when take that object and pass it on to some other function. It may have appeared like a duck to you, but 10 functions later, it's slightly off and you get a difficult to understand TypeError or AttributeError.

Where I do think this pattern makes sense is in trying to use system resources. Checking that a file exists or a process is alive before deleting or killing it is a recipe for difficult to track down Time of Check to Time of Use bugs. I'm curious if you think this is also an anti-pattern in c++ and if so, how you properly deal with the TOCTU race conditions?

1 comments

In C++ I would consider the best option in those cases would be for the function that performs the operation to return an error rather than throw an exception. That way you avoid the race condition, but also don't have to worry about the overhead of calling it in a tight loop.

If the library you are using does throw exceptions, then I would probably start with just using exception handling. Then if I notice poor performance, add an initial check, purely as an optimization, while keeping the exception handling to deal with race condition.