1

I am looking for help to see if there is any better way to write code. I need to instantiate different implementation based on some value, but somehow I feel that I can write xyz property in more generic way

Here is the simple representation of my code

public class A
{
    string p1;
    IEnumerable<B> b;
}

public interface Ix
{
    ...
}

public class x1 : Ix
{
     ...
}
public class x2 : Ix
{
    ...
}

public class C
{
    public C()
    {
        _a = GetA();
    }

    public List<Ix> xyz
    {
        get
        {
            if (_a.b == "sometype")
            {
                return _a.b.ToList().Select(r => new x1(r) as Ix).ToList();
            }
            else
            {
                return _a.b.ToList().Select(r => new x2(r) as Ix).ToList();
            }
        }
    }
}

Please let me know if I can write xyz property in better way?

Thanks in advance.

Praveen
  • 13
  • 2
  • *"I need to instantiate different implementation based on some value"* - This is the [Factory Pattern](http://stackoverflow.com/q/10513086/119527). – Jonathon Reinhart Jun 26 '15 at 16:10
  • It looks to me like the creation of this list is the responsibility of `A` and it could do this polymorphically rather than via a 'flag'. Though the example is a bit contrived (and doesn''t compile), so it's a bit hard to tell. – Charles Mager Jun 26 '15 at 16:11
  • This may not be the best place to ask this, you should probably try http://codereview.stackexchange.com/ – David Watts Jun 26 '15 at 16:12

1 Answers1

0

You are making multiple lists for this, I suggest doing:

return _a.b.Select(r => new x1(r) as Ix).ToList();

but ideally, you'd do something like this:

public IEnumerable<Ix> xyz
{
    get
    {
        Func<..., Ix> factory = _a.b == "sometype" ? (r => new x1(r)) : (r => new x2(r));
        return _a.b.ToList().Select(factory);
    }
}
Ryszard Fiński
  • 452
  • 3
  • 7