I'm studying the structures of libraries currently. I want to learn how good programmers write code, what are the strategies they follow, the art the programmer followed to develop the library. And how important the library should be written in the well arranged form.
But as I'm go back and forth into the library over and over, I really need to understand, the way the programmer followed, and the reasons behind the applied strategy.
The example I'm studying now is the HMC5883L and how the programmer used the Wire library to manage the developing the library. This should be quite easy for experienced programmers, but I'm really studying the concepts, strategies .. etc.
As I'm going over and over I have different questions, so to start this discussion I want to begin with this question about the programmer writing two very similar functions that pretty much do the same thing.
// Read byte to register
uint8_t HMC5883L::fastRegister8(uint8_t reg)
{
uint8_t value;
Wire.beginTransmission(HMC5883L_ADDRESS);
#if ARDUINO >= 100
Wire.write(reg);
#else
Wire.send(reg);
#endif
Wire.endTransmission();
Wire.requestFrom(HMC5883L_ADDRESS, 1);
#if ARDUINO >= 100
value = Wire.read();
#else
value = Wire.receive();
#endif
Wire.endTransmission();
return value;
}
// Read byte from register
uint8_t HMC5883L::readRegister8(uint8_t reg)
{
uint8_t value;
Wire.beginTransmission(HMC5883L_ADDRESS);
#if ARDUINO >= 100
Wire.write(reg);
#else
Wire.send(reg);
#endif
Wire.endTransmission();
Wire.beginTransmission(HMC5883L_ADDRESS);
Wire.requestFrom(HMC5883L_ADDRESS, 1);
while(!Wire.available()) {};
#if ARDUINO >= 100
value = Wire.read();
#else
value = Wire.receive();
#endif
Wire.endTransmission();
return value;
}
Update:
Actually, the programmer used the 1st version only in the HMC5883L.begin();
function, but why?
if ((fastRegister8(HMC5883L_REG_IDENT_A) != 0x48)
|| (fastRegister8(HMC5883L_REG_IDENT_B) != 0x34)
|| (fastRegister8(HMC5883L_REG_IDENT_C) != 0x33))
{
return false;
}
Everything else in the library used the 2nd version.
So, basically the two functions are to read a specified register in the HMC5883L, my questions:
- what is the difference? I know that there's an extra care has been put into the second function, but why ?
- Is it so important ?
- Are there situations that require any version of the functions ?