We help IT Professionals succeed at work.

OOP best practices using .NET

rufustmac used Ask the Experts™
I am fairly new to OOP so I am asking for advise as I develop my program to make sure I understand what I am doing.

Is it better to completely initialize a class via it's constructor and then use it's properties to supply it's methods with values?  For example if I have ClassA and I create an object of classB inside ClassA, should I use classB(object initilzer) and then inside classB call it's own methods using this.methodName() and use the properties of the local class to provide values?  Or, should each function of the class accept parameters from calling classes to initialize it's local variables?
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
From what I've been taught and read, it really depends on what you are doing and what makes the most sense. Not the most scientific answer, but it is what it is. For instance, if you are just manipulating values, properties make sense. If you are (or reasonably may be in the future) performing actions with it, using methods makes sense.

As for doing it in the constructor or via methods, it also depends. Generally, anything that will completely fail because it is not using a value valid should be required in the constructor, if possible. It's pretty much a way to hep ensure the person using the object doesn't try to perform an action without having first supplied enough valid parameters to at least have a shot of moving forward. Some people will disagree and say always having a construction without any parameters is better - not wrong either.
I prefer to keep my objects in a valid state at all times.  The way to do this is to have constructor(s) that include required values, with some possibly automatically initialized.  

E.g. for a CheckingAccount class, I might have two constructors - one that takes an accountNumber and a balance and one that takes just an accountNumber (with the balance defaulting to zero).  For this example, I would not have a setter for the balance - just a getter.  The balance would be affected by other methods, such as withdraw and deposit.

I'd recommend that you also use lazy initialization where appropriate.  This means that when first accessed, the attribute value will self-initialize as needed.