tags:

views:

60

answers:

2

I want to extract the guard statement from the following method

private void CreateProxy()
    {
        //extract the following guard statement.
        Host selected = this.comboBox1.SelectedItem as Host;
        if (selected == null)
        {
            return;
        }


        this.SearchProxy = ServiceProxy.ProxyFactory.CreateSearchProxy(GetSelectedIP().ToString());
        this.StreamProxy = ServiceProxy.ProxyFactory.CreatePlayerProxy(GetSelectedIP().ToString());
    }

     //extracted guard method
     public bool IsHostSelected()
     {
        Host selected = this.comboBox1.SelectedItem as Host;
        if (selected == null)
        {
            return false;
        }
        return true;
     }

see? now i have to add return value for the extracted method, is this kinda ugly?

any better solution to avoid adding the return value for the extracted method?

+1  A: 

any better solution to avoid adding the return value for the extracted method?

Yes:

 //extracted guard method
 public bool IsHostSelected()
 {
    Host selected = this.comboBox1.SelectedItem as Host;
    return selected != null;
 }
OscarRyz
my point is not the return true/false statement. it is i have to add return value to the extracted method. maybe this is not big deal at all.
Benny
+1  A: 

I don't see the big deal. First, I would rewrite it as:

static bool SelectedItemIsHost(ComboBox box)  { 
    return box.SelectedItem is Host;
}

Note the rename, the ComboBox as a parameter, and the body change.

Now, this makes your code read more clearly:

void CreateProxy() {
    if(SelectedItemIsHost(this.comboBox1)) {
        this.SearchProxy = ServiceProxy.ProxyFactory.CreateSearchProxy(GetSelectedIP().ToString());
        this.StreamProxy = ServiceProxy.ProxyFactory.CreatePlayerProxy(GetSelectedIP().ToString());
    }
}

So now it reads "if the selected item is a Host then do stuff."

Now, this goes way beyond your question, but this looks like a big coupling of UI logic and domain logic. You might want to reconsider a decoupling there.

Jason
yes. i am aware of the coupling.
Benny