DEV Community

Discussion on: Don’t Go To Casting Hell; Use Default Native Types in Go

Collapse
 
pinotattari profile image
Riccardo Bernardini

I program in Ada and we (most Ada programmers) have a different view: define your types based on what they actually mean and leave to the compiler the problem of mapping them to native types (unless you have special needs like fitting them into a packet).

For example, a type representing a dice outcome could be defined

type Dice_Outcome is range 1..6;

This says that Dice_Outcome is an integer that assumes values in the range from 1 to 6. What is the underlining native type? Is it a byte (to save space) or maybe an int64 (that the processor handles more efficiently)? I do not know and (in most cases) I do not care. (If I care I can instruct the compiler to do a specific choice)

What about the "casting hell"? Well, my experience is that if you define your types correctly usually you do not have much need for casting. If a function expects as argument a TCP port number and you are trying to pass a Dice_Outcome... Hmmm... the thing is fishy... and it is more probable that you did a mistake somewhere. Sure, every now and then you need conversions, but they are quite rare. Using types with a "meaning" prevents mixing and the necessity of castings.