Using interfaces directly in C# - c#-4.0

I recently read in "Professional C# 4 and .NET 4" that:
You can never instantiate an interface.
But periodically I see things like this:
IQuadrilateral myQuad;
What are the limitations in using interfaces directly (without having a class inherit from the interface)? How could I use such objects (if they can even be called objects)?
For example instead of using a Square class that derives from IQuadrilateral, to what extent could I get away with creating an interface like IQuadrilateral myQuad?
Since interfaces don't implement methods, I don't think I could use any methods with them. I thought interfaces didn't have fields to them (only properties), so I'm not sure how I could store data with them.

The answer is simple, you can't instantiate an interface.
The example you provided is not an example of instantiating an interface, you are just defining a local variable of the type IQuadrilateral
To instantiate the interface, you would have to do this:
IQuadrilateral myQuad = new IQuadrilateral();
And that isn't possible since IQuadrilateral does not have a constructor.
This is perfectly valid:
IQuadrilateral myQuad = new Square();
But you aren't initiating IQuadrilateral, you are initiating Square and assigning it to a variable with the type IQuadrilateral.
The methods available in myQuad would be the methods defined in the interface, but the implementation would be based on the implementation in Square. And any additional methods in Square that are not part of the IQuadrilateral interface would not be available unless you cast myQuad to a Square variable.

You can't create an instance of an interface.
The code you showed defines a variable of type IQuadrilateral. The actual instance this variable points to will always be of a concrete class implementing this interface.

Background Knowledge
Think of an interface as a contract. In a contract between two people, it defines what is capable, what is expected from the parties involved. In programming, it works the same way. The interface defines what to expect, what must exist for you to conform to that interface. Therefore, since it only defines what to expect, it itself, doesn't provide the implementation, the "code under the covers" so to speak, does.
A property behaves like a field, but allows you to intercept when someone assigns a value to it or reads the value. You can also deny reading or writing to it, your choice when you define the property. Interfaces work with properties instead of fields because of this. Since the "contract" is just defining what property should be there (name and type), and if it should allow a read or write capabilities, it leaves it up to the implementer to provide this.
Take for example the IEnumerator interface from the .NET framework. This interface was designed to allow iteration over a collection of objects. The purpose is not to change items, or randomly access them, it's just for getting object A and moving to the next, and the next, and the next, as many times as needed. Many collection type classes implement this: Queue, ArrayList, SortedList, Stack, etc. All these types of objects store many objects and now they all share the common "contract": the ability to iterate one-by-one over them.
However, you can see that the IEnumerator interface has a MoveNext() method declared. Why? This is because the items may not be served in the same manner. For example, people will generally access the ArrayList from the first item to the last. But a Stack was designed opposite, for people to access the last object down to the first.
Questions Answered
With all this knowledge, the limitation of declaring a variable as the interface type as opposed to the class type that implemented the interface is that you only get access to what the interface (the contract) says should be there. The benefit though is that you can assign to this variable any class type that implements the interface.

Related

Apply Visitor Pattern as an Extensibilty Mechanism for a single class

Let's say in my program I have a class called Robot that inherits from some other class.
Until now I have some methods inside Robot like addPart or getCost. Now I'm asked to add a new module of functionality to it (a few methods that use it's parts) but they explicitly ask the new module to be added with little to no impact to the current class.
I thought a Visitor could solve this but the thing is I won't be applying the pattern to a hierarchy. Is this a correct thing to do? (as you can see my Robot is part of a composite)
Fundamentally, I agree with your approach. You have successfully identified an approach that allows you to extend Robot (a parts composite) without having to actually modify the Robot class. The only changes I would make are the following:
I would introduce a new interface named something like IPartsComposite that would define the Accept method. This interface would be implemented by Robot since it is composed of Part instances.
The base Visitor would be a base generic class or interface i.e.Visitor<T>. This type would define a single method Visit(T). Then, in your case, you would have three concrete implementations of Visitor<IPartsComposite>.
PartsVisitorService
PartsVisitorCosts
PartsVisitorProduction
In each of these concrete classes you would implement Visit(IPartsComposite).

What are pure virtual methods in UML?

I am attempting to understand how I should use the realization of interfaces and the implementation of abstract classes in UML. I came across the post at https://stackoverflow.com/a/13438187/700543 whereby the poster states that pure virtual methods are interfaces whilst those that are part pure virtual methods are abstract classes. Is anyone able to give me a real world scenario and not one based on code?
An Interface is only a "class skeleton" for library users to extend, and as you said, methods cannot be implemented. An Abstract class can have implemented methods. I will give you a real life example:
Imagine I provide an Interface for people to implement sorting functions and I also provide a Class for bench marking sorting functions. My bench marking class only needs to know what methods of the Interface it needs to call in order to perform the bench marking, it does not know how they are implemented. Therefore, inside the bench marking class you might only see something like sortInterfaceInstace.getNumberOfSwap(), whereas sortInterfaceInstance is only known to be of sortInterface type at compile time, and not of any specific user sort implementation.
If you need implemented methods, use abstract instead of interfaces.
An interface only describes how something can be used, it provides none of the underlying implementation of how it gets done, i.e. a class with only pure virtual functions. An English analogy for an interface may be an adjective.
One example of an interface is a Movable interface. This interface may provide one pure virtual function move which tells the object to move to a given location. However, how it moves there is not implemented.
An abstract class on the other hand differs from an interface in that it provides some of the implementation details, but not all of them. These are conceptually high-level items that can be manipulated in certain ways, but when you get down to it the high-level item doesn't really exists or make sense by itself.
For example, say we have an abstract Shape class. The shape can have a certain origin which can be tracked independent of what Shape it is. The functions to transform the shape can be declared and implemented in the Shape class, saving the hassle of having to provide the same implementation in each sub-class. However, when you try to get the area or perimeter of the shape it's difficult to answer this without knowing more about the shape.

