About constructors - c#

I got a question about Constructors.I think constructors are all just our convenience instead of setter methods,right? So for an object , the properties you think important(such as required fields in a webform)are passed as parameters into constructor.
Is there any criteria that these many number of parameters should be passed into constructor?
Please elaborate on these points and as well as any points about constructors.
Edit:Sorry about the way i asked question.Yes,we create an object with constructor and we assign values with setters but my question is about the comparison between default constructor with setters and constructor with explicit parametrs.

No, it's not just a convenience instead of setters. In particular, a constructor will only be called once. Using constructor parameters, you can create immutable types which are given their values at construction time - that wouldn't be possible with setters.
It's generally not a great idea to have huge numbers of parameters, whether to a constructor or a normal method. If you find you have a lot of parameters, you may want to create a type representing all the related ones - that type may have a bunch of getters/setters. See ProcessStartInfo for an example of this.

I see it this way:
You pass the parameters in a constructor that are required in order to create an object that is in a 'valid' state.
For your example: I would not pass 'required fields in a webform' to the instance of the class that is filled up with those values.

You have to call setters on an object, and the constructor creates that object. Without a constructor invocation, you'll have no object to call upon.
Re. the number of parameters. If you have a sizable number of parameters, that suggests:
related parameters might be composable into objects themselves. e.g. a start date and an end date into a TimePeriod object
that object has too many responsibilities, and should be decomposed further
Check out the Factory pattern and Builder pattern for some alternatives re. creating objects.
A further note re. constructor parameters and setters. In Java and C#, the parameters passed into the constructior can be used to initialise fields once only, and the fields are immutable from that point on (unlike when you set these via setters). This has great benefits for code reliability (at some cost of object immutability).

Constructors are used to initialise a class. You should pass as many parameters as are required to define your class into the required initial state.
Note that you can also overload a constructor.

If you have some non-optional, and many optional parameters, and you want to avoid looong parameter lists in constructors (which can be very error-prone, especially if the parameters are of the same type), you should favor the use of the
Builder pattern
instead.

You can also consider the use of the Factory pattern for object creation.

I think you should pay more attention to where the objects are being deployed when deciding how to create them. I try to summarize some points that help when choosing which method to use for filling object fields, i.e. constructor or setter methods:
State: By state, I mean the value of all fields of an object in a snapshot of runtime. When developing an application, keeping track of object state is important especially if an object is going to be accessed in multiple threads. Even in single-thread programming, objects may be modified in different methods and classes especially in languages such as Java that passes all objects by reference. Setting the state once and for all the lifetime of an object (in the constructor) and avoiding setters (called immutable pattern) makes programming, especially concurrent programming, really easier. But pay attention that this approach increases object modification cost because all the fields should be copied into a new instance on each modification; for example in Java, compare String (which is immutable) to StringBuilder and StringBuffer (which are stateful). String is thread-safe and easy-to-use but costly for long string creation, while StringBuilder is not thread-safe but fast in concatenating small strings. Meanwhile, StringBuffer is both stateful and thread-safe but costly in every method call because its methods that are synchronized (It means: do not make a stateful object thread-safe when it is not necessary in most of the use cases). So, as a general hint: use constructors (and immutable pattern) for objects which are accessed in multiple threads and use setters for local objects and fields which are under more control.
Injection: When we are using a dependency injection framework such as Spring or Guice, the framework makes one method more preferable than the other. For example, spring encourages setter injection more than constructor injection. Spring constructs the objects (beans) mostly using default constructors and then injects the dependencies using setter methods. Then Spring calls the init (PostConstruct) method for you. So, you can do whatever initialization you want in this method with the dependencies in-place. In contrast, Guice encourages constructor injection as its best practice.
Beauty of Code: Not only having a long list of parameters in a constructor is not beautiful, but also if many other constructors should be overloaded to support multiple optional parameters, these constructors may clash because of having same parameter types. Therefore, using setters is more effective if many of the fields are optional. But I think even in this case, the object usage scenario is more important. Long list of parameters can be resolved by grouping them in other classes, as other developers have suggested here.
To new or To Delegate: Whenever you are going to new an object whether using constructor or setter methods to fill the fields, it is a good practice to think if it may be needed someday that someone else pass (inject, create) it here. This leads to the Factory design pattern which is helpful especially when developing tools and libraries.

Related

Use instance variables or static variables in object instances that will only be instantiated a single time and won't be accessed from outside?

