Inheritance & Virtual Interface in systemverilog? - oop

Multiple inheritance is very general OOPS concept, then why it is not implemented in systemverilog and only single inheritance is allowed?
2nd why interfaces are not allowed inside class? Is it because of storage implementation like dynamic storage in class and static in modules, programs, interface?

This really should be two separate posts for your two distinct questions. Unfortunately the keyword interface will be used to answer both of them with entirely separate meanings.
I wrote a 2010 DVCon paper describing some of the reasons that multiple inheritance was not in the original SystemVerilog LRM, and possible solutions. SystemVerilog 1800-2012 did add multiple interface class inheritance and here is a link to a good description of that feature. This use of the keyword interface as a kind of class has nothing to do with the interface in your 2nd question.
You are mostly correct about why interface instances are not allowed in classes. An SV interface is very similar to the design elements module and program that are instances of hierarchical containers. During the process of elaboration, these containers get flattened out before simulation begins. Class instances are only constructed at run-time by executing procedural code.
The elaboration process is particular to hardware description languages and is part of the the code generation and replication process. It is also what allows you to hierarchically reference signals throughout the design without the use of pointers. Class objects on the other hand, are only referenced through dynamically created handles.

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).

What problems does the Abstract Factory design pattern solve?

The intent of the Abstract Factory design pattern is to
"Define an interface for creating families of related or dependent objects
without specifying their concrete classes." [GoF]
This is a short statement of what the design pattern does (solution),
but it isn't clear what particular design problems it solves.
I would define the
following design, refactoring, and test problems,
but I am not sure whether this list is complete.
Design Problems
Creating Objects and Object Families
How can a system support creating different families of objects
so that which family to create can be selected and changed dynamically?
How can a system be configured with a family of objects?
And how can the whole family of objects be exchanged dynamically?
How can the way objects are created (which classes are instantiated)
be changed independently?
How can a system be independent of how its objects are created?
Creating Consistent Object Families
How can be ensured that a system creates objects from only one of different
families at a time?
Refactoring Problems
Distributed Creation Code
How can instantiating concrete classes throughout an application be refactored?
How can creation code that is distributed across many classes be centralized?
Testing Problems
Unit Tests
How can creating objects and object families be designd
so that object creation can be mocked easily for unit testing?
Keeping the long story short - if in the future a new group of objects is introduced in your current OO design, a new factory will be derived from AbstractFactory, encapsulating creation of all concrete objects related to that group. It’s that simple.
As addition is also important to say that
“This pattern defines an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses".
In short we need a class here which will do all the common tasks and expose a virtual or abstract function.
So creating AbstractFactory will encapsulate common functionalities with an additional overridable (virtual or abstract) method and then recreate our SubFactoryA and SubFactoryB. By doing so - you'll achieve common architecture, propagate minimum/default set of practices, standards etc. Here is a very good article about all this.

Can Coldfusion components share methods without being descendants of the same super class

