Inheritance in C++/WinRT Windows Runtime Components - c++-winrt

I have a couple of questions related to inheritance in Windows Runtime Components authored using C++/WinRT. Firstly why is there a restriction that classes, if they have a base class, must have ultimately derive from a class in the Windows.* namespace?
Secondly, what is the best way to work around this. In fact I don't really want consumers to be able to derive from my class, but I'd like to derive from a base class in the implementation in order not to rewrite code. At the moment my implementation class is a lightweight wrapper around a standard C++ class that uses standard C++ inheritance. But is there a way to simplify this? Can a list one implementation class as the base class of another? I am mainly familiar with C# where multiple inheritance is not possible, so am not sure about this sort of thing.

Any runtime class (that you declare in your application) that derives from a base class is known as a composable class. The ultimate base class of a composable class must be a type originating in a Windows.* namespace;.
And if you want to inherit custom runtimeclass, the Windows App Certification Kit tests will produce errors. From this thread, it seems that you can only declare a C++ native class and implement the interfaces. Let the implementation classes inherit from it.

Related

Abstract and interfaces together

I am struggling to understand both abstract and interface approach. Since i get the idea what is the purpose to use one over another is clear. I was trying to found whatever example of using them both in action however all tutorials are how to use interface over abstract or vice versa showing usage either for one or another. I would really love to see practical example which could show both in action best on some real life example. Additional comments why in specific case you used one over another appreciated. Generics are very welcome to see as well in such example.
I'll propose foloowing example. We got some engine to get files from diffrent locations which could be taken using diffrent protocols as follows. I would like to understand on this example how this could be accomplished with both interfaces and abstract.
'As all of protocol has to close and open would it be good to put in abstract?
abstract class Collector
Protected Id
Protected Name
MustInherit Sub OpenConnection
MustInherit Sub CloseConection
End Class
'?
class Ftp : Collector
class Sftp: Collector
class Soap: Collector
'Interface?
Public Interface IRepository(Of T, Tkey)
Function GetAllFiles() As IEnumerable(Of T)
Function GetAllById(Tkey) as IEnumerable(Of T)
End Interface
Some key distinctions:
An abstract class can contain some implementation. An interface cannot.
In .NET, a class can not inherit from multiple base classes.
A class can implement multiple interfaces
The choice of which approach is really up to you. In general, it's a choice between the Composition pattern or Inheritance.
Composition uses Interfaces. Think of an object as having X.
Inheritance uses Classes. Think of an object as being X.
In either case, an abstract class or an interface is just a Type, through which you will access and manipulate them. For example, if you have some code that wants to perform Insert/Update/Delete operations, it doesn't need to know that the object it is operating on is a FTP client--only that the object has the ability to support these operations. (and that is exactly what IRepository specifies)
You definitely can combine both. There's no reason a concrete FtpClient class couldn't inherit from an abstract Protocol class and also implement the IRepository interface. It could even use generics!
Interfaces are great for decoupling your code, and also great for unit test mocks.
There is also a good summary of pros & cons on Wikipedia (Composition_over_inheritance). Pros:
To favor composition over inheritance is a design principle that gives the design higher flexibility. It is more natural to build business-domain classes out of various components than trying to find commonality between them and creating a family tree. For example, a gas pedal and a wheel share very few common traits, yet are both vital components in a car. What they can do and how they can be used to benefit the car is easily defined. Composition also provides a more stable business domain in the long term as it is less prone to the quirks of the family members. In other words, it is better to compose what an object can do (HAS-A) than extend what it is (IS-A).
Initial design is simplified by identifying system object behaviors in separate interfaces instead of creating a hierarchical relationship to distribute behaviors among business-domain classes via inheritance. This approach more easily accommodates future requirements changes that would otherwise require a complete restructuring of business-domain classes in the inheritance model. Additionally, it avoids problems often associated with relatively minor changes to an inheritance-based model that includes several generations of classes.
Cons:
One common drawback of using composition instead of inheritance is that methods being provided by individual components may have to be implemented in the derived type, even if they are only forwarding methods. In contrast, inheritance does not require all of the base class's methods to be re-implemented within the derived class. Rather, the derived class only needs to implement (override) the methods having different behavior than the base class methods. This can require significantly less programming effort if the base class contains many methods providing default behavior and only a few of them need to be overridden within the derived class.
I don't understand why you want to have an example combining both. Let's just say both are valid ways to build solid software architecture. They're just two tools - like having a kitchen knife and a meat cleaver. You won't necessarily use them together but see the pro's and con's when looking at the dinner you want to serve.
So usually you take abstract/MustInherit classes if you want to provide a common denominator. Sub-classes derive from the abstract one and have to implement the methods just like they would if they implemeted an interface. The good thing here is that abstract classes can provide "base logic" which can be developed centrally and all the sub-classes can make use of that. In the best case, abstract classes provide kind of "hooks" to plug in special logic in the sub-classes.
Interfaces describe what a class has to fulfill. So everything an interface defines has to be implemented in classes implementing the interface. There's no reusable logic built-in in this approach like in abstract base classes but the big "pro" for interfaces is that they don't take away the single base type you can derive from like abstract classes do. So you can derive from anything or nothing and still implement an interface. AND: You can implement multiple interfaces.
One word to the "reusable logic" with interfaces. While this is not really wroing, the .NET framework allows use to write extension methods on types (and interfaces) to attach externally developed code. This allows code reuse with interfaces like having a method implemented in there. So for example, you could write an extension method None() for the interface IEnumerable which is checking whether the enumerable is empty.
public static bool None(this IEnumerable values)
{
return !values.Any();
}
With this, None() can be used on any IEnumerable in your code base having access to the extension method (in fact, Any(), Select(), Where(), etc. are extension methods as well, lying in the System.Linq namespace).