Generally, are there any performance gain or any other reasons for using one way over the other?
Say I am having a winforms application and there will only be a single window per process ever. There are no comfort implications in my use case: The variable is only accessed from methods in that one form instance.
You won’t notice a performance difference unless you are calling the methods millions of times. The question should be: Which variant makes more sense?
A static member makes sense in two cases:
All instances (and there should be more than one) share a common resource.
The class is static and therefore all members must be static as well.
Otherwise it seems natural to use instance members.
In the paradigm of Object-oriented programming (OOP) entities are represented as objects that have data fields (attributes that describe the object) and associated procedures known as methods (freely adapted from Wikipedia).
Static members are not part of this paradigm and are not really object-oriented. It is the very reason of objects to have (instance) data fields.
Examples of common resources are: A database context, configuration options, a random number generator, the next free ID to be assigned to an instance.
Examples of static methods are factory methods. The Color structure, for instance, has FromArgb, FromKnownColor and FromName methods which all initialize a Color from different sets of parameters.
As far as performance is concerned, I agree with Eric J's comment. I would suggest making it an instance member, considering that designs change. Even if it doesn't ever change, there's really no advantage to making it static.

Reflection C#: Create instance of an object which has no default constructor

I know that FormatterServices.GetUninitializedObject can do that, but the core library for xbox does not contain the class.
I'm working on a XNA game and I'm trying to make this work there. Activator.CreateInstance is available but than I need a default constructor, what's ugly.
I thought of if there is no default constructor, I take the shortest and pass in any values (for example when it requires an int and an object, I pass in 0 and null).
But the problem on that is that the constructor could throw an exception if it works with the objects passed in. Well I still could write it in a try catch block and maybe it works that way. But I really unlikely would do that. Is there any other solution?
Thanks for any help :)
You don't need the default constructor, I think there's an overload where you can pass parameters in
Activator.CreateInstance (typeof (Foo), new object []{ args});
That said, you can also use reflection to get the constructor and just call that.
Edit: wait - rereading the question, are you saying you don't know what to pass in? Then why are you creating it?
No, this is completely the wrong solution.
You definitely need a default constructor, otherwise you have no business constructing the objects this way.
Note that you can use a "non-default" (I'm taking "default" here as meaning "parameterless") constructor, but you should still pass in the required parameters, not just by type, but by meaning as well.
Since you're resorting to Activator.CreateInstance, I'm assuming you don't know a lot about the type in question, except its Type object. In this (general) case, you should not just pass in some odd values to the constructor in the hopes that it will make sense to the type in question.
If, on the other hand, you have some sort of contract going, where you can say "I know this type supports contract X", you might look into using an interface, and calling a method on that interface after constructing the object. The interface would then have a known method (known to the code that needs to construct the instance) that you would call with known (known as in knowing how many, their types, as well as their meaning) parameters.
Just randomly (passing in 0 and null just to satisfy the signature is just as arbitrary as passing on 42 and some odd object) passing parameters to the constructor is not safe at all.
Example with interface:
object instance = Activator.CreateInstance(someTypeObject);
((ISomeInterface)instance).Initialize(your, specific, parameters, here);
What you might need is a IoC framework, so that you can say "whenever someone needs an instance of this class, here's how to construct it".
Look up:
Inversion of control (IOC) - Wikipedia
Autofac
Ninject
Unity
Castle Windsor
there are more, search for inversion of control C#
You state that your target class does not have a default (or "parameter-less") constructor. Put another way; your class's constructor contains "Dependencies." It cannot (and should not!) be constructed until those dependencies are met.
What you need is a Dependency Injection (or Inversion of Control) container. I recommend looking at Ninject, for excellent implementation which happens to be compatible with XNA.
Dependency Injection frameworks allow you to specify general 'rules,' such that the DI container can "fill in the blanks" when you encounter an object which requires parameters in the constructor. For example, an example of a DI rule for creating type Foo:
"When you try to create an object of type Foo which has a constructor with parameters (int, object), pass these values to the constructor: (0, null)."
Spend a little bit of time glancing through some of the examples on the link provided, for an idea of how to achieve what you're asking using the Ninject library.

What's the fundamental reason for C# to forbid calling the default constructor?

This is a subsequent question to another question I asked here:
Calling constructor from other constructor in same class at the end
The previous one was about how, now the question is why Microsoft designed it this way ?
UPDATE: My question is rather:
Why can't I call a constructor directly AT THE END of another constructor whereas I can call AT THE BEGINNING.
If they forbid call at the end why didn't they forbid to call directly at the beginning also ?
Why can't I call a constructor
directly AT THE END of another
constructor whereas I can call AT THE
BEGINNING.
Well, let's break it down into two cases. (1) you're calling a "this" constructor, and (2) you're calling a "base" constructor.
Suppose you're in the first case. The typical usage pattern for this scenario is to have a bunch of ctors that take different arguments and then all "feed" into one master ctor (often private) that does all the real work. Typically the public ctors have no bodies of their own, so there's no difference between calling the other ctor "before" or "after" the empty block.
Suppose you're in the first case and you are doing work in each ctor, and you want to call other ctors at times other than the start of the current ctor.
In that scenario you can easily accomplish this by extracting the work done by the different ctors into methods, and then calling the methods in the ctors in whatever order you like. That is superior to inventing a syntax that allows you to call other ctors at arbitrary locations. There are a number of design principles that support this decision. Two are:
1) Having two ways to do the same thing creates confusion; it adds mental cost. We often have two ways of doing the same thing in C#, but in those situations we want the situation to "pay for itself" by having the two different ways of doing the thing each be compelling, interesting and powerful features that have clear pros and cons. (For example, "query comprehensions" vs "fluent queries" are two very different-looking ways of building a query.) Having a way to call a ctor the way you'd call any other method seems like having two ways of doing something -- calling an initialization method -- but without a compelling or interesting "payoff".
2) We'd have to add new language syntax to do it. New syntax comes at a very high cost; it's got to be designed, implemented, tested, documented -- those are our costs. But it comes at a higher cost to YOU because you have to learn what the syntax means, otherwise you cannot read or maintain other people's code. That's another cost; again, we only take the huge expense of adding syntax if we feel that there is a clear, compelling, large benefit for our customers. I don't see a huge benefit here.
In short, achieving your desired construction control flow is easy to do without adding the feature, and there's no compelling benefit to adding the feature. No new interesting representational power is added to the language.
For the "base" scenario, it's quite straightforward. You never want to call a base constructor AFTER a derived constructor. That's an inversion of the normal dependency rules. Derived code should be able to depend on the base constructor having set up the "base" state of the object; the base ctor should never depend on the derived constructor having set up the derived state.
Eric Lippert has a blog post about the order in which initializers and constructors run when an object is created. In it he says: "The more derived constructors may rely upon state initialized by the less derived constructors, so the constructors should run in order from base to derived".
I think the technical reason for the behaviour you describe is hinted within the C# specification here:
http://en.csharp-online.net/ECMA-334:_17.10.3_Constructor_execution
Any variable initializers are called as part of the constructor code, and if you were able to call a constructor directly - which is a Very Special Function from the compiler's point of view - you might fire off additional behaviour. With the constructor chaining approach (using the ": this" on the constructor definition) the compiler respects your attempt to call another constructor safely.
I don't think there's really much requirement to call another constructor within the same class (inheritance aside) -- there's nothing you can't do without defining another function and, to be honest, I prefer to do that. If my constructors get lengthy, I usually feel more comfortable pushing it into separate function as I often need to call a complicated "Reset" or "Init" function outside of the constructor.
IIRC from the design of C++, constructors must be called in top-down order because a base class instance is not guaranteed to be useable until its constructor has finished executing. You cannot construct your derived object safely unless you know in advance that your base object is fully initialised and ready to go. If that seems like a trivial point, consider the case where the base class contains private state that is only initialised properly in its constructor. AFAIK the reasoning is the same in the CLR.
The same reasoning applies in the opposite direction. It is only safe to destroy/finalize the base class instance after the derived class instance has been done, because the derived object may rely on the base object's state still being valid.
I'm guessing, but possibly as simple as: it is very rare you want it, and when you do there are usually better options (private/protected initialization methods) that do the job adequately. And without the risk of forgetting to initialize it, or calling a method that relies on data that isn't yet initialized (a reason why calling virtual methods in the ctor is a bit risky).
The only caveat is that you can't use a readonly field with a post-ctor initialization method, but that is IMO less evil than making things more complex for a corner-case.
The purpose of a constructor is to initialize the object.
Overloading the constructors is used when you want to pass some initial parameters to the object.
So the purpose of the design is to have one Mega constructor which accepts all the variables and do all the initializing, and have the other constructors propagate variables, and set default values to parameters not passed from the user.
The idea is to have a single method doing the initialization, and not having seperate constructors each doing something else.
The default constructor is only ever created by the compiler when you don't specify your own constructor. It is a bit of syntactic sugar, to make it easy to quickly create a class.
By writing your own constructor, you are in effect declaring that yes, you are interested in how your objects are initialized. The default constructor is not generated.
Since disabling the default constructor is only possible by writing another constructor, allowing users to call the default constructor would make it impossible to disable it.

