My question is specific to, why and where not to implement IDisposable interface.
If I am not using & consuming any unmanaged resources, still is it good practice to implement IDisposable interface.
What are the advantages or disadvantages if I do it? or is it good practice to implement it?
Please advise.
You implement IDisposable for one of two reasons:
If you have Unmanaged resources to free.
You do this because this is the only way for the GC to know how to free unmanaged resources which otherwise it doesnt know about. This is about WHAT resources to free. This case is actually quite rare - more often than not you access unmanaged resources through existing managed objects. This case requires a full "official recommended" implementation. Generally you should wrap unmanaged resources in their own separate (managed) class that does the IDisposable implimentation (rather than including unmanaged resources in other larger objects).
If your class contains objects that impliment IDisposable.
You do this not because the objects won't get free if you don't (they will) but because you want to be able to control WHEN those resources are freed. Having a dispose impliementation that disposes disposable members of a class means that consumer can apply a using statement to easily control WHEN resources are freed. In pratice more often than not this is the main reason for implementing IDisposable. Note that if your class is sealed you can get away with a mimimal IDisposable implementation here - I.e just Dispose - there is no need for the full blown "official recommended' implimenation.
It follows that if neither of these cases applies then no need to implement.
If a class implements IDisposable, that will generally impart to any code which creates instances of that class a responsibility to ensure that Dispose gets called on that instance before it is abandoned; it may fulfill this responsibility either by calling Dispose on the object itself when it is no longer needed, or by making sure that some other object that receives a reference accepts "ownership" and responsibility for it. In the majority of cases, when code is written correctly, each IDisposable object upon which Dispose has not yet been called, will at every point in time, have exactly one other entity (object or execution scope) which "owns" it. During the lifetime of the IDisposable object, ownership may get passed among different entities, but when one object receives ownership the former object should relinquish it.
In many cases, objects will be used in such a fashion that tracking ownership is not difficult. Generally, any object whose state is ever going to be modified should have exactly one owner and that owner will know when the object is no longer needed. Additionally, because modification of the owned object's state would constitute modification of the owner's state, the owner itself should have a single owner. In such cases, requiring the owner to call Dispose will not pose any difficulty (the owner's owner should call Dispose on it). There is, however, a 'gotcha' with this principle: it's possible for an object to create an instance of a mutable class but never mutate it nor allow anyone else to do so. If the mutable class in question simply holds values and does not implement IDisposable, objects which hold references to the things that will never actually mutate need not concern themselves with ownership. This can allow some major simplifications, since it will be possible for many objects to hold references to the non-changing object and not have to worry about which of them will use it last. If, however, the mutable class in question implements IDisposable, such simplifications are no longer possible.
Related
Apparently, singletons are bad, and a factory method is recommended. I'm wondering if a singleton toolbox is any better than a singleton.
In my opinion, It's really weak to think that singletons are bad,factory methods are good.
Each of them has preferences. As consequence, I'm sure that there is misunderstanding here.
I know that wikipedia is not the best source. But check out the definition of them. The range of situations are not the same for these patterns.
In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton.
In class-based programming, the factory method pattern is a creational pattern which uses factory methods to deal with the problem of creating objects without specifying the exact class of object that will be created. This is done by creating objects via calling a factory method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor.
Garbage collected object oriented programming languages reclaim unused memory automatically, but all other kinds of resources (i.e. files, sockets...) still require manual release since finalizers cannot be trusted to run in time (or at all).
Therefore such resource objects usually provide some kind of "close"- or "dispose"-method/pattern, which can be problematic for a number of reasons:
Dispose has to be called manually which may pose problems in cases when it is not clear when the resource has to be released (similar problem as with manual memory management)
The disposable-pattern is somewhat "viral", since each class containing a disposable resource must be made disposable as well in order to guarantee correct resource cleanup
An addition of a disposable member to a class, requiring the class to become disposable as well, changes the interface and the usage patterns of the class, thus breaking encapsulation
The disposable-pattern creates problems with inheritance, i.e. when a derived class is disposable, while the base class isn't
So, are there any alternative concepts/approaches for properly releasing such resources? Any papers/research in that direction?
One approach (in languages that support it) is to manually trigger a garbage collection event to cause finalizers to run. However, some languages (like Java) do not provide a reliable mechanism for doing so.
Given some type as follows:
class Thing {
getInfo();
isRemoteThing();
getRemoteLocation();
}
The getRemoteLocation() method only has a defined result if isRemoteThing() returns true. Given that most Things are not remote, is this an acceptable API? The other option I see is to provide a RemoteThing subclass, but then the user needs a way to cast a Thing to a RemoteThing if necessary, which just seems to add a level of indirection to the problem.
Having an interface include members which are usable on some objects that implement the interface but not all of them, and also includes a query method to say which interface members will be useful, is a good pattern in cases where something is gained by it.
Examples of reasons where it can be useful:
If it's likely than an interface member will be useful on some objects but not other instances of the same type, this pattern may be the only one that makes sense.
If it's likely that a consumer may hold references to a variety of objects implementing the interface, some of which support a particular member and some of which do not, and if it's likely that someone with such a collection would want to use the member on those instances which support it, such usage will be more convenient if all objects implement an interface including the member, than if some do and some don't. This is especially true for interface members like IDisposable.Dispose whose purpose is to notify the implementation of something it may or may not care about (e.g. that nobody needs it anymore and it may be abandoned without further notice), and ask it to do whatever it needs to as a consequence (in many cases nothing). Blindly calling Dispose on an IEnumerable<T> is faster than checking whether an implementation of IEnumerable also implements IDisposable. Not only the unconditional call faster than checking for IDisposable and then calling it--it's faster than checking whether an object implements IDisposable and finding out that it doesn't.
In some cases, a consumer may use a field to hold different kinds of things at different times. As an example, it may be useful to have a field which at some times will hold the only extant reference to a mutable object, and at other times will hold a possibly-shared reference to an immutable object. If the type of the field includes mutating methods (which may or may not work) as well as a means of creating a new mutable instance with data copied from an immutable one, code which receives an object and might want to mutate the data can store a reference to the passed-in object. If and when it wants to mutate the data, it can overwrite the field with a reference to a mutable copy; if it never ends up having to mutate the data, however, it can simply use the passed-in immutable object and never bother copying it.
The biggest disadvantage of having interfaces include members that aren't always useful is that it imposes more work on the implementers. Thus, people writing interfaces should only include members whose existence could significantly benefit at least some consumers of almost every class implementing the interface.
Why should this not be acceptable? It should, however, be clearly documented. If you look at the .net class libraries or the JDK, there are collection interfaces defining methods to add or delete items, but there are unmodifiable classes implementing these interfaces. It is a good idea in this case - as you did - to provide a method to query the object if it has some capabilities, as this helps you avoid exceptions in the case that the method is not appropriate.
OTOH, if this is an API, it might be more appropriate to use an interface than a class.
(very newbie questions)
i may be misunderstanding this but on MSDN i believe it says that it is good practice to implement the Dispose destructor in every class you write. should i (do you) really implement the IDisposable interface with every class i write?
also, is the proper syntax for implementing an interface to put the "Implements" keyword on the line after the "class" declaration? i put it on the same line as "class" and I got an error.
one more?: when coding the method implemented by the interface, is it mandatory to follow this syntax, as an example:
Public Sub Dispose() Implements IDisposable.Dispose
what i'm curious about in the above code, is if i need to declare the implemented method as
"Implements System.IDisposable.Dispose"
You should only implement IDisposable if your class holds instances of other classes that implement IDisposable, or if it holds native resources.
For more information, see this article.
No you should not. Only implement IDisposable if you are using unmanaged resources directly or have members that implement IDisposable and want to make sure their dispose method gets called when the dispose method gets called on your class.
Many actions a computer might perform create the need for a counter-balancing "cleanup" action. For example, the act of opening a file creates a need to close it. The act of placing a call with a modem creates the need to disconnect it. Performing an action without performing the required counter-balancing cleanup may sometimes be harmless, but may sometimes have severe consequences in the computer or in the real world (failing to close a file before a user ejects the media may cause file corruption and data loss; failing to terminate a modem connection may cost someone many dollars in excess phone charges).
The purpose of IDisposable is provide a means by which well-behaved programs can make sure that any cleanup actions that need to be performed actually get done. Any routine which performs an operation that must be counter-balanced by cleanup should keep the information and impetus necessary to perform such cleanup until such time as it has been performed; if the routine can't perform such cleanup before returning to the caller, it should either (1) provide the information to the caller, and be documented as requiring the caller to use that information to perform the cleanup, or (2) keep the necessary information in one or more fields, and implement IDisposable; when IDisposable.Dispose is called, the object should use the saved information to perform the cleanup.
Note that IDisposable only works cleanly if any object that requests the creation of an IDisposable object accepts and honors the responsibility of making sure that the object's IDisposable.Dispose method will be called sometime. The system does provide a "backup" means, called finalization, which objects can use to ensure that they get a chance to perform their cleanup. Essentially, an object registers a request with the system that says "Let me know if I've been abandoned". If the system detects that an object has been abandoned, it will try to give the object a chance to perform any necessary cleanup. Note the system may take awhile to notice that an object has been abandoned, and for various reasons the notifications may not always happen. It is almost always much better to call IDisposable.Dispose on objects before they are abandoned, than to rely upon the "last chance" finalization mechanism.
The .Net framework has a garbage collector and for the most part manages allocation and release of memory for you (when creating a new object). However you also need to manage un-managed resources (I also seen being refereed to as native resources). So now the garbage collector is not good enough and you have to manage memory using the IDisposable interface. A good example is creating the DataAccesslayer where you handle database connection and use the IDisposable interface
check this out to see how to implement iDisposable interface:
https://msdn.microsoft.com/en-us/library/498928w2%28v=vs.110%29.aspx
OK thought I understood IDipose but just reading the best practices section of Accelerated VB.NET and it states that "The object doesn't contain any objects that implement iDispose, so you don't need to iterate through the containment tree calling iDispose"
Is this "containment tree" just what the program know's he has used and then distroys, or is there a contaiment class / collection that I should be looking at when I distroy an object ?
I haven't read the book but I've never heard of this “containment tree”. In context, it sounds as if this merely means all fields (of a given class) that also implement IDisposable and consequently have to be disposed in the class’ Dispose method (if the disposing argument is True) – or rather, in your case, since there are no such fields you don’t have to take any further action.