We have used a homegrown version of object oriented coldfusion for a while and I'm just starting to experiment with cfc's and how it "should" be done...
If I understand correctly, cfinterface defines the signature of functions, and any class that implements that interface must have their own functions to do whats defined in the interface.
I'm kind of trying to do the opposite - the interface doesn't just define the function's signature, but also defines the logic of the function and anything that implements that interface can use its functions without having to define it itself. Does that exist besides creating subclasses?
For example, say you have classes A,B,C,D that all belong to the Animal class
A & B can walk
A & C can talk
B & D can sleep
Suppose the logic of walk, talk & sleep (if the object can do it) is the same regardless of the class doing it
Ideally, if A & B both implement the walking interface, they can walk without defining a separate walk method in each class.
Or borrowing a better example from this java multiple inheritance question
A Pegasus is a mix of a Horse and a Bird because it runs like a horse
but flies like a bird
Is that possible? (I think this is multiple inheritance?)
In short: no, an interface only defines a contract, it does not (and cannot) define functionality). Also CFML does not have the concept of multiple inheritance.
You will have to use single-inheritance and concrete implementations to effect what you need. I can't be bothered assessing your implementation-sharing requirements to work out what an approrpriate class hierarchy might be to minimise code duplication. I'm sure you can do that yourself (and it's not really part of your question anyhow).
One tactic you could try is to use mixins for your common methods. Store the common methods in a different library, and then inject them into your objects as required. So basically Mixins.cfc would implement walk(), talk(), sleep(), and you'd have an AFactory.cfc, BFactory.cfc, CFactory.cfc. When asking a factory for a new A, B or C, and the factory method injects the mixin methods before returning the instances. Obviously this is a fairly cumbersome process, and you'd want to use some sort of IoC container to manage all this.
A better question might come out of you showing us more real world examples... I suspect your domain design could perhaps stand improvement if you find yourself needing to do what your example suggests. Actual design requirements are seldom exposed with examples using animals.
You can do similar things with WireBox and its Virtual Inheritance feature:
http://wiki.coldbox.org/wiki/WireBox.cfm#Virtual_Inheritance
// Declare base CFC
map("BaseModel").to("model.base.BaseModel");
map("UserService").to("model.users.UserService").virtualInheritance("BaseModel");
It's basically very similar to what Adam described above; a base class is created, and references to it's public members are placed in the sub class.
https://github.com/ColdBox/coldbox-platform/blob/master/system/ioc/Builder.cfc#L535
There's no reason why you can't build something similar but you should know this has already been done.
Full disclosure, I am a contributing member of the *Box community.

What is the difference between subtyping and inheritance in OO programming?

I could not find the main difference. And I am very confused when we could use inheritance and when we can use subtyping. I found some definitions but they are not very clear.
What is the difference between subtyping and inheritance in object-oriented programming?
In addition to the answers already given, here's a link to an article I think is relevant.
Excerpts:
In the object-oriented framework, inheritance is usually presented as a feature that goes hand in hand with subtyping when one organizes abstract datatypes in a hierarchy of classes. However, the two are orthogonal ideas.
Subtyping refers to compatibility of interfaces. A type B is a subtype of A if every function that can be invoked on an object of type A can also be invoked on an object of type B.
Inheritance refers to reuse of implementations. A type B inherits from another type A if some functions for B are written in terms of functions of A.
However, subtyping and inheritance need not go hand in hand. Consider the data structure deque, a double-ended queue. A deque supports insertion and deletion at both ends, so it has four functions insert-front, delete-front, insert-rear and delete-rear. If we use just insert-rear and delete-front we get a normal queue. On the other hand, if we use just insert-front and delete-front, we get a stack. In other words, we can implement queues and stacks in terms of deques, so as datatypes, Stack and Queue inherit from Deque. On the other hand, neither Stack nor Queue are subtypes of Deque since they do not support all the functions provided by Deque. In fact, in this case, Deque is a subtype of both Stack and Queue!
I think that Java, C++, C# and their ilk have contributed to the confusion, as already noted, by the fact that they consolidate both ideas into a single class hierarchy. However, I think the example given above does justice to the ideas in a rather language-agnostic way. I'm sure others can give more examples.
A relative unfortunately died and left you his bookstore.
You can now read all the books there, sell them, you can look at his accounts, his customer list, etc. This is inheritance - you have everything the relative had. Inheritance is a form of code reuse.
You can also re-open the book store yourself, taking on all of the relative's roles and responsibilities, even though you add some changes of your own - this is subtyping - you are now a bookstore owner, just like your relative used to be.
Subtyping is a key component of OOP - you have an object of one type but which fulfills the interface of another type, so it can be used anywhere the other object could have been used.
In the languages you listed in your question - C++, Java and C# - the two are (almost) always used together, and thus the only way to inherit from something is to subtype it and vice versa. But other languages don't necessarily fuse the two concepts.
Inheritance is about gaining attributes (and/or functionality) of super types. For example:
class Base {
//interface with included definitions
}
class Derived inherits Base {
//Add some additional functionality.
//Reuse Base without having to explicitly forward
//the functions in Base
}
Here, a Derived cannot be used where a Base is expected, but is able to act similarly to a Base, while adding behaviour or changing some aspect of Bases behaviour. Typically, Base would be a small helper class that provides both an interface and an implementation for some commonly desired functionality.
Subtype-polymorphism is about implementing an interface, and so being able to substitute different implementations of that interface at run-time:
class Interface {
//some abstract interface, no definitions included
}
class Implementation implements Interface {
//provide all the operations
//required by the interface
}
Here, an Implementation can be used wherever an Interface is required, and different implementations can be substituted at run-time. The purpose is to allow code that uses Interface to be more widely useful.
Your confusion is justified. Java, C#, and C++ all conflate these two ideas into a single class hierarchy. However, the two concepts are not identical, and there do exist languages which separate the two.
If you inherit privately in C++, you get inheritance without subtyping. That is, given:
class Derived : Base // note the missing public before Base
You cannot write:
Base * p = new Derived(); // type error
Because Derived is not a subtype of Base. You merely inherited the implementation, not the type.
Subtyping doesn't have to be implemented via inheritance. Some subtyping that is not inheritance:
Ocaml's variant
Rust's lifetime anotation
Clean's uniqueness types
Go's interface
in a simple word: subtyping and inheritance both are polymorphism, (inheritance is a dynamic polymorphism - overriding). Actually, inheritance is subclassing, it means in inheritance there is no warranty to ensure capability of the subclass with the superclass (make sure subclass do not discard superclass behavior), but subtyping(such as implementing an interface and ... ), ensure the class does not discard the expected behavior.

In OOP what are the different meanings of interface in the different contexts they apply to [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I'm a bit new to object oriented programming. On my journey I have come across something that has had me confused for a few days now. It is the term "interface" and how it has different meanings in different contexts and even different programming languages. I want to understand "interface" but when I do my research I seem to get different definitions as if it has multiple meanings.
Would someone kindly give me a concise definition of interface in each context (just the main ones)?
I purchased a book called the object oriented thought process by Matt Weisfeld where some of them have been identified which are below:
Graphical user interface
The interface to a class is basically the signatures of its methods
Objective-C code can be broken up into physically separate modules called interface and impelentation
A Java-style interface and an Objective-C protocol are basically the contract between a parent class and a child class
(Are there any more uses/definitions of the term interface in OOP than those identified above?)
If someone would kindly explain the different contexts of the term interface in OOP it would be highly appreciated.
Short answer:
Your 4th bullet point probably comes closest to the generally accepted notion of what OOP interfaces are: contracts between parties that need to interact with one another. Such contracts define the means (a) provided by one party, and (b) required by the other, in order to do so.
Long answer:
Very generally speaking, an interface is a thing that allows two (possibly very different) entities to interact with each other; it enables them to work together while at the same time allowing them to stay apart. The interface is the "common ground" that both parties agree on.
(Can be as simple as a door lock: Both the lock and any key able to work it must "fit together" in one place; you could call that place the interface.)
How does this general definition apply to your list?
Graphical user interface
A GUI allows humans and computer programs to interact. It does not require the computer to become fully human (and listen with ears, talk with the mouth, smile, etc.), neither does it require of the human to become a computer program itself. (UIs from past decades excluded. :)
"The interface to a class is basically the signatures of its methods"
The (publicly visible) methods and their exact signatures are the only means by which other types are going to be able to interact with that class, so in that sense, they together form that class' interface.
Also, a general description of each constructor and method is typically a part of the interface as well as a short general description of the purpose of the class and each of its methods. And of course, the name of the class itself -- pretty important.
"Objective-C code can be broken up into physically separate modules called interface and [implementation]"
I don't know Objective-C well enough to comment on that, but many languages have a module system that allows you to partition your codebase into separate, functionally independent modules. These usually don't have to expose all their types and functions to outsiders; each module may carefully declare what can be seen by other modules. As above, all that is chosen to be exposed is the "interface", because it will be the only way to interact with whatever is in the module. That "whatever is in the module" stays hidden; it's called the "implementation", and outsiders should not have to know about it.
"A Java-style interface and an Objective-C protocol are basically the contract between a parent class and a child class"
This is perhaps what comes closest to the generally accepted notion of interfaces in OOP: That they are contracts between parties that want to interact. See short answer at the beginning of this question.
Basically, a Java interface allows us to describe a group of methods and their exact signatures, but it won't allow us to provide the implementation. Therefore it's a pure interface; it cannot be called directly. It only describes how one could interact with a class that actually implemented it. (The two parties do not necessarily have to be "parent" and "child".)
Ideally, an interface should not just state what one class has to offer; it should also describe what a typical consumer will need, thereby keeping the interface focused in a well-encapsulated system. (I am referring to the Single-Responsibility Principle here.)
Interface is a concept of abstraction and encapsulation. It is basically a contract you should comply to or given to ie, Interface is just a contract between two parties so that they know how they will interact with each other. An interface generally defines how you can interact with a class, the methods that it supports.
An interface contains only the signatures of the methods. The methods dont have anything neither interface can do anything. It is just a pattern.
Now in this anAbstarctMethod() is the Interface which is defined and it only has signatures but it doesnot have the implementation. Now when the class ASubClass implements the ineterface then the actual implementation is provided to the interface.
As far as Graphical user Interface is concerned I dont think that may necessarily be Object Oriented Programming. The wiki says that a graphical user interface is just a user interface through which you can interact with the electronic devices through icons and other indicators.
The Java doc has given a good example for this:-
Methods form the object's interface with the outside world; the
buttons on the front of your television set, for example, are the
interface between you and the electrical wiring on the other side of
its plastic casing. You press the "power" button to turn the
television on and off.
A good example from here:-
An interface is a description of the actions that an object can do...
for example when you flip a light switch, the light goes on, you don't
care how, just that it does. In Object Oriented Programming, an
Interface is a description of all functions that an object must have
in order to be an "X". Again, as an example, anything that "ACTS LIKE"
a light, should have a turn_on() method and a turn_off() method. The
purpose of interfaces is to allow the computer to enforce these
properties and to know that an object of TYPE T (whatever the
interface is ) must have functions called X,Y,Z, etc.
You may also check Why Use Interfaces?
Another powerful design technique is to have a single class implement
multiple interfaces. If you do this, you will have objects that
support multiple interfaces and, therefore, multiple behaviors. When
used together with run-time type inspection, this becomes very
powerful.
In OOP, the term "interface" means basically all the method signatures for all the messages that can be sent to objects of a class. So in Objective-C, it would be all the method declarations in the header file.
The term "Graphical User Interface" is not using the word "interface" in an OO context.
Item #2 on your list is an OO interface.
Item #3 is referring to the .h and .m files.
Item #4 refers to the keyword 'interface' in the Java language and equating it to the keyword 'protocol' in the objective-C language.
General meaning:
An Interface is essentially something that interacts with something else
For example: An interface can be with a python application and the Skype-API (thought off the top of my head xD)
An interface is a form of multiple inheritance (without the 'alleged' complications that brings) (it's a controversial subject)
OO is founded on the "is a" relationship, MI (multiple inheritance) allows an object to be several things. Interfaces define a way for them to be these things, without an implementation.
They are "what you must to _to be a _ whatever".