foreach

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Tue Jun 17 09:44:15 PDT 2014


On Tue, Jun 17, 2014 at 07:59:22AM +0000, monarch_dodra via Digitalmars-d wrote:
[...]
> We recently did some cleanup in our organization in regards to a
> couple functions whose argument counts were are too damn high: We
> created a helper-class which actually contains the arguments. So the
> calls now look like:
> 
> Arguments arg;
> arg.InputSize = 5;
> arg.method = ASSSENDING;
> fun(arg);
> 
> It might look like bloat initialy, but it makes things *WORLDS*
> easier. For starters, the arguments are *all* named, even at call
> sight. Second, any un-specified argument has its default value, even
> if there are other arguments you want to modify later.

+1. I've actually done that in D before. Basically, instead of having
unending argument lists to 15 related functions (because they call each
other with one or two arguments changed but the rest remain the same),
factor out the arguments into a context struct that contains them, then
just pass these structs between the functions, updated as necessary. For
medium-length argument lists, this works very well because they retain
by-value semantics, so all you have to do is to refer to ctxt.param17
instead of param17. For even longer argument lists, you could consider
using struct pointers instead, or just outright classes (but if you have
to go that far, I'd say something is very, very wrong with your code
design! :P).

Better yet, once you've factored out function arguments this way, it's
easy to add new parameters without needing to update the signature of 15
functions (and have 15*n opportunities for screwing up when a typo
causes the accidental permutation of the last few arguments in each
updated call).


> That said, there might have been better approaches to not fall into
> this trap in the first place, but that's an (arguably) low cost sanity
> patch.

Well, I'd say that if you start having a group of functions that all
take more-or-less the same super-long list of parameters, that's a
strong indication that you should really make them methods of a struct
or class that contains those parameters as fields. :)


T

-- 
Stop staring at me like that! It's offens... no, you'll hurt your eyes!


More information about the Digitalmars-d mailing list