Raghav
Raghav

Reputation: 9630

Custom collection question

I have a CustomerRepository class (in my BL), and I am returning a collection as follows:

 public static ICollection<Customer> FindCustomers()
    {
        Collection<Customer> customers = null;
        try
        {
           customers = DAL.GetCustomers();             
        }
        catch (Exception ex)
        {
            //log and re-throw exception here
        }
        return customers;
    }

I have a few questions on this:

  1. Is the try/catch block ok?
  2. I am creating the collection outside try, and returning it outside catch.

Am I overlooking any best practices here?

Would love to know about potential gotchas here :)

Upvotes: 0

Views: 212

Answers (4)

ShuggyCoUk
ShuggyCoUk

Reputation: 36438

This is fine (and idiomatic)

public static ICollection<Customer> FindCustomers()
{
    try
    {
       return DAL.GetCustomers();         
    }
    catch (Exception ex)
    {
        //log and re-throw exception here
    }
}

I would add that returning IQueryable (or if not feasible IEnumerable) is probably a better idea so as to give your class more wiggle room in future as to how the data is arranged.

Upvotes: 3

Vivek
Vivek

Reputation: 440

If you are doing some processing inside try, then declare your returning objects outside try and return them outside catch. So I think what you wrote is correct.

I think if you use more specific interfaces (like IEnumerable<>) then your consumers (or upper layers/tiers) might have problems using your collection classes. They might need to add more work (like IEnumerable does not support the Count property). Using ICollection<> or even Collection<> should also be ok.

Upvotes: 0

Raghav
Raghav

Reputation: 9630

What would happen if suppose an error comes in try block before return statement, as in below code i am manually throwing a exception and compiler is warning me at return h; line that it is unreachable code.

 public int Test()
        {
            try
            {
                int h = 0;
                h = 100;
                throw new Exception();
                return h;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

Is it ok to have such warnings?

Upvotes: 0

Arsen Mkrtchyan
Arsen Mkrtchyan

Reputation: 50712

public static ICollection<Customer> FindCustomers()
{
        try
        {
           return DAL.GetCustomers();
        }
        catch (Exception ex)
        {
            //log here
            throw;
        }
}

I think this is better version

Upvotes: 3

Related Questions