[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: [Nbd] [PATCH 1/1] server: remove non-reachable call to err()



On Mon, Mar 11, 2013 at 12:54:04PM +0200, Tuomas Räsänen wrote:
> On Mon, Mar 11, 2013 at 12:28:45AM +0100, Wouter Verhelst wrote:
> > On Sun, Mar 10, 2013 at 11:38:10PM +0200, Tuomas Räsänen wrote:
> > > 
> > > Very well, assert() might be a good idea and I even thought it for a
> > > second or two, but then the pedantic side of me took over. Assert-statements
> > > do burn my eyes, you know.
> > 
> > Why?
> > 
> 
> Just mild allergy, nothing serious.

Heh.

> But seriously speaking, I've just never used to use those. I've always
> seen them as unnecessary cruft, as footprints of Captain Obvious or
> something. But, I do think that explicit is better than implicit, and
> in that light, I think that there might be even some inherent beauty
> in them. I'm glad you asked, made me think.

Assertions are a replacement for a large block of code, really.

If you have a single, 200-line function, where you build a complex data
structure based on configuration etc, and follow that up with processing
that data, then it might be possible to prove mathematically that within
this function, a particular variable can never have a particular value.

As such, you can avoid the branches that would only be needed for those
particular values (because they can never happen, so would be dead
code), and you would be safe in the knowledge that the program will
never crash because you missed those cases.

However, 200-line functions are ugly; you should split such functions
up. But then you have a function boundary where you basically don't know
what's coming in. If someone adds a second call to the "data processing"
function with invalid values (or at least, values that the data
processing function does not expect), then you might end up with nasal
daemons.

Yes, you could add in a huge if block to guard against invalid data, or
you could do it somewhat nicer and use a "goto error" or some such, but
that's still adding in unnecessary code for things that shouldn't be
there in the first place. Instead, you add an assert -- which can be
compiled out easily for optimization, if wanted -- and you're safe. A
sufficiently smart optimizer can also use the assert() statements, fwiw.

> What do you think, should we actually use this kind of assertions more
> often throughout the code base? Now there is only a couple of
> assertions, but the code is full of hidden/implicit invariants,
> waiting to be stated explictly.

I think we should, yes.

-- 
Copyshops should do vouchers. So that next time some bureaucracy requires you
to mail a form in triplicate, you can mail it just once, add a voucher, and
save on postage.



Reply to: