I am developing mono and .net applications. I have some basic questions regarding the best practices.
If I need to create an unmanaged object just to be used once (may be pass to a method or invoke one of it's method) and don't need it later, should I assign it to a variable first and then use it so that I can dispose it (or may be assign variable in a using() block) or should I just use like new Class().Method(), in order for GC to be able to collect it? What is the best practice?
Do I need to dispose of objects which has only a local scope of a method or is it enough if I dispose of object that are properties of the class (global)?
I have a Class A and a Class B. An object of B is created in some method M of Class A. This object (of class B) has another method M2 which invokes a second method in Class A, M3. So structure is as below
Class A
{
void M()
{
var b = new B();
}
public string M3()
{
return "OK";
}
}
Class B
{
void M2()
{
Console.WriteLine(new A().M3();
}
}
Will this create a cyclic reference a stop GC from collecting these two objects?
What are the other general principles for good Memory efficient programming?
This question has a significant risk of becoming "too broad", i.e. off-topic for StackOverflow. That said, some brief answers:
If I need to create an unmanaged object just to be used once (may be pass to a method or invoke one of it's method) and don't need it later… What is the best practice?
Best-practice for using any unmanaged object is to wrap it in an instance of SafeHandle. Of course, most common unmanaged objects you'd have to deal with are already wrapped by .NET, either in some custom implementation of IDisposable (e.g. StreamReader), or in newer framework code, as a SafeHandle subclass.
But when you are dealing with your own unmanaged objects that .NET has no knowledge of, you'll want to follow .NET's example and use SafeHandle.
Do I need to dispose of objects which has only a local scope of a method or is it enough if I dispose of object that are properties of the class (global)?
If you create the object, and you have not passed it to some other code for it to own, and you are not going to return it from the method, then you need to dispose it. You do need to dispose objects which are referenced only within a method.
Typically you would use the using statement to do this.
…Will this create a cyclic reference a stop GC from collecting these two objects?
Ignoring for a moment that your code example wouldn't compile, nor contains any reference cycles… :)
Unlike some memory management schemes, such as ref-counting, .NET's garbage collection does not have any issue with cyclical references at all. An object is determined to be collectable or not based on whether it is reachable from a root reference. Two unrooted objects which reference each other are still neither reachable from a root reference and so are both collectable.
What are the other general principles for good Memory efficient programming?
That's definitely too broad for StackOverflow. Even in the GC-based system .NET uses, there a lot of fine details that one can concern oneself with. The basic system eliminates a number of common programming errors, but it has its own idiosyncratic behaviors that are in some cases important to understand.
Some time spent browsing MSDN and web articles on the topic will help you learn more about garbage collection, in .NET and in general. If and when you have other specific questions, please feel free to post them on StackOverflow.
Related
I'm creating a utility class CommonDaoOperations that contains several generic methods: Create, Update, Delete.
This is not a base class because some DAOs are more complex and can't use these generic methods, but many DAOs can.
I'm now pondering how that utiliy class should look like exactly:
static class with only static generic methods
regular class with generic methods, created once per DAO as private readonly member
regular class with generic methods, created once per DAO method (in each call)
Creating an instance of a class per DAO / method obviously costs more than calling a static method, but I'm pretty sure that these costs are negligable in almost any application.
I'd favor solution 2 or 3 because of the benefits of non-static classes (interfaces, can be mocked, can be derived / enhanced, could gather parameters via constructor in the future should it be necessary (compared to a 10-parameter-method in a static class)).
So I guess the real question is: should I be creating my utility class as a member variable, or instantiate it per DAO method?
public void Create(User user) {
new CommonDaoOperations().Create(user);
}
public void Delete(User user) {
var daoOps = new CommonDaoOperations();
daoOps.CheckSomething(); // just an example of multiple calls to the class
daoOps.Delete(user);
}
I'm interested to hear what other devs think about any of these approaches, or if there's still anothere / better way to do this.
Edit
Just realized that I should have given approach #3 more thought - as Vadim pointed out, replacing the concrete class would be cumbersome when it's instantiated in each method, but I could factor that in a property:
private CommonDaoOperations DaoOps {
get { return new CommonDaoOperations(); }
}
public void Create(User user) {
DaoOps.Create(user);
}
I believe this to be more maintianable than the above snippet, however know I introduced a property for a 'utility' class in my DAO, which might be a code smell by itself (as Ant P pointed out).
Summary
This was a tough decision - while I accepted the answer from Ant P, Vadim's answer is also legitimate. Which approach to use depends on the utility class, all 3 approaches have their uses (except the updated #3). At least that is my take of the provided answers.
Static classes do have their uses, but also many downsides as briefly mentioned above.
Regular class, instantiated per method: the utiliy class is created and used just where it is required. Reduces dependencies, keeps your type pure.
Regular class, instantiated as member: when many/all methods require an instance of the utility class, it may be a better idea to create a member variable. Changing the type or how it is instantiated becomes easier this way.
I will let those more qualified comment on the performance implications; however, here are my thoughts on each:
1. Static class
This concept is fine for simple, 'uncomprehensive' utility methods that require no real extensibility but - as you note yourself - your common DAO operations stand to grow considerably more sophisticated. This is unlikely to be very manageable as a single static class, particularly when it's used across multiple different types of DAO.
2. Concrete class, instantiated per-DAO object
This is all fine and dandy, but do you really need the utility class to be a member of the individual DAO? I could understand this if you needed some kind of consistency or state persistence within the utility class, across the lifetime of the DAO, but it seems that these methods are fairly nebulous (true to its name as a "utility" class).
Which leaves 3. Concrete class, instantiated per method. This seems the most natural solution to me. This gives you the flexibility to make use of all of the advantages of a concrete class as you acknowledge in your question, while restricting the scope of the object to where it's needed - the individual method call.
Should your class evolve into something that's needed across the entire DAO, e.g. you suddenly need to maintain the state of the object (or if you need to inject it into the DAO's constructor, or something else along those lines), you can always change where it's instantiated (though it seems to me that, if this happens, you don't really have a utility class any more and you need to reconsider how this class fits into your architecture).
Unless you plan to create an exceptionally large number of these objects, I don't think it'll affect performance.
I would prefer (2). There's simply need to create it for each use, that's just writing code for nothing. In addition, if you'd ever want to use some sort of IOC, get the utility class as a parameter, change the way it is initialized or simply change the class to another class - having a single member to change is a lot easier than changing all the places where it's used.
Unless you have a very good reason, stay away from statics or Singletons. (an example of a very good reason is something like developing an addon or a plugin in which you don't control the way your classes are initialized and used).
When considering the difference and usages between static classes and concrete classes sure there are implications to take in mind, see the testability for example (but this is not so sure at all as shown after), but there are first of all, some assumptions to do:
instance classes have state, manage state, and behaviors are related to it's internal state, if operations are not related to internal state in some ways, these are truly candidates for static methods, but I will say more after about that. This is the base even for encapsulation, and goes hand by hand with SRP (Single Responsibility Principle) which says that a class should have a single responsibility, doing one thing and no more, so, this gives you the fact that methods are all related to it's internal state directly or indirectly
static classes haven't and don't manage state. Maybe some one could say that it's not true at all, see singletons. Well, singleton's maybe good, but singletons designed as static classes are too close to anti-pattern, in this case, singletons could be managed as IoC containers does, by managing justo one instance at all. If needed I could provide some examples about with and without containers.
Well, someone says static classes are something close to anti-pattern, because for example testability.. well, this is non true, and this depends of what the static class and test which involves to is related.
I will report a very good example on that by on of the great software architect at all, Udi Dahan, which for example, in a good article about Domain Events, he talks between other things, about static classes and testability, here the link Domain Events Salvation if you go to the section How to raise domain events and Unit testing with domain events, he talks about that.
After that, as you says, another difference about the two, is about memory cost, but others says about that. Take in mind that, tools like Reshaper, makes suggestions to transform instance classes/methods which doesn't handle state to the static representation, this in advantage of memory and usage.
The last words about your design: CommonDaoOperations seems to a truly static class which doesn't handle state, so it's a good candidate to be a static class, for it's nature, for jobs it does. You can instead treat it as "singleton" using a IoC container and configuring that class in the right way. There are many ways to accomplish that in other ways without Containers.. here a simple article which talks about singletons and static classes C# Singleton, Static Class. Sure making a property which returns the helper is not so a good design, and a property which returns a new instance for a get operation is always a bad design, it will be justified with solid reasons...
So seeing your design and how you use the helper class, the words says by Udi in the link above describe well the solution you should implement.
In C++, we have Copy Constructor, Destructors, overloaded = which are together called copy control.
My questions are:
Is copy constructor used in C# for initializing objects when passed to a function as argument or when initializing (not assigning) or when returning an object from a function as in C++?
Does an implicitly overloaded = operator function gets called when we assign (not initialize) any object to another object of the same type?
No: reference objects are passed by reference, while value objects are copied byte-for-byte. You can make your own "copy constructors", but you would be responsible for calling them explicitly.
You cannot overload the assignment operator
In fairness to C#, none of the intricacies of the C++ copy control are necessary because of the underlying garbage-collected memory model. For example, you do not need to control the ownership of dynamically allocated objects when copying objects, because you are free to have as many references to dynamic objects as you wish.
In C# you cannot overload the assignment operator.
Destructors don't really make sense in a managed memory world (most of the time). There is actually an equivalent (finalizers) but you should very rarely need to utilize them.
Copy constructors are made for certain classes, but it's not done nearly as often as in C++. It will never be called implicitly by the language, it will only be used when you manually call it.
No. If you want to provide copying mechanism, you do this by implementing the ICloneable interface: http://msdn.microsoft.com/en-us/library/system.icloneable.aspx
C# has no concept of a copy constructor, nor of overloading operator=. In C# objects just exist and you use handles to them in your code. Handles can be copied "by value" to be used throughout your code, but that's a so-called "shallow" copy, the object itself is still the same, they all point to the same memory (indirectly).
Copy constructors are akin to deep copying in the managed world, and you can achieve that through ICloneable, but it's completely manual and up to the object's implementation to write it. You can also achieve it through serialization (the boost way) or through any manner of indirect ways.
As a final point, since object lifetimes are non-deterministic (they die when the GC arbitrarily decides they should die), there's no such thing as destructors either. The closest thing are finalizers (called non-deterministically when your object gets collected) and the IDisposable pattern (along with using) which give you a semblance of control over finalization. Needless to say they are rarely used.
Edit: I should point out that, while copy constructors have no equivalent, you do have "type casting" constructors through implicit, the precise name escapes me at the moment.
I am having a situation that I have a common reference object that is being pass around as parameter to different operation object. It makes the code very messy to pass it around.
Is there anyway to make it like a reference to every operation (like a session)? However, it is just a core code library. Using static class is not the solution.
Thanks
Solution 1 - You can use singletons. They guarantee that there is only one instance of the class in the running code.
Solution 2 - why don't you put the shared reference object as a property of the object with those operations? That way, each operation has access to it. You can do some fancy stuff like if the reference property is null, throw an exception or so.
There are two general approaches to this that I know of:
a) Use IoC and a constructor dependency to pass in your shared object. As you mentioned if this object is used in many, many places this pollutes the interface and in many cases adds a lot of clutter.
b) Use an ambient context: Create a interface based singleton that may be accessed by the classes that need the object instance. Have a setter within the singleton that allows you to override the instance (e.g. for unit testing) so testing the code is still possible.
Maybe the Ambient Context Pattern could work for you? http://aabs.wordpress.com/2007/12/31/the-ambient-context-design-pattern-in-net/
I've been playing around with c++ lately and wondered why there were so many global functions. Then I started thinking about programming in c# and how member functions are stored, so I guess my question is if I have a:
public class Foo {
public void Bar() { ... }
}
and then I do something silly like adding 1,000,000 Foo's to a list; does this mean I have 1,000,000 Foo objects sitting in memory each with there own Bar() function? Or does something much more clever happen?
Thanks.
Nope, there is only one instance. All instances of a class point to an object that contains all the instance methods that take an implicit first parameter affectionately called this. When you invoke an instance method on an instance the this pointer for that instance is passed as the first parameter to that method. That is how the method knows all the instance fields and properties for that instance.
For details see CLR via C#.
This is, of course, complicated by virtual methods. CLR via C# will spell out the distinction for you and is highly recommended if you are interested in this subject. Either way, there is still only one instance of each instance method. The issue is just how these methods are resolved.
An instance method is simply a static method with a hidden this parameter.
(virtual methods are a little more complicated)
In C++ a member function doesn't normally require any per-object storage (an exception - virtual functions - is discussed in the next paragraph). Normally, at each point where the function is used the compiler generates CPU-specific machine code to directly call that function, and for inline functions the call may be avoided and the function's affect may be optimally integrated into the caller's code (which can be ~10x faster for small functions such as "getters and setters" that simply read or write one member variable).
For those classes that have one or more virtual functions, each object will have one extra pointer to a per-class table of function pointers and other information. Thus, each object grows by the size of a pointer - typically 4 or 8 bytes.
Addressing your original observation: C++ has more non-member functions (usually in the std namespace), but a namespace serves this purpose better than a class anyway. Indeed, namespaces are effectively logical interfaces for "static" functions and data that can span many "physical" header files. Why should the logical API of a program be compromised by considerations related to physical files and their implications to build times, file-modification-timestamp triggered make tools etc? In trivial cases where the namespace is in one header, C++ could use a class or struct to scope the same declarations, but that's less convenient as it prevents the use of namespace aliases, using namespaces, and Koenig lookup for implicitly searching namespaces matching a function arguments' namespaces - forcing very explicit prefixing at every point of use. It also gives the false impression that the user is intended to instantiate an object from the content.
ReSharper likes to point out multiple functions per ASP.NET page that could be made static. Does it help me if I do make them static? Should I make them static and move them to a utility class?
Performance, namespace pollution etc are all secondary in my view. Ask yourself what is logical. Is the method logically operating on an instance of the type, or is it related to the type itself? If it's the latter, make it a static method. Only move it into a utility class if it's related to a type which isn't under your control.
Sometimes there are methods which logically act on an instance but don't happen to use any of the instance's state yet. For instance, if you were building a file system and you'd got the concept of a directory, but you hadn't implemented it yet, you could write a property returning the kind of the file system object, and it would always be just "file" - but it's logically related to the instance, and so should be an instance method. This is also important if you want to make the method virtual - your particular implementation may need no state, but derived classes might. (For instance, asking a collection whether or not it's read-only - you may not have implemented a read-only form of that collection yet, but it's clearly a property of the collection itself, not the type.)
Static methods versus Instance methods
Static and instance members of the C# Language Specification explains the difference. Generally, static methods can provide a very small performance enhancement over instance methods, but only in somewhat extreme situations (see this answer for some more details on that).
Rule CA1822 in FxCop or Code Analysis states:
"After [marking members as static], the compiler will emit non-virtual call sites to these members which will prevent a check at
runtime for each call that ensures the current object pointer is
non-null. This can result in a measurable performance gain for
performance-sensitive code. In some cases, the failure to access the
current object instance represents a correctness issue."
Utility Class
You shouldn't move them to a utility class unless it makes sense in your design. If the static method relates to a particular type, like a ToRadians(double degrees) method relates to a class representing angles, it makes sense for that method to exist as a static member of that type (note, this is a convoluted example for the purposes of demonstration).
Marking a method as static within a class makes it obvious that it doesn't use any instance members, which can be helpful to know when skimming through the code.
You don't necessarily have to move it to another class unless it's meant to be shared by another class that's just as closely associated, concept-wise.
I'm sure this isn't happening in your case, but one "bad smell" I've seen in some code I've had to suffer through maintaining used a heck of a lot of static methods.
Unfortunately, they were static methods that assumed a particular application state. (why sure, we'll only have one user per application! Why not have the User class keep track of that in static variables?) They were glorified ways of accessing global variables. They also had static constructors (!), which are almost always a bad idea. (I know there are a couple of reasonable exceptions).
However, static methods are quite useful when they factor out domain-logic that doesn't actually depend on the state of an instance of the object. They can make your code a lot more readable.
Just be sure you're putting them in the right place. Are the static methods intrusively manipulating the internal state of other objects? Can a good case be made that their behavior belongs to one of those classes instead? If you're not separating concerns properly, you may be in for headaches later.
This is interesting read:
http://thecuttingledge.com/?p=57
ReSharper isn’t actually suggesting you make your method static.
You should ask yourself why that method is in that class as opposed to, say, one of the classes that shows up in its signature...
but here is what ReSharper documentaion says:
http://confluence.jetbrains.net/display/ReSharper/Member+can+be+made+static
Just to add to #Jason True's answer, it is important to realise that just putting 'static' on a method doesn't guarantee that the method will be 'pure'. It will be stateless with regard to the class in which it is declared, but it may well access other 'static' objects which have state (application configuration etc.), this may not always be a bad thing, but one of the reasons that I personally tend to prefer static methods when I can is that if they are pure, you can test and reason about them in isolation, without having to worry about the surrounding state.
For complex logic within a class, I have found private static methods useful in creating isolated logic, in which the instance inputs are clearly defined in the method signature and no instance side-effects can occur. All outputs must be via return value or out/ref parameters. Breaking down complex logic into side-effect-free code blocks can improve the code's readability and the development team's confidence in it.
On the other hand it can lead to a class polluted by a proliferation of utility methods. As usual, logical naming, documentation, and consistent application of team coding conventions can alleviate this.
You should do what is most readable and intuitive in a given scenario.
The performance argument is not a good one except in the most extreme situations as the only thing that is actually happening is that one extra parameter (this) is getting pushed onto the stack for instance methods.
ReSharper does not check the logic. It only checks whether the method uses instance members.
If the method is private and only called by (maybe just one) instance methods this is a sign to let it an instance method.
I hope you have already understood the difference between static and instance methods. Also, there can be a long answer and a short one. Long answers are already provided by others.
My short answer: Yes, you can convert them to static methods as ReSharper suggests. There is no harm in doing so. Rather, by making the method static, you are actually guarding the method so that you do not unnecessarily slip any instance members into that method. In that way, you can achieve an OOP principle "Minimize the accessibility of classes and members".
When ReSharper is suggesting that an instance method can be converted to a static one, it is actually telling you, "Why the .. this method is sitting in this class but it is not actually using any of its states?" So, it gives you food for thought. Then, it is you who can realize the need for moving that method to a static utility class or not. According to the SOLID principles, a class should have only one core responsibility. So, you can do a better cleanup of your classes in that way. Sometimes, you do need some helper methods even in your instance class. If that is the case, you may keep them within a #region helper.
If the functions are shared across many pages, you could also put them in a base page class, and then have all asp.net pages using that functionality inherit from it (and the functions could still be static as well).
Making a method static means you can call the method from outside the class without first creating an instance of that class. This is helpful when working with third-party vendor objects or add-ons. Imagine if you had to first create a Console object "con" before calling con.Writeline();
It helps to control namespace pollution.
Just my tuppence: Adding all of the shared static methods to a utility class allows you to add
using static className;
to your using statements, which makes the code faster to type and easier to read. For example, I have a large number of what would be called "global variables" in some code I inherited. Rather than make global variables in a class that was an instance class, I set them all as static properties of a global class. It does the job, if messily, and I can just reference the properties by name because I have the static namespace already referenced.
I have no idea if this is good practice or not. I have so much to learn about C# 4/5 and so much legacy code to refactor that I am just trying to let the Roselyn tips guide me.
Joey