开发者

Comparing if-else, switch-case and Contains() for performance, readibility and reusebility

I have this below code(this is a sample, there are many more other conditions which Session["Yapilanislem_Popup"].ToString() is different.).

       if (Session["Yapilanislem_Popup"].ToString() == "updatemustericeki")
        {
            KayitGuncelleme();
        }

        else if (Session["Yapilanislem_Popup"].ToString() == "updatemusterisenedi")
        {
            KayitGuncelleme();
        }           

            ///

        else if (Session["Yapilanislem_Popup"].ToString() == "yenitahsilat")
        {
            YeniKayit();
            Session["Yapilanislem_Popup"] = "updatetahsilat";
            BaslikLabel.Text = "Tahsilat Güncelle";
        }
        else if (Session["Yapilanislem_Popup"].ToString() == "yeniodeme")
        {
            YeniKayit();
            Session["Yapilanislem_Popup"] = "updateodeme";
            BaslikLabel.Text = "Ödeme Güncelle";
        }

I want to refactor this code by using a switch-case or Contains() or switch-case and Contains().

For Contains() I think I can do this:

if (Session["Yapilanislem_Popup"].ToString().Contains("update"))
            {
                KayitGuncelleme();
            }
else if(Session["Yapilanislem_Popup"].ToString().Contains("yeni")){
YeniKayit();
                Session["Yapilanislem_Popup"] = "updateodeme";
                BaslikLabel.Text = "Ödeme Güncelle";

}

For switch-case I can basically write it for each case.

Switch-case would be many lines of codes for more conditions of Session["Yapilanislem_Popup"].ToString() however if I use Contains() there will be lesser number of lines of co开发者_运维问答des.

I am also concerned about performance issue.

Which one would be better to use regarding performance, readibility and reusability?


Massive first step, stop doing Session["Yapilanislem_Popup"].ToString() each time, get it once:

string yapPopup = Session["Yapilanislem_Popup"].ToString();

Then use a case statement:

string nextState = yapPopup; // default to no state change

switch (yapPopup)
{
case "yenitahsilat":
    YeniKayit();
    nextState = "updatetahsilat";
    BaslikLabel.Text = "Tahsilat Güncelle";
    break;

case "yeniodeme":
    YeniKayit();
    nextState = "updateodeme";
    BaslikLabel.Text = "Ödeme Güncelle";
    break;

default:
    if (yapPopup.Contains("update"))
    {
        KayitGuncelleme();
    }
    break;
}

Session["Yapilanislem_Popup"] = nextState;

Note that exact matches get their own case, any other logic/testing happens in the default case.

Edit: "It looks like you're writing a state machine" (ala clippy). See use of nextState variable to make it more obvious.


I couldn't help noticing, it is always better to use Convert.ToString(session["value"]) instead of Session["Value"].ToString() as it will handle your null objects as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