What is the best way to code a method overloading?

Valentin :

I am a computer science student and I am currently working on methods overloading.

I did a method overloading to get a random number with differents parameters: low bound and high bound or only low bound.

Is it better to do:

/**
 * Return a random double in [low; sup[
 */
public static double getDouble(int low, int sup) {
    return low + Math.random() * (sup - low);
}

/**
 * Return a random double in [0; sup[
 */
public static double getDouble(int sup) {
    return getDouble(0, sup);
}

Or, have I to do:

/**
 * Return a random double in [low; sup[
 */
public static double getDouble(int low, int sup) {
    return low + Math.random() * (sup - low);
}

/**
 * Return a random double in [0; sup[
 */
public static double getDouble(int sup) {
    return Math.random() * sup;
}

In brief, my question is what way is the best between both? Thank you.

GhostCat salutes Monica C. :

One of the real big problems in software development is code duplication.

You absolutely always strive to minimize identical segments of code.

Sure, in your examples, it is almost irrelevant which version you choose. If your code would just be that, and would never be touched again, both options are readable and fine.

But chances are that things need to be enhanced or changed over time. And then option 1 requires you to pay a little bit less of attention and diligence. Thus you go for that one.

Also note that it is perfectly fine to think about such subtleties. Not because this specific example is so critical, but to train that skill. So that you are ready and prepared come the day when you have to write code of higher complexity that doesn't fit in 10 lines!

And yes, this isn't specifically tied to overloading. As said: minimizing code duplication should always be one of your highest priorities. Sometimes you have to compromise, but you do so as conscious decision, not out of a lazy mood or impulse.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=113827&siteId=1