How to handle units in c++ interface

前端 未结 9 2123
独厮守ぢ
独厮守ぢ 2021-02-07 02:56

I am currently designing an API where I want that the user to be able to write code like this:

PowerMeter.forceVoltage(1 mV);
PowerMeter.settlingTime(1 ms);
         


        
9条回答
  •  一整个雨季
    2021-02-07 03:36

    Before you go crazy with anything more complicated, whenever you write new code that takes a quantity as an argument you should name your methods like this so that it's 100% clear:

    PowerMeter.forceInMilliVolts( ... )
    PowerMeter.settlingTimeInSeconds( ... )
    

    And similarly use variables with the right names e.g.:

    int seconds(10);
    int milliVolts(100);
    

    This way it does not matter if you have to convert, it is still clear what you are doing e.g.

    PowerMeter.settlingTimeInSeconds( minutes*60 );
    

    When you are ready with something more powerful move to that, if you really need to, but make sure you do not lose the clarity of which unit is being used.

提交回复
热议问题