none
Instantiating objects pattern RRS feed

  • Question

  • Hi,

    Here is my test code, I am trying to figure out best practice for the following code:

    public class A

    {

    private B b;

    public A() {}

    public void SetB(B b)

    {

    this.b = b;

    }

    public void AMethod()

    {

    if(b == null)

    {

    b = new B();

    }

    b.DoSomething();

    }

    }

    I need help figuring out the best practice to check the member variable B(if it is already instantiated through SetB then use it , if not then instantiate it as in MethodA. Is there is better way(design pattern etc) of doing it. An example would be great.

    Thanks

     


    Wednesday, July 25, 2012 7:05 PM

Answers

  • If you are concerned with object creation of B, you can create it outside the class, and send it as parameter to methods in class A. If you feel creating an object every time is an overhead, you can use prototype pattern. 

    • Marked as answer by itswcf Thursday, August 2, 2012 10:55 PM
    Thursday, July 26, 2012 11:12 AM

All replies

  • If your class relies on an instance of B, make an instance of B a parameter to the constructor of A, and null check it as it comes in (e..g, new A(null) should throw an ArgumentNullException).

    Generally, if an instance of a class requires member properties (or fields) to be set before it can be used, make those values constructor arguments.

    Evan

    Wednesday, July 25, 2012 8:54 PM
  • Thanks for reply. I tried your solution, but here is another issue that I am seeing now. Class A has other methods too like AMethod1(), AMethod2() etc which does not use B. So in case where I use class A just for using AMethod1() or AMethod2, in that case constructor parameter solution may not be optimal. As in that case, B is not being used but just being checked and instantiated.

    Thanks

    Wednesday, July 25, 2012 10:15 PM
  • If you are concerned with object creation of B, you can create it outside the class, and send it as parameter to methods in class A. If you feel creating an object every time is an overhead, you can use prototype pattern. 

    • Marked as answer by itswcf Thursday, August 2, 2012 10:55 PM
    Thursday, July 26, 2012 11:12 AM