Usage of a correct collection Type

I am looking for a native, or a custom-type that covers the following requirements:
A Generic collection that contains only unique objects like a HashSet<T>
It implements INotifyCollectionChanged
It implements IENumerable<T> (duh) and must be wrappable by a ReadOnlyCollection<T> (duh, duh)
It should work with both small and large numbers of items (perhaps changing inner behaviour?)
the signature of the type must be like UniqueList<T> (like a list, not a key/valuepair)
It does not have to be sortable.
Searchability is not a "must-have".
The main purpose of this is to set up a small mesh/network between related objects.
So this network can only unique objects and there has to be a mechanism that notifies the application when changes in the collection happen.Since it is for a proof-of-concept the scope is purely within the assembly (no db's or fs are of any importance).
What is a proper native type for this or what are the best ingredients to create a composite?
Sounds like you could just wrap HashSet<T> in your own type extremely easily, just to implement INotifyCollectionChanged. You can easily proxy everything you need - e.g. GetEnumerator can just call set.GetEnumerator() etc. Implementing INotifyCollectionChanged should just be a matter of raising the event when an element is added or removed. You probably want to make sure you don't raise the event if either you add an element which is already present or remove an element which isn't already present. HashSet<T>.Add/Remove both return bool to help you with this though.
I wouldn't call it UniqueList<T> though, as that suggests list-like behaviour such as maintaining ordering. I'd call it ObservableSet<T> or something like that.

Shared Domain Logic?

Take for example:
CreateOrderTicket(ByVal items As List(Of OrderItems)) As String
Where would you put this sort of logic given:
CreateOrder should generate a simple list ( i.e. Item Name - Item Price )
PizzaOrderItem
SaladBarOrderItem
BarOrderItem
Would you recommend:
Refactoring common to an abstract class/interface with shared properties a method called CreateOrderTicket
Or,
Creating a common service that exposes a CreateOrderTicket
We obviously would not want three createOrderTicket methods, but adding methods, inheriting, overloading and using generics seem like a high cost just to abstract one behaviour..
Assume for the sake of a simple example that (currently) there is no OrderItem baseclass or interface..
Help!! :)
p.s. Is there a way to overload without forcing all inheriting objects to use the same name?
Abstract base class sounds like the best option in this situation. Of course it all depends on what kind of shared behaviour these items have. Without knowing more, I'd guess all of these order items have Name and Price for example - and in future you might add more common stuff.
Without a shared base class which contains the Name and Price properties, you'll probably have troubles implementing a CreateOrderTicket method which takes a list containing more than 1 kind of orders.
Also I don't think inheriting from an abstract base class would be that high cost as technically the objects already derive from the Object base class. (Though I don't think this is completely equal to a custom base class.)
VB.Net can implement methods from an interface using a different name than the one specified in the interface but don't think the same goes for overriding abstract functionality.

LabVIEW Objects

I have a base class object array into which I have typecasted many different child class objects and am passing it to a sub vi. Is there any way by which I can find out the original type of the object of each individual elements in the array?
Thanks ...
For posterity, this was crossposted to the LAVA forums. The user Aristos Queue, one of the developers of LabVIEW's native OO features, answered with the following:
Using a dynamic dispatch method in every class is the recommended way of handling this, although the recommendation is to create a method that does whatever it is you're trying to do. I'm guessing that you're thinking of a dynamic dispatch method that returns a name or ID of the object so you can say, "Is it equal to this? Ok, then it must be this class..." and then you do Action X if it is that class. If you write a dynamic dispatch method ActionX.vi and then override it appropriately, you'll save yourself on performance and have much easier time for code maintenance in the future.
You can also use the To More Specific node to test if a given object can be downcast to a given type -- this allows for inheritance testing as opposed to the name or ID comparison that only does type equivalence. If the To More Specific node returns an error then it is not of the destination type.
So your options are (in order of preference):
dynamic dispatch method that does the action
To More Specific node to do type testing
dynamic dispatch method that returns name/ID of the class of the object
Get Path of LabVIEW Object.vi (shipped in vi.lib in LabVIEW 8.5 but not added to the palettes until LabVIEW 8.6)
NI has a good overview of LVOOP that is a must-read, since OO is implemented in a unique way for LabVIEW.
Have you tried the 'to more generic class' and 'to more specific class' functions, on the application control palette?

Resources