Changing interface in C++

I am reading an article on extension of interface at following link.
http://wiki.hsr.ch/APF/files/ExtensionInterface.pdf
It has been mentioned here on page 142
Over time the addition of these requests can bloat the interface with
functionality not anticipated in the initial framework design. If new
methods are added to the "universalComponent" interface directly, all
client code must be updated and recompiled. This is tedious and
error-prone.
My question is (Assume we are using C++ to develop)
Why we have to compile client code if we add new methods to interface and not
modifying any existing functions in interface?
Thanks!
I haven't read the article, but for starters, I would suggest to de-emphasize the terms "method" and "interface" in C++. Those terms are popular in strict OO languages like Java, but C++ is a broader, multi-paradigm language.
With that said, "adding methods to interfaces" is really just adding more virtual member functions to a base class. Changing the base class changes the definition of all derived classes, and thus all code that requires the complete type of any derived class or of the base class must be recompiled.
C++ types are not a runtime feature. Types only exist at compile time, and the compiler must have full access to the type definitions. (Again in contrast to other languages!) The interface-implementation relationship exists purely at compile-time and cannot be "precompiled". So there's really no such thing as "modifying the interface" that would produce runtime-modularity. The "interface" concept is just a neat mnemonic that you can use when designing your application, but it does not save you from recompiling. Changing a class definition changes the internal representation of the class, and you cannot (in general) make a correct C++ program unless all parts of the program see the same class definitions.
Adding a method to a class that is involved in polymorphism (means it has at least one virtual member function) potentially changes the binary layout of objects of that class and it's subclasses.

Interface uses as like this

