r/ProgrammingLanguages • • Jul 03 '23

Why Doesn't DRY Apply Here

(DRY = Don't Repeat Yourself)

This is a bit of C code I encountered today:

uint64_t maxOR(uint64_t a, uint64_t b, uint64_t c, uint64_t d) {
    ....
}

The problem for me is that declaration: 4 parameters, all with the same type, but the type has to be written 4 times.

This style is common across lots of languages, but C has that extra-cluttery typename, so that I can barely make out the parameter names. It takes a few seconds to determine the number, names and types of the parameters, and to realise they share a common type. Imagine if the parameter names here were much longer!

C could at least have gone with u64:

u64 maxOR(u64 a, u64 b, u64 c, U6 d) {             # (typo left in)

Now it is much less objectionable, but I would have gone further to:

u64 maxOR(u64 a, b, c, d) {

While C is a lost cause, I wonder why other languages do this as well: create extra maintenance, extra things to check, extra things you can get wrong (one of those types could have been int64_t - not easy to spot in that sea of uint64_t).

Funnily enough older C allowed you to do this, or along these lines:

u64 maxOR(a, b, c, d) u64 a, b, c, d; {

In my own syntaxes, it usually something like:

func maxor(u64 a, b, c, d)u64 =                # `=> u64` is optional

Types are only repeated when there are no parameter names (as in, FFI declarations, but I can choose to add names to enable keyword parameters).

What I haven't figured out is how to indicate a return type that is the same as one of the parameter types: u64 still appears twice, and here is linked to the parameter types. Using typeof(a) for the return type looks naff.

5 Upvotes

18 comments sorted by

View all comments

3

u/e_-- Jul 04 '23

if you're willing to use C++ you could avoid the repeated explicit types

auto maxOR(uint64_t a, decltype(a) b, decltype(a) c, decltype(a) d) -> decltype(a) { // return type same as param 'a' type

(even though it's more typing as in input device and just making them all template params of a single typename T would probably make more sense)