I'm working on implementing Mono to my C++ project and I have a C# class that holds a single integer. Something like this:
public class TestClass {
int number;
}
And I have another Class that has a field of TestClass. Something like this:
public class AnotherClass {
TestClass test;
}
Now, I have an instance of AnotherClass called instance and I want to set it's test field. Since the field can be null by default I create an instance of TestClass called testInstance, set it's number field and then set instance.test field to testInstance.
However I'm wondering if it wouldn't be faster to instead give TestClass a constructor that sets the number field to a parameter it takes and then initialize testInstance with that constructor and lastly set instance.test to testInstance. So my questions is that, Is it faster to call a constructor that just sets a field from withing C# or to set that field manually from within C++
Performance difference should be very small in your case, It may be big when your constructor has complex code inside it or multiple fields to be set. In general, it's good to practise keeping the constructor simple and doing the object initialization inside it.
When you are setting the field directly not in the constructor you are escaping from doing the things which the constructor does apart from setting this particular field.
your code should be readable, easily maintainable and scalable, so chose the approach accordingly.
If you are really concerned about the performance then you could do a benchmark and compare the results.
Related
public class ClassA
{
private SomeOtherClass _someOtherClass = new SomeOtherClass();
}
or
public class ClassB
{
private SomeOtherClass _someOtherClass;
public ClassB()
{
_someOtherClass = new SomeOtherClass();
}
}
or
public ClassC
{
SomeOtherClass _someOtherClass
public SomeOtherClass someOtherClass
{
get{
if(_someOtherClass == null)
{
_someOtherClass = new SomeOtherClass();
}
return _someOtherClass;
}
}
}
All of the above accomplish populating a property with an instance of an object. Is there a benefit to one of them over the other ones? In practice, I only use C when I don't have control over the construction of a class (like in a GUI). A smells a bit to me, but I don't have a concrete reason for that smell.
Note I am omitting the Inversion Of Control (IOC) pattern from the discussion as the benefits of that are well known and I of course use it often. This question is more about the case of a simple class that may not need that pattern.
A and B are almost the same (implementation details on the order, but not important in this case).
I would use C when:
The initialization of the variable can be delayed, or isn't frequently used;
I want to optimize the initialization time and memory of the class.
Another option for C is the use of Lazy<T>, but that is out of scope for the question I think.
A and B are (as said in other answers) basically the same. The property is populated when the class is constructed.
C doesn't populate the property on construction of the class, but only when it's accessed, which can be useful for a number of reasons (for example performance). Furthermore, it also has the side-effect that the property will never be able to be 'null' (whenever it's accessed, which could be an advantage or a disadvantage, depending on what the property is used for.
Well, the first and second example works the same, but I can say that the second one is much cleaner than the first one, because the instantiation is in the constructor, and the purpose of the constructor is usually to initialize the object's members that can be defined at that moment. In this way, you can easily know what has been instantiated just by looking at the constructor, and not searching through all the fields. In any of the first two cases, you could mark the field as readonly if you don't change it's value after that.
I see the third one as a kind of lazy loading, because you will initialize the field when you get the property. I use this when I am not sure if I will use the object within the class, so it is created per request. However, it has the minimal overhead of checking everytime if the field is instantiated, but it's nothing to worry about with current hardware. If you will use the object only within the class, you can mark the property as private, because it has no reason to be seen from the outside.
I have a rather lengthy constructor which is performing various initialisation work, and as such I wanted to factor out some of this work into some functions. This led to me wonder whether I should make the said functions instance or static methods. I understand the risk of calling a virtual function from a constructor but I also think there is something not right about calling an instance method on an object which is not 100% instantiated. Surely this is a contradiction in terms.
I'd be interested in peoples opinion on this matter. I also found that by using a static method to return an initialised variable I could make the member target read-only. Here's a simplified illustration of my scenario.
public class A
{
private readonly string _foo;
public A()
{
_foo = InitialiseFoo();
}
private static InitialiseFoo()
{
// Do stuff
return new string ("foo");
}
}
This is pretty normal to call instance method in a constructor, moreover method which doing Initialization. So basically this is a kind of Extract Method refactorig to reduce a constructor method body, so you are extracting part of initialization into a separate method and constructor is aware on saving of the input arguments, etc...
Regarding the static modifier.. sometimes (I believe when no other ways to refactor because this looks not good - from my point of view) you need to call a method to pass results in a base constructor so in this case you have to mark it as static to call in a static context in other cases leave it without the static modifier
public A()
: base(GetLogger())
{
}
private static ILog GetLogger() ...
I can understand the desire to only use static members in a constructor, because it DOES make the code more straightforward to use without having to track what has been initialized and what hasn't, but you're likely making things needlessly complicated for yourself. Calling an instance method in C# is fine as long as you have a good reason to do it. For instance, if you have a number of constructors that all perform some common tasks, creating a single member function to do the work is easier to maintain than copy-and-pasting the code for each constructor. You can also imagine a case where the method can be re-used outside of the constructor for something like reseting the class to the initialized state.
The static method, is fine, but will only work in the case where you are doing some isolated work and putting the result into a member variable. It provides a very clean, functional programming-like feel. If any of the work involves class state, however, it's going to get ugly.
In most of the cases we usually creates a private variable and its corresponding public properties and uses them for performing our functionalities.
Everyone has different approach like some people uses properties every where and some uses private variables within a same class as they are private and opens it to be used by external environment by using properties.
Suppose I takes a scenario say insertion in a database.
I creates some parameters that need to be initialized.
I creates 10 private variables and their corresp public properties
which are given as
private string name;
public string Name
{
get{return name;}
set{name=value;}
}
and so on. In these cases mentioned above, what should be used internal variables or properties.
And in those cases like
public string Name
{
get{return name;}
set{name=value>5?5:0;} //or any action can be done. this is just an eg.
}
In such cases what should be done.
What is the conclusion
I actually meant to ask this.
Should we use variables within that class or not or should we use properties everywhere within same class as well.
If you use auto-implemented properties, then the field will be hidden, so you are forced to use the property, even in the class where the property is defined. Auto-implemented properties are a good idea, unless you need to add some logic to the getter/setter.
If the only use for the private variable is as a storage container, you might use:
public string Name {get; set;}
IMHO one should never make variables public - always use properties so you can add constraints or change behaviours later on whitout changing the interface.
Made things more readable:
I expose my data always through properties.
If I do not need additional logic (e.g. validation) I use implicit properties. This way there is no backing field and I cannot access it by accident. If I need to add some additional logic I can easily change the implicit property to a "traditional" one. As I use the property everywhere I do not have to worry that my extra logic is not called.
If I need something extra (like validation) then I have a private backing field, but I access this field only in the property body (get/set accessors). Again I do not need to worry if I change something in the property: My code will always use the same logic.
The only reason for not calling the property in my opinion would be if for some reason I really do not want any additional logic to be called, but this seems a dangerous thing so I rather avoid it...
I never expose public variables. Why? Because I can't lay constraints on them, whereas I can when I'm using properties. I can first check the value if it meets my constraints (e.g. an email address) and then I save it. Otherwise I throw an Exception.
You should never expose public variables without a very good reason. It is tough to say never, because if you trying to interop with comm type components you might be required too.
Anything publicly exposed should be a property. Why is that?
The reason is if you need to change the source of the value, or add some business logic checking if it is a public member you are going to require anything using the code to change. If it is a property you can change the internal logic and not require anybody using it to change the code.
I personally use properties and only create members variables when I want a property to do more than getting or setting (since this is easy with C# 3.0 with shortcut properties).
If I want to keep a property from being publicly exposed I make it as private, and only expose it when I have too.
We require explicit private variables in some situation like validation before set.Sometime we also need to conversion of input, for instance , formatting the input.
I have two objects that I will be mainly use inside of single class. I will initialize them at the beginning and use them throughout the life of the program. Now, my question is that if I should just create them as global variables and access them anywhere in the code (in side of single class) or I should create them as local variables and pass them as parameters to other functions. I just want to see what would be the best programming practice.
I am using C#.
Thanks.
In general you should avoid global variables. If it will be practical, I recommend keeping them as locals and passing them as parameters to your functions.
As Josh pointed out, if these variables are only used inside a single instance of the class, then you should just make them private (or protected) members of that class and be done with it. Of course, then they could only be passed in as parameters to other methods with the same access level (IE, private).
Alternatively, you may consider using the Singleton Design Pattern, which is slightly cleaner (and preferable) to using globals.
If the scope of the objects is the lifetime of the class they are instantiated in, then they should be private member variables.
If they do not maintain state themselves, then you should make them static classes.
You should still pass them around as variables, or at least create property accessors to get at the backing field. This way you can change implementation details without blowing up your code.
SOLID design principles are a good place to start when thinking about these things.
I have two objects that I will be
mainly use inside of single class. I
will initialize them at the beginning
and use them throughout the life of
the program.
This sounds like a perfect time to use a private static readonly variable. These can be initialized in their declaration, or you can make a static constructor to initialize them.
The fact that you are only referencing these objects within a single class is key point. There are other better ways to do things if these objects are ever needed outside of the single class.
If the objects will be the same for every instance of the class then
static const double PI = 3.14158;
You should generally use accessor methods (e.g. getters and setters) and keep your internal variables private. This way the rest of your code, outside of your class, is not dependent on your actual variables.
See this tutorial.
If your class is dependent on these 2 objects then they should probably be members on the class itself. Something like this (where A is the class you are talking about and B is one of the objects you initialize:
public class A
{
private B _b;
public A(B b)
{
_b = b;
}
public void DoSomething()
{
//do something with _b;
}
private void DoSomethingElse()
{
//do something else with _b;
}
}
In this example A is dependent on B (so you pass your instance of B into A's constructor or through some Dependency Injection framework). It wouldn't make a lot of sense for every method on class A to need a parameter of type B to be passed to it.
I think in this case you should ask what makes more sense. Is there some kind of relationship between the 2 objects and the new class. Also, how often are they used in the class.
Generally, If only a couple of methods use the objects, pass them around otherwise, instantiate them as class level variables (possibly using private static readonly as Jefferey suggests) and use them in the class. Making the code more readable should be your goal here.
If you have a Property that gets and sets to an instance variable then normally you always use the Property from outside that class to access it.
My question is should you also always do so within the class? I've always used the Property if there is one, even within the class, but would like to hear some arguments for and against as to which is the most correct and why.
Or is it just a matter of coding standards being used on the project?
One of the stronger argument for accessing local (class scope) variables through properties is that you add a level of abstraction in your class. If you change any logic concerning how that field is stored then the rest of your code will be left unaffected.
For example you might change that from a local variable to a property of a child object, to a database call, to a webservice call, to a static property on a class and so on. When making the change it gives you a single point of change, the property, and you do not have to update the rest of your class since they all use the property.
Also using the property enables you to apply business rules on the value of the property instead of having to enforce the same rule at each location where you'd directly access the field. Again, encapsulation
With the introduction of automatic properties there's even less reason to explicitly have a local variable, unless you need to apply business rules on the get/set
It depends on whether you want to apply any logic implemented within the property setter, and so you really have to decide on a case by case basis.
When you go directly to the private field, you know that the field is being set to exactly what you say.
When you go through the Property, the value gets set according to the setter logic, so you get any business rules or validation you want over values assigned to that field.
Pretty hard to come up with a rule about when doing either is 'correct', about the only one I'd say I follow is that in constructor initialisation I'd pretty much never use the Property.
Yes I think you should use properties internally in your classes whenever possible. Properties are more flexible and allows you to add logic for validating it's value at a central place.
You can also delay the initialization of the the field to whenever the property is used instead of being forced to do it in the constructor (or everywhere the field is used). Example:
class Test {
private int _checksum = -1;
private int Checksum {
get {
if (_checksum == -1)
_checksum = calculateChecksum();
return checksum;
}
}
}
I think it's purely preference.
Though, I find myself using the properties a lot more in C# 3.0 with the auto-property support:
class Foo {
public string Value { get; set; }
public void Write() {
Console.Write(Value);
}
}
Generally depending on the project coding standards I use a "_" or "m" preceding the name for my private class attributes. (Like below)
private int mVariable;
private int _Variable;
With those in front of the variable I recognize right away that I'm dealing with an internal variable for the class. Then when it comes to debugging later myself or someone else can immediately recognize that the code is dealing with an internal private variable and make an adjustment. So it comes down to readability for me.
Always Use Properties, Here are some of the reasons
Easy to Use. In visual Studio you can use "Prop Tab Tab". You will get the property snippet
Properties are language elements that are accessed as though they are data members
.Net framework classes uses it, the data binding code classes in the .NET Framework support properties,
Properties have all the language features of methods. Properties can be virtual