If interfaces have empty methods (implicit abstract method) then what is its use? Why do we say it reduces the code and provides re-usability? Give me a real life example of using an interface that shows the difference between an abstract class and an interface.
Interface is more like a contract. It doesn't provide any implementation reuse as such. Which actually makes your code de-coupled from implementation. Having a abstract class with ALL the methods abstract provides the same benefit (if we ignore the issue of multiple inheritance).
For a really good example take a look at Java Collections and how things are loosely coupled using interfaces for Collection, Map and Lists.
Because of the terminology you are using, I am going to assume you are talking about Java.
An interface is useful in lieu of an abstract class because a class can only inherit from a single class, but can implement multiple interfaces.
An interface is a contract between parts of the program. It says that one part of the program has certain expectations about classes that implement this interface. As long as those classes uphold that interface contract, the other parts of the program don't care how that contract is implemented, just that it is implemented.
It allows for polymorphism and for the reuse of code. For instance, (with respect to Java), you can take the List interface. You can write code that interfaces with a List object where you don't care about the implementation of the List. Your code then can be used with a LinkedList or an ArrayList or any other type of list that it may deal with, and it should be able to manage well enough. You can write code now that has certain expectations through this List interface contract, and 15 years down the road someone can use the latest technologies to create their own List implementation and your code will be able to use it.
Abstract class lets you describe fields and non abstract methods. It does not limit you to simply describing interface, it involves some logic. Interface on other hand does what it says and has nothing to do with logic. From client code side, you have no worries about implementation and how stuff works. It lets you exchange one interface realization with other without additional code.
On realization code side, interface lets you perform multiple "inheritance".
I like to call these types of features "implied code documentation". Using an interface can communicate a lot of information to other developers who will be working on your project, and this information can help prevent a lot of headaches.
For instance, if a class implements an interface that has 2 methods, and I'm new to the project, that may tell me that the developer who wrote those methods don't want the method signature to change.
Think about the Dog class and the Cat class that both implement the interface Sociable, where there are methods walk(int speed), sit(), layDown(), bite(int degree).
If we have a Dog class and a Cat class that implement these methods and there are dependencies on them, changing the method signature of one could have some negative effects.
Interfaces are a way to help describe a class. In this example, a Sociable Dog and a Sociable Cat have a lot in common.
As far as reusability goes, your classes become reusable because it's harder for others to come in and change the contract defined in the method signature.
Lastly, while a class can only subclass one class, it can implement multiple interfaces. Thus, the advantage of using an interface is that I can have a Dog that implements Big and Sociable, and a Cat that implements Small and Sociable.

Supressing warning for a class (trying to simulate an Abstract class in objc)

