[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: how to prevent bugs without static type checking?
- From: William Ahern <william@...>
- Date: Mon, 22 Oct 2012 22:38:51 -0700
On Tue, Oct 23, 2012 at 12:07:11PM +0800, 乙振斐 wrote:
> Without static type checking, we may send wrong parameters to a function
> and we cannot find this mistake until the program crashes in run time.
> But if it is a huge program, we are not able to cover 100% codes in test,
> in this situation ,how can we prevent this problem?(say, pass wrong type
> parameters to a function)
The size of the program doesn't matter unless you're trying to add tests to
existing code. For new code, as long as you write tests at the same time you
write the code, then it's not a problem.
It's like washing dishes. If you leave them to pile up, it's a chore. If you
wash the dishes right after you use them, it's not much trouble.
But you should design your code with run-time errors in mind, e.g. by
checking for pcall failures. You should make catching, reporting, and
debugging errors easier to do at run-time, instead of relying on the
compiler or post-mortems.
There are other techniques. In a recent library I had to deal with optional
timeouts. I used a pattern like:
function foo(query, timeout)
local deadline = timeout and timeout + monotime()
...
if deadline then
...
There are two pertinent characteristics here. First, I can pass nil or false
as `timeout', and it'll just work--it's a little lenient with the type.
(Note also that the arithmetic operation will coax number strings into
number values.)
Second, if `timeout' is the wrong type it fails early in the function, and
unconditionally. If someone passes the wrong type it'll blow up sooner
rather than later. That often makes any bug more likely to be caught during
QA testing.
I'm sure other people have similar patterns and habits.