what is the inconveniences of using static property or method in OO approach?

I need to explain myself why I do not use static methods/propertis. For example,
String s=String.Empty;
is this property (belongs to .Net framework) wrong? is should be like?
String s= new EmptySting();
or
IEmptyStringFactory factory=new EmptyStringFactory();
String s= factory.Create();
Why would you want to create a new object every time you want to use the empty string? Basically the empty string is a singleton object.
As Will says, statics can certainly be problematic when it comes to testing, but that doesn't mean you should use statics everywhere.
(Personally I prefer to use "" instead of string.Empty, but that's a discussion which has been done to death elsewhere.)
I think the worst thing about using statics is that you can end up with tight coupling between classes. See the ASP.NET before System.Web.Abstractions came out. This makes your classes harder to test and, possibly, more prone to bugs causing system-wide issues.
Well, in the case of String.Empty it is more of a constant (kind of like Math.PI or Math.E) and is defined for that type. Creating a sub-class for one specific value is typically bad.
On to your other (main) question as to how they are "inconvenient:"
I've only found static properties and methods to be inconvenient when they are abused to create a more functional solution instead of the object-oriented approach that is meant with C#.
Most of my static members are either constants like above or factory-like methods (like Int.TryParse).
If the class has a lot of static properties or methods that are used to define the "object" that is represented by the class, I would say that is typically bad design.
One major thing that does bother me with the static methods/properties is that you sometimes they are too tied to one way of doing something without providing an easy way to create an instance the provides with easy overrides to the behavior. For example, imagine that you want to do your mathematical computations in degrees instead of radians. Since Math is all static, you can't do that and instead have to convert each time. If Math were instance-based, you could create a new Math object that defaulted to radians or degrees as you wished and could still have a static property for the typical behaviors.
For example, I wish I could say this:
Math mD = new Math(AngleMode.Degrees); // ooooh, use one with degrees instead
double x = mD.Sin(angleInDegrees);
but instead I have to write this:
double x = Math.Sin(angleInDegrees * Math.PI / 180);
(of course, you can write extension methods and constants for the conversions, but you get my point).
This may not be the best example, but I hope it conveys the problem of not being able to use the methods with variations on the default. It creates a functional construct and breaks with the usual object-oriented approach.
(As a side note, in this example, I would have a static property for each mode. That in my eyes would be a decent use of the static properties).
The semantics of your three different examples are very different. I'll try to break it down as I do it in practice.
String s=String.Empty;
This is a singleton. You would use this when you want to ensure that there's only ever one of something. In this case, since a string is immutable, there only ever needs to be one "empty" string. Don't overuse singletons, because they're hard to test. When they make sense, though, they're very powerful.
String s= new EmptySting();
This is your standard constructor. You should use this whenever possible. Refactor to the singleton pattern only when the case for a singleton is overwhelming. In the case of string.Empty, it very much makes sense to use singleton because the string's state cannot be changed by referring classes.
IEmptyStringFactory factory=new EmptyStringFactory();
String s= factory.Create();
Instance factories and static factories, like singletons, should be used sparingly. Mostly, they should be used when the construction of a class is complex and relies on multiple steps, and possibly state.
If the construction of an object relies on state that might not be known by the caller, then you should use instance factories (like in your example). When the construction is complex, but the caller knows the conditions that would affect construction, then you should use a static factory (such as StringFactory.CreateEmpty() or StringFactory.Create("foo"). In the case of a string, however, the construction is simple enough that using a factory would smell of a solution looking for a problem.
Generally, it is a bad idea to create a new empty string - this creates extra objects on the heap, so extra work for the garbage collector. You should always use String.Empty or "" when you want the empty string as those are references to existing objects.
In general, the purpose of a static is to make sure that there is ever only one instance of the static "thing" in your program.
Static fields maintain the same value throughout all instances of a type
Static methods and properties do not need an instance in order to be invoked
Static types may only contain static methods/properties/fields
Statics are useful when you know that the "thing" you are creating will never change through the lifetime of the program. In your example, System.String defines a private static field to store the empty string, which is allocated only once, and exposed through a static property.
As mentioned, there are testability issues with statics. For example, it is hard to mock static types since they can't be instantiated or derived from. It is also hard to introduce mocks into some static methods since the fields they use must also be static. (You can use a static setter property to get around this issue, but I personally try to avoid this as it usually breaks encapsulation).
For the most part, use of statics is o.k. You need to decide when to make the trade-off of using static and instance entities based on the complexity of your program.
In a purist OO approach, static methods break the OO paradigm because you're attaching actual data to the definition of data. A class is a definition of a set of objects that conform to semantics. Just like there are mathematical sets that contain one or zero elements, there can be classes that contain only one or zero possible states.
The way of sharing a common object and allowing multiple actors on its state is to pass a reference.
The main problem with static methods comes from, what if in the future you want two of them? We're writing computer programs, one would assume that if we can make one of something, we should be able to make two very simply, with statics this isn't the case. To change something from a static state to a normal instance state is a complete rewrite of the class in question.
I might assume I want to only ever use one SqlConnection pool, but now what if I want a high priority pool and a low priority pool. If the connection pool was instanced instead of static the solution would be simple, instead I have to couple pooling with connection instantiation. I better hope the library writer had forsight or else I have to reimplement the pooling.
Edit:
Static methods in single inheritance languages are a hack to provide reuse of code. Normally if there are methods one wanted to share common code between classes you could pull it in through multiple inheritance or a mixin. Single inheritance languages force you to call static methods; there's no way to use multiple abstract classes with state.
There are draw backs to using statics such as:
Statics dont allow extension methods.
Static constructor is called automatically to initialize the class before the first instance is created (depending on the static class being called of course)
Static class data lives throughout the lifespan of the execution scope, this wastes memory.
Reasons to use static methods
Statics are good for helper methods, as you dont want to create a local copy of a non-static class, just to calla single helper method.
Eeerm, static classes make the singleton pattern possible.
From a scenario-driven design, the criteria for choosing statics vs. instance methods should be: if a method can be called without an instance of a class to be created, make it static. Else, make it an instance method. First option makes the call a once line process, and avoid .ctor calls.
Another useful criteria here is whether responsabilities are in the right place. For ex. you got an Account class. Say you need functionality for currency conversion e.g. from dollars to euros. Do you make that a member of the Account class? account.ConvertTo(Currency.Euro)? Or do you create a different class that encapsulates that responsibility? CurrencyConverter.Convert(account, Currency.Euro)? To me, the latter is better in the sense that encapsulates responsibilities on a different class, while in the former I would be spreading currency conversion knowledge across different accounts.

Class Design - Properties or Parameters?

I am designing a class...
there are crucial methods that need an object passed to them or they need to be able to "get" an object.
So the question is, should you use getter/setters OR directly send the object as an argument to the method - in order for the method to work properly. Or should you set objects via the constructor if they are really crucial to the class operating correctly?
If it doesn't make sense to have an instance of this class without a certain object (eg it might make no sense to construct a data-access class without a connection to a database), then it's a "dependency" and should be part of the constructor.
If your class can survive without it, or can use some default value, then you could instead make it a property and check if it's assigned before being used.
I'd strongly advocate constructor dependency injection in most cases though.
The question isn't how "crucial" they are (every method needs to have the data it needs, by definition). A better question is how frequently do they change. If they'll be different each time the method is called (or at least reasonably could be) they should be parameters. If they are expected to generally be the same for the life of the object (or a significant fraction there of) they should be stored with the object.
In the latter case, don't just rely on the user calling a setter. If they are required, they should be set in the constructor even if they can be changed by a setter.
As you mentioned, you have the following three options:
Use getters/setters
As you might know, get/set will indicate a state of the object, that is accessed multiple times(generally) during the object lifetime. So if you have a scenario like 'CrucialMethod1' to 'CrucialMethodN' consuming this state then this could be used. Additionally, this will also help in exposing the state externally.
Use as parameter to constructor
Generally, a parameter to the constructor will 'dictate' the state into which the object will be initialized. So if you have a scenario where the 'CrucialMethod' may or may not be called, then this would not be most appropriate.
Use as parameter to the method
This would be useful in the scenario when the 'CrucialMethod' acts/transforms(depends) on the parameters passed. This facilitates calling the method without dependency on the state of the parameter being.
Your call!
If they are required to the class operating correctly you should require them in the constructor or set them inside it.
As for passing it in or not. I prefer when classes can take care of themselves so have it do the work and get what it needs.

Categories

Resources