Cleanest way to get value from secondary form [closed]

Posted on

Problem

I’ve written a simple program that reads barcodes from a page and will ask the user to select one to use. I have a few methods that use the results of that form and I was wondering if there is a better/cleaner way to execute the following code:

string barcode = "";    

if (barcodes.Count > 1)
{
    using (var form = new frmSelectBarcode(barcodes))
    {
        if (form.ShowDialog() == DialogResult.Yes)
        {
            barcode = form.getSelection();
        }
    }
}

//Do other things

I feel like it’s fairly clean, but I don’t like that there’s 3 levels of indentation and I’m not sure if that should be necessary.

Solution

Let us going through your code

  • better assign String.Empty than “” to a variable your aging eyes will thank you in a few years.
  • objects should be named using PascalCase casing
  • public methods should be named using PascalCase casing as well

I would add a Public static string GetBarcode(List<Barcode> barcodes) method to your frmSelectBarcode class like so.

Public static string GetBarcode(List<Barcode> barcodes)
{
    if (barcodes.Count <= 1)
    {
        return string. Empty;
    } 
    using (var form = new frmSelectBarcode(barcodes)) 
    { 
        if (form.ShowDialog() == DialogResult.Yes)
        { 
            return form.getSelection(); 
        } 
    }
    return string.Empty;
}

In this way you have only one place where you need to maintain the code and it’s quite easy to call where ever you need the result like so

string barcode = frmSelectBarcode.GetBarcode(barcodes) ;

Leave a Reply

Your email address will not be published. Required fields are marked *