I’m writting a C++ library for http clients. I don’t have much experience with programming, so please help me.
I have method named add. It gets two parameters. The first is name of type and second is parameter q. It is a number between 0 and 1 <0,1>. It should have 0 to 4 digits after dot.
I can write it but I don’t know what’s the better:
-
void add(std::string type, double q)-> I must convert q to std::string in body of this method. -
void add(std::string type, std::string q)-> It’s ok, it’s faster but maybe less intuitive for user, because it’s a number (?)….
Is it a good idea, to have two methods: 1) and 2)?
Please help me. I don’t have an experience… I know that two of this methods works but what is better, more popular. What do You think? How would you write this?
Normally you want to make it clear what is expected of the user simply by them taking a look at the method signature. Your code should provide helpful hits to the person who is using it (i.e. make it more obvious what your code is doing and what’s expected of them).
Let’s start with the worst one:
qis supposed to be a number.qis not a very descriptive name.With the above example, the caller may get confused and call the method with reversed parameters:
add("5.0123", "someType")There is nothing telling the user that they did something wrong, until the parameters have to be used. The worst part is that you don’t know where things will blow up now. This may result in some very difficult to track down bugs simply because the proper type wasn’t enforced.Slightly better:
qis still not a descriptive nameI would recommend:
value(which is more descriptive thanq).Now the user can’t call the method with the parameters out of order, i.e.
add(5.0123, "someType"), as it would result in a compiler error. If it’s not obvious: it’s MUCH better to get a compiler error, because it can be fixed immediately. This way you’re making safer code from the ground up.This, of course, means that you’ll have to convert the
doubleto astring, but for the most part it’s a small price to pay given all the benefits outlined above.I don’t know what the value represents, but the more closely you can name the parameter to the “real-world” entity it represents, the better it is.