This is the situation. I've been a C++ programmer for ages. I like abstract classes and "interfaces" so I would likt to do the same using objc.
I use a protocol for my interfaces, but the problem is that when my abstract class inherits from the protocol (I don't want to implement it here) I get warnings like:
warning: method definition for 'XXXXX' not found and 'XXXXX' class does not fully implement the 'XXXXXX' protocol.
Is there anyway to supress this? I hope child classes of this ones will throw "correct warnings" if base class did not implemented the protocol.
Another option is to inherit from the protocol just when needed, but I like to force this in the base class to make sure inherited implementes the interface.
Any tip?,
Thanks in advance.
When you implement a protocol in an Objective-C class, you have to implement all the methods. However, you can provide stub implementations. This mailing list post describes how to use doesNotRecognizeSelector: in "abstract" classes.
I don't think there is a solution in a way you are looking for. You must define all methods declared in the protocol, at least implement them as an empty methods.
I understand that you are looking for a C++ like code, but Obj-C is different and we must live with it. Also, gcc supports c++/obj-c mix, so you can write some part of the project in pure C++ what is great when you need some low-level code or want something easy to port.

When to use interfaces or abstract classes? When to use both?

While certain guidelines state that you should use an interface when you want to define a contract for a class where inheritance is not clear (IDomesticated) and inheritance when the class is an extension of another (Cat : Mammal, Snake : Reptile), there are cases when (in my opinion) these guidelines enter a gray area.
For example, say my implementation was Cat : Pet. Pet is an abstract class. Should that be expanded to Cat : Mammal, IDomesticated where Mammal is an abstract class and IDomesticated is an interface? Or am I in conflict with the KISS/YAGNI principles (even though I'm not sure whether there will be a Wolf class in the future, which would not be able to inherit from Pet)?
Moving away from the metaphorical Cats and Pets, let's say I have some classes that represent sources for incoming data. They all need to implement the same base somehow. I could implement some generic code in an abstract Source class and inherit from it. I could also just make an ISource interface (which feels more "right" to me) and re-implement the generic code in each class (which is less intuitive). Finally, I could "have the cake and eat it" by making both the abstract class and the interface. What's best?
These two cases bring up points for using only an abstract class, only an interface and using both an abstract class and an interface. Are these all valid choices, or are there "rules" for when one should be used over another?
I'd like to clarify that by "using both an abstract class and an interface" that includes the case when they essentially represent the same thing (Source and ISource both have the same members), but the class adds generic functionality while the interface specifies the contract.
Also worth noting is that this question is mostly for languages that do not support multiple inheritance (such as .NET and Java).
As a first rule of thumb, I prefer abstract classes over interfaces, based on the .NET Design Guidelines. The reasoning applies much wider than .NET, but is better explained in the book Framework Design Guidelines.
The main reasoning behind the preference for abstract base classes is versioning, because you can always add a new virtual member to an abstract base class without breaking existing clients. That's not possible with interfaces.
There are scenarios where an interface is still the correct choice (particularly when you don't care about versioning), but being aware of the advantages and disadvantages enables you to make the correct decision.
So as a partial answer before I continue: Having both an interface and a base class only makes sense if you decide to code against an interface in the first place. If you allow an interface, you must code against that interface only, since otherwise you would be violating the Liskov Substitution Principle. In other words, even if you provide a base class that implements the interface, you cannot let your code consume that base class.
If you decide to code against a base class, having an interface makes no sense.
If you decide to code against an interface, having a base class that provides default functionality is optional. It is not necessary, but may speed up things for implementers, so you can provide one as a courtesy.
An example that springs to mind is in ASP.NET MVC. The request pipeline works on IController, but there's a Controller base class that you typically use to implement behavior.
Final answer: If using an abstract base class, use only that. If using an interface, a base class is an optional courtesy to implementers.
Update: I no longer prefer abstract classes over interfaces, and I haven't for a long time; instead, I favour composition over inheritance, using SOLID as a guideline.
(While I could edit the above text directly, it would radically change the nature of the post, and since a few people have found it valuable enough to up-vote it, I'd rather let the original text stand, and instead add this note. The latter part of the post is still meaningful, so it would be a shame to delete it, too.)
I tend to use base classes (abstract or not) to describe what something is, while I use interfaces to describe the capabilities of an object.
A Cat is a Mammal but one of it's capabilities is that it is Pettable.
Or, to put it a different way, classes are nouns, while interfaces map closer to adjectives.
From MSDN, Recommendations for Abstract Classes vs. Interfaces
If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.
If you want to provide the option of replacing your implementation completely, use an interface. This applies especially for interactions between major components, these should always be decoupled by interfaces.
There may also be technical reasons for prefering an interface, for example to enable mocking in unit tests.
Internally in a component it may be fine to just use an abstract class directly to access a hierarchy of classes.
If you use an interface and have a hierarchy of implementing classes then it is good practice to have an abstract classe which contain the common parts of the implementation. E.g.
interface Foo
abstract class FooBase implements Foo
class FunnyFoo extends FooBase
class SeriousFoo extends FooBase
You could also have more abstract classes inheriting from each other for a more complicated hierarchy.
Refer to below SE question for generic guidelines:
Interface vs Abstract Class (general OO)
Practical use case for interface:
Implementation of Strategy_pattern: Define your strategy as an interface. Switch the implementation dynamically with one of concrete implementations of strategy at run time.
Define a capability among multiple unrelated classes.
Practical use case for abstract class:
Implementation of Template_method_pattern: Define a skeleton of an algorithm. The child classes can't change strucutre of the algortihm but they can re-define a part of the implementation in child classes.
When you want share non-static and non-final variables among multiple related classes with "has a" relation.
Use of both abstradt class and interface:
If you are going for an abstract class, you can move abstract methods to interface and abstract class can simply implement that interface. All use cases of abstract classes can fall into this category.
I always use these guidelines:
Use interfaces for multiple TYPE inheritance (as .NET/Java don't use multiple inheritance)
Use abstract classes for a re-usable implementation of a type
The rule of the dominant concern dictates that a class always has a main concern and 0 or more others (see http://citeseer.ist.psu.edu/tarr99degrees.html). Those 0 or more others you then implement through interfaces, as the class then implements all the types it has to implement (its own, and all interfaces it implements).
In a world of multiple implementation inheritance (e.g. C++/Eiffel), one would inherit from classes which implement the interfaces. (In theory. In practise it might not work that well.)
There is also something called the DRY principle - Don't Repeat Yourself.
In your example of data sources you say there is some generic code that is common between different implementations. To me it seems that the best way to handle that would be to have an abstract class with the generic code in it and some concrete classes extending it.
The advantage is that every bug fix in generic code benefits all concrete implementations.
If you go interface only you will have to maintain several copies of the same code which is asking for trouble.
Regarding abstract + interface if there is no immediate justification for it I would not do it. Extracting interface from abstract class is an easy refactoring, so I would do it only when it is actually needed.