Site icon ashishb.net

File size should always be of “long” type

int getTextFileSize(String fileName) {
  return (int) (new File(BASE_DIR, fileName).length();  // WRONG
}

A 32-bit signed int can deal with ~2GB worth of data. And if your code is not going to deal with files larger than 2GB, why worry? But what if  someone wants to use the same code for a video file some day? Or What if someone writes another code to iterate over all the files in the BASE_DIR directory? Most likely they will be inclined to use int for the final sum as well. Adding integers in most languages results in int and automatic overflows into a negative number (and even worse, back to a positive number). The caller code might think that BASE_DIR does not exist. Therefore, the best future-proofing is to never have file size stored as an integer. Even, Android platform got it wrong with StatFs#getBlockSize and corrected it by adding StatFs#getBlockSizeLong.

Exit mobile version