1

This might seem like a weird question to ask, but is there a convention on how to order arguments in a constructor, and especially where to add arguments the constructor "gains" in subclasses? It seems to me there should be one, after I found myself reading code like this (Code is Groovy, but that's not really relvent to the question):

class Matter {
    double volume
    double mass

    Matter (double m, double v) {
        mass = m; volume = v;
    }
}

class Food extends Matter {
    double nutrition

    Food (double m, double v, double n) {
        super (m,v); nutrition = n;
    }
}

class Apple extends Food {
    double sweetness

    Apple (double s, double m, double v, double n) {
        super (m,v,n); sweetness = s;
    }

}

class GreenApple extends Apple {
    double acidity

    GreenApple (double a, double m, double n, double s, double v) {
        super (s,m,v,n); acidity = a;
    }
}

As I've illustrated above, once we have arrived at GreenApple, any order that might have once been there in the constructor arguments is gone. Note, however, that the programmers did not add their new arguments randomly - the author of Food believed that new arguments should be added in the back, the author of Apple believed that they should be added at the front, and the programmer of GreenApple thought the arguments should be sorted alphabetically, but together, they made the constructors fairly messy (and type safety will be of no use here, these are all doubles).

Coincidentally (well, not really), these are also the three conventions I though there might be. So, my question is now, is there a such a convention, and if there is, what is it? And does it differ between languages?

Callid
  • 79
  • 1
  • 6

1 Answers1

0

To the best of my knowledge there isn't any "hard" conventions like sorting arguments per alphabetical order or something like that. IMHO arguments in constructors or in just any functions for that matter should be sorted from most significant to least significant. Of course that's subject to interpretation but it isn't a problem good communication between team members can't solve.

Indeed, in most cases, I would expect subclasses to not reorder constructor arguments if they still need to be passed from the outside. But there could be very valid reasons to make exceptions.

Crono
  • 10,211
  • 6
  • 43
  • 75