justiceorjustus
justiceorjustus

Reputation: 1965

Calling one overloaded method from another to build ViewModel C#/ ASP.NET MVC

Semi-new to ASP.NET MVC and programming in general. I have a method which builds a ViewModel that I use in most of my other Views and has two overloads. I wanted to call the first overload from the second overload to be more efficient, so I did this:

public HeaderViewModel BuildHeaderViewModel(int? chainId, int? sheetId)
{
    HeaderViewModel header = new HeaderViewModel();

    header.ChainName = db.Chains.Find(chainId).Name;
    header.SheetName = db.Sheets.Find(sheetId).Name;
    header.SheetDescription = db.Sheets.Find(sheetId).Description;

    return header;
}

public HeaderViewModel BuildHeaderViewModel(int? chainId, int? sheetId, int? fileId)
{
    HeaderViewModel header = new HeaderViewModel();

    header = BuildHeaderViewModel(chainId, sheetId); // calling first overload

    var fileDetails = db.FileDetails.Find(fileId);
    header.SheetFileName = fileDetails.Name + fileDetails.Extension;

    return header;
}

My question is, is this the correct / most efficient way of doing this? Any input would be appreciated.

Upvotes: 1

Views: 143

Answers (2)

D Stanley
D Stanley

Reputation: 152626

Actually, the typical way to use chain overloads is to have the majority of the logic in the most specific one and deal with optional values appropriately:

public HeaderViewModel BuildHeaderViewModel(int? chainId, int? sheetId)
{
    return BuildHeaderViewModel(chainId, sheetId, null);
}

public HeaderViewModel BuildHeaderViewModel(int? chainId, int? sheetId, int? fileId)
{
    HeaderViewModel header = new HeaderViewModel();

    header.ChainName = db.Chains.Find(chainId).Name;
    header.SheetName = db.Sheets.Find(sheetId).Name;
    header.SheetDescription = db.Sheets.Find(sheetId).Description;

    if(fileId.HasValue)
    {
        var fileDetails = db.FileDetails.Find(fileId);
        header.SheetFileName = fileDetails.Name + fileDetails.Extension;
    }
    return header;
}

The main difference is that your current method does nothing different if fileId is null, which may be OK, in which case you can take the null check out of the overload.

Upvotes: 3

MavisBeacon
MavisBeacon

Reputation: 48

I don't think there is anything wrong with calling a method from another overload version of it - I've seen it done, and was able to see the intention pretty easily.

You are basically saying "If I have the fileId, I'd like to also initialize the FileDetails object, too!"

Makes sense to me :)

Upvotes: 0

Related Questions