Jeremie Pelletier:
> I also made a simple D script to rename all c files to cpp:
Generally I suggest to use a scripting language to do a similar task (or a
simper linux shell script, probably one or two lines), but I agree that doing
this I can't see possible faults/troubles of the same D code. So in the end
writing it in D is a good experiment.
You are probably an expert programmer, yet in your script I see some things
that in my opinion are better done in other ways:
- Don't init things to void unless your performance experiment tells you to,
and do it with care. This is explained in D documentation too. The speed gain
is very limited and the risk of giving false pointers to the conservative GC is
present, because currently it's not very precise.
- Gotos aren't evil, but it's better to use them only as performance
optimization or for tricky flows of the code. Generally in D there are better
ways to solve such problems. For example you can just throw an exception if
args.length!=2, and the uncaught exception will show an error message to the
user and the code will stop.
- try ... catch(FileException) {} looks not nice.
- if(de.name[$-2 .. $] == ".c") is a bit unsafe, because unlike Python D slices
aren't saturating (and in the meantime I have asked to the Python developers,
they have told me that this design is desired in Python, it's not a design
mistake left for backward compatibility as someone here told me. And it's a
very handy thing. The only advantage of the way D slices are done is that D
ones are a bit faster. But their unsafety unnerves me and forces me to write
uglier and longer code). Generally it's better to use string functions, that
are safer. Python has endswith() and startwith() string methods that in D (as
functions) are even more important.
- In D the main doesn't need to return an int in an explicit way. If your
program stops because you have thrown and exception, I think the return value
is not zero.
- Generally don't use this: printf("Usage: %.*s <path>", args[0]); printf() is
good mostly to speed up output if you have to print tons of things, or in
debugging write* functions, or for a simple compatibility with Tango. Generally
use writeln or writefln.
- Unless performance is critical, it's generally better to write script-like D
programs in a high-level style, because in such kind of programs the purpose is
to write the code quickly, to have readable code, and most of all to have the
most reliable code as possible. In such small programs saving microseconds is
usually not positive.
- Note for D developers, listdir() desiged like that isn't good. Python too
used to have something similar (os.path.walk()), but it's better to invent its
design, and give an interable that instead yields the nodes of the tree
(os.walk() from Python 2.3).
Bye,
bearophile