Thomas Doyle
Thomas Doyle

Reputation: 113

How do I prevent code duplication when defining multiple methods with the same name?

I recently discovered that you can define multiple methods with the same name as long as their arguments differ (I believe it's called method overloading). So for example, in a script I have a method called getDate(int date) and another called getDate(). The only differences between these methods is that the one that doesn't accept an argument uses a static integer defined in the class instead of the date argument.

I've used this logic for at least 5 different methods in the class, however it seems very messy to be duplicating code like this. Is there a more elegant solution?

Upvotes: 1

Views: 1566

Answers (2)

Typically, its best to have one function that does the meat of what you're trying to achieve, while others invoke that function (or each other) to avoid duplicating actual logic.

I'll use your example:

Date GetDate(int date) {
    // -- do whatever you do here
    return DoAThing(date);
}

Date GetDate() {
    return GetDate(staticVar);
}

This way, if you want to change how you get a date, you won't have to change your code in multiple places, and when you modify GetDate(int date), your other functions that invoke it will simply follow suit.

Upvotes: 2

Paul Atréides
Paul Atréides

Reputation: 51

Just call the methods as needed e.g.

//To Get the Date normally
DateTime date = getDate();
//Otherwise
date = getDate(1, DateTime.Today);

You should not have a problem calling them. They should be overloaded correctly by unity because I checked it with my editor.

Upvotes: -1

Related Questions