In Kotlin or Java we have many different types: integer, byte, double, long, float, string, character, etc.
But one can use an integer instead of byte, and a double instead of an integer.
Why we need all those different type? Why we can’t just have a double, and forget about integer, byte, float, etc.?
5
Under the hood, everything is an array of bytes, so why do you need anything else?
Different types make the code simpler and make it easier to reason about the code. They avoid errors. They save memory. They document the interface. Here’s a method: resetCounter(double value)
. Tell me, are values 23,768 and 0.5 valid as arguments? Or will the method crash? Now what if the signature is rather resetCounter(short value)
?
Imagine you have a stream of bytes (a binary file, for instance). Your suggestion is to forget about bytes, and use doubles instead. Well…
-
Double is 64 bits long, versus 8 bits for a byte. This means that your stream will be eight times bigger, for no benefit whatsoever. Imagine that you need to download eight gigabytes in order to get your one gigabyte file. Why would you want to do such a thing?
-
Something, somewhere, may assign a value such as 7,502 to a the byte (that you decided to replace by a double). What would happen when you try to compress the stream? Or pass show it as an image on the screen? What if the value is 7,502.3333333333?
-
Do you think somebody who will maintain the source code will know, automatically, that all the values should be within the -128..127 range, or that one shouldn’t do floating point operations on them? How?
-
At some point, you need to verify that the stream starts by 0xC49F02. Write the code which would do that. How easy/difficult it is, compared to the similar code for the stream of bytes? How confident are you that the code is correct? How many tests did you write? What tests are here just because you used double instead of a byte?
1