Eof - to return or to throw?

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Mon Feb 12 17:16:47 PST 2007


Dawid Ciężarkiewicz wrote:
> I've just asked Kris why mango is not throwing Eof in it's I/O operations
> instead of returning it.
> 
> After short discusion he told me to ask about your opinons on NG (probably
> to stop me from distrupting him ;) ).
> 
> So here am I.
> 
> Two versions of same functionality.
> 
> SomeIOClass {
>    /* throws Eof, 0 == nothing available */
>    return uint readWithThrowingEof(void[] buf);
> 
>    /* -1 == eof, 0 == nothing available */
>    return int  readWithReturningEof(void[] buf);
> }
> 
> 
> Which is better?
> 
> I've always thought about returning Eof as an workaround when you can't
> throw it or it is too costly. Like in C.
> 
> I mean:
> 
> try {
>    auto amount = io.readWithThrowingEof(buf);
>    useData(buf, amount);
> } catch (Eof e) {
>    /* do smth */
> }
> 
> Isn't any worse than:
> 
> auto amount = io.readWithReturningEof(buf);
> if (ammount >= 0) {
>    useData(buf, amount);
> } else if (ammount == -1) {
>    /* do smth */
> }

In fact, the first one better. But only because the lack of typos :P. 
(ammount != amount)

> 6 lines vs. 6 lines
> 
> But when dealing with multiple reads, try block is _much_ better. In ideal
> situation you can only have one try {} catch {} and just read, use, read,
> use etc. I can come with many examples where catching/throwing Eof is more
> flexible both for implementator and library user and the difference is BIG.
> Especialy in D with great exception support.
> 
> But are there cases where readWithReturningEof is better? Can someone give
> me a snippet that we could discuse on? I really have no idea where
> returning magical value Eof could be more handy than throwing it.

You say multiple reads is much better with a try block? (And you use 
line count as a metric?)
Let's read until end of file:
---
int amount;
while ((amount = io.readWithReturningEof(buf)) != EOF) {
	useData(buf, amount);
}
---
vs.
---
try {
	while (true) {
		auto amount = io.readWithThrowingEof(buf);
		useData(buf, amount);
	}
} catch (Eof e) {
}
---
4 lines vs 7 lines, and one less indentation level when not using try 
blocks.

I prefer the first one.



More information about the Digitalmars-d mailing list