gazeranco
gazeranco

Reputation: 55

Is it ok to call the method again from inside the method?

Is this ok, I feel like its not right, like im doing a "GOTO", is this ok?

private void myCopySpecial()
{
    TSMUI.Picker myPicker1 = new TSMUI.Picker();
    Component c1 = myPicker1.PickObject(TSMUI.Picker.PickObjectEnum.PICK_ONE_OBJECT) as Component;

    TSMUI.Picker myPicker2 = new TSMUI.Picker();
    Beam fromBeam = myPicker2.PickObject(TSMUI.Picker.PickObjectEnum.PICK_ONE_PART) as Beam;

    if (c1 == null)
    {
        MessageBox.Show("That's not a component? Try again.");
        //User selected something other than a component, start again.
        myCopySpecial();
    }

Upvotes: 0

Views: 1385

Answers (1)

CodeCaster
CodeCaster

Reputation: 151720

It would take a very persistent user to let this method throw a StackOverflowException, but the possibility is there. That's because this design introduces a type of recursion that you, as a programmer, don't have control over.

A simple while loop will suffice:

private void PickComponent()
{
    Component c1 = null;

    while (c1 == null)
    {
        TSMUI.Picker myPicker1 = new TSMUI.Picker();
        c1 = myPicker1.PickObject(TSMUI.Picker.PickObjectEnum.PICK_ONE_OBJECT) as Component;

        if (c1 == null)
        {
            MessageBox.Show("Please select a component.");
        }
    }
}

Or refactor it altogether into a method that actually picks the component and keeps prompting the user if they don't pick a component:

private Component PickObjectAsComponent()
{
    Component pickedComponent;

    do
    {
        TSMUI.Picker myPicker1 = new TSMUI.Picker();
        pickedComponent = myPicker1.PickObject(TSMUI.Picker.PickObjectEnum.PICK_ONE_OBJECT) as Component;

        if (pickedComponent == null)
        {
            MessageBox.Show("Please select a component.");
        }

    } (while pickedComponent == null)

    return pickedComponent;
}

Then from your code, you can simply call this method:

Component pickedComponent = PickObjectAsComponent();

I don't know how TSMUI.Picker.PickObject() can let the user cancel picking a part, because now this method won't exit until the user does pick one. I can imagine that they will regret starting this action in a workspace that doesn't contain any components.

Upvotes: 5

Related Questions