Novikov
Novikov

Reputation: 4489

overloading vs generics or polymorphism

Let's say we're trying to write a helper extension method to add cells for asp.net. Asp.net TableCell controls only have a default constructor and can be a hassle to work with when dealing with highly custom data (disregard the fundamental flaws of this solution not related to the question).

Polymorphic solution

public static void AddCell(this Table table, object cell) {
    TableCell tableCell;
    if (cell is TableCell) {
        tableCell = (TableCell)cell;
    } else if (cell is WebControl) {
        tableCell = new TableCell();
        tableCell.Controls.Add((WebControl)cell);
    } else {
        tableCell = new TableCell();
        tableCell.Text = cell.ToString();
    }
    table.Rows[table.Rows.Count - 1].Cells.Add(tableCell);
}

Question

Would this be better implemented as a generic method, or several method overloads?

Upvotes: 1

Views: 494

Answers (2)

Timwi
Timwi

Reputation: 66614

You should use three overloaded methods, and the third one should take a string instead of an object.

Reasons:

  1. The three overloads make it obvious to the client developer which kinds of data the method accepts.

  2. It is easier to extend the functionality by adding more overloads without breaking existing calls to the methods in client code.

  3. Your current implementation is prone to causing bugs when client developers accidentally pass something they didn’t mean to. Since the parameter is object, the compiler cannot possibly check the correctness of the type. It is better to require an explicit .ToString() on the part of the client to make it explicit that this is what being done.

Upvotes: 4

Chris Thompson
Chris Thompson

Reputation: 35598

This looks more like a case where you'd want to provide overloaded methods. I say that because you're not dealing with a constant interface or something that could be easily applied to generics. That is, what you do with the cell object depends entirely on what it is. To me, it would make more sense to overload the AddCell method to perform different functionality based on the type of parameter. Also, if you're dealing with a finite number of types that you know about at compile time, it just seems to me that working with generics would unnecessarily complicate things.

Upvotes: 1

Related Questions