4 ms·
The example you mentioned, translated in Java, would be: Double mean = 55.50; Double tax = 0.0675; Double tip = 0.15; And the function declaration
by S4M 12y ago
The example you mentioned, translated in Java, would be:
Double mean = 55.50;
Double tax = 0.0675;
Double tip = 0.15;
And the function declaration would be:
Double calc_total(Double meal, Double tax, Double tip)
So even with the types, you have exactly the same problem as in python, and creating a special class to wrap up percentages is something I find quite heavy.
Your alternatives would be to have naming conventions, like you do, or some proper documentation that tells you what the function expects for its arguments, with an example of a function call, which I particularly like in python because of the REPL.
- vilhelm_s 12y agoBut perhaps a better type system can still be helpful. E.g. F# supports units of measure, so you can declare 'dollar' as a unit, and write let calc_total (meal_cost : float<dollar>) (tax : float) (tip : float) = meal_cost * (1.0+tax) * (1.0+tip) This way it is at least clear from the types that the numbers are meant to be multiplied, not added.
- S4M 12y agoI never used F#. In your example, would the code: meal_cost + tax trigger a compiler exception?
- vilhelm_s 12y agoYes, you get The type 'float' does not match the type 'float<dollar>' There is an online typechecker, so one can try out F# without installing it: http://www.tryfsharp.org/Learn/scientific-computing#units-of-measure http://www.tryfsharp.org/Learn/scientific-computing#units-of...
- S4M 12y agoAnd how about: meal_cost * tax ? This one makes sense in the real world, so I suppose an advanced type system allows the programmer to specify what operations are legit or not across different types.
- vilhelm_s 12y agoOne could imagine systems for that, but units of measure doesn't do any customization of different operations. It's just unit checking for for arithmetic, like in high-school math.
- squeaky-clean 12y ago> So even with the types, you have exactly the same problem as in python, and creating a special class to wrap up percentages is something I find quite heavy. Yep, I agree completely and was hoping to make that point. The typing makes it clear that meal is going to be a single price, and that tip won't be a String or something unexpected, but it is still unclear whether it is a percentage or a amount. I guess what I mean to say is that while static typing certainly helps, it isn't the be-all and end-all of code clarity, and descriptive names can really help code readability regardless of your typing system. Also, admittedly the example I provided is rather simple. And in any language, you should be using a proper Currency type or library when dealing with money, which would make most of my argument moot: Currency calc_total(Currency meal, Double tax, Double tip) And now specifying tax and tip as percentages isn't necessary. But not all examples are so friendly!