pass argumenting constructor vs methods

When is it best to pass an argument through a constructor rather than a method?

What is it exactly that makes you think to use the constructor rather than a method?


In some languages (such as C# and Java), the constructor is the only place where readonly/final fields can be initialized. Thus, constructors with parameters are often used with classes which are at least partly immutable. The KeyValuePair<,> class in C# is an example of this.

There is also something to be said for guaranteeing that an object is in a valid state at all times. If one or more "setup" methods have to be called every time on a certain class to make it valid, then doing this initialization in the constructor can be a way to help consumers of the class avoid using the object when it is not fully initialized.

One major disadvantage of initializing an object via a constructor is that this often requires that your constructor take parameters. This can make it hard or even impossible to instantiate your object via reflection. Thus, many frameworks that rely on reflection also require that the classes used with them have a parameter-less constructor.

One exception to this last point is that constructors are often used with Dependency Injection. In this case, the arguments to a class's constructor define its dependencies, thus allowing a DI framework to do the work of intializing the object.

Need Your Help

<c:if> test=“” in jsf

jsf-2 jstl primefaces

I'm using primefaces and jstl to loop a datatable.I have a List in backing bean for the columns.

Algorithm for implementing C# yield statement

c# algorithm compiler-construction iterator state-machines

I'd love to figure it out myself but I was wondering roughly what's the algorithm for converting a function with yield statements into a state machine for an enumerator? For example how does C# turn

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.