Difference between sc_port and sc_export - systemc

Can someone clearly and intuitively explain what is the difference between an sc_port and an sc_export in SystemC? When does one use a port, and when an export?
I've been reading portions of the manual but I still fail to grasp the main conceptual difference between the two.

SystemC requirement is that every port or export MUST be bound/connected to a channel (exception of unbound ports, but let us ignore them for now). Where this channel is instantiated is what differentiates ports and exports.
For an export, the channel instance MUST reside within the same module that has the export, or inside a submodule located inside it.
For a port, the channel instance MUST reside outside the module with the port.
Imagine a module top_module with two submodules sender and receiver instantiated inside it with a one-bit data connecting sender to receiver. If you choose to make the sender's output data to be of type sc_port<>, then you will need to instantiate the channel, say sc_signal<>, in the top_module and the bind statement would ideally be in the constructor of the top_module. But if you choose to make the sender's output data to be of type sc_export<>, then you will need to instantiate the channel inside the submodule sender. Because you are essentially "exporting" the functionality of the channel to the world outside of sender.
This is my intuitive understanding of ports and exports. Please take my "MUST" statement with a grain of salt as the Accellera implementation enforces no such rule but has more to do with binding order (top-down vs bottom-up) than anything else.
As a thumb-rule, I always use exports for outputs and ports for inputs for all my modules. My philosophy is, "you drive it, you own it".

From IEEE Standard for Standard SystemC ® Language Reference Manual
Class sc_export allows a module to provide an interface to its parent module. An export forwards interface
method calls to the channel to which the export is bound. An export defines a set of services (as identified by
the type of the export) that are provided by the module containing the export.
Providing an interface through an export is an alternative to a module simply implementing the interface.
The use of an explicit export allows a single module instance to provide multiple interfaces in a structured
manner.
If a module is to call a member function belonging to a channel instance within a child module, that call
should be made through an export of the child module.
The upshot of all this being that without sc_export one would need to create an sc_port in the parent module and connect it to the port of the child module in order to expose a child's port as a port of the parent module. Using sc_export allows one to directly expose a child port as port of the parent module. Simply create an instance of sc_export and bind it to a child port.
For a full description and class specification see section 5.13 of IEEE Standard for Standard SystemC ® Language Reference Manual
p.s. If you do not intend to convert your code to VHDL then there is no need to use sc_export. SystemC is just standard C++ and ports are just normal public members (you could have a private port but there hardly seems much point) so you can just take a reference to it and pretend that it's a member of its parent module or any other module that has access to it for that matter.

Related

Facade in Object Oriented Programming

In OOP, should a Facade be an object or just a class? Which is better?
Most of the examples in Wikipedia creates Facade as an object which should be instantiated before use.
CarFacade cf = new CarFacade();
cf.start();
Can it be designed to be like this instead?
CarFacade.start();
UPDATE
Can a Facade facilitate a singleton?
A facade
represents a high level API for a complex subsystem (module).
reduces client code dependencies.
This means that your client code only uses the facade and does
not have a lot of dependencies to classes behind that facade.
It is better to use an instance of an interface, because
you can replace it for tests. E.g. mock the subsystem the facade represents.
you can replace it at runtime.
When you use a static methods, your client code is bound to that method implementations at compile-time. This is usually the opposite of the open/close principle.
I said "usually the opposite", because there are examples when static methods are used, but the system is still open for extension. E.g.
ServiceLoader
The static load methods only scan the classpath and lookup service implementations. Thus adding classes and META-INF/services descriptions to the classpath will add other available services without changing the ServiceLoader's code.
Spring's AuthenticationFacade for example uses a ThreadLocal internally. This makes it possible to replace the behavior of the AuthenticationFacade. Thus it is open for extension too.
Finally I think it is better to use an instance and interface like I would use for most of the other classes.
It's two fold. You can use it as a static method. Say for instance in spring security I use AuthenticationFacade to access currently logged in user Principal details like so. AuthenticationFacade.getName()
There are other instances, in which mostly people create an instance of Facade and use it. In my opinion neither approach is superior over the other. Rather it depends on your context.
Finally Facade can use Singleton pattern to make sure that it creates only one instance and provides a global point of access to it.
This question is highly subjective. The only reason I am responding is because I reviewed some of my own code and found where I had written a Façade in one application as a singleton and written almost the same Façade in a different application requiring an instance. I'm going to discuss why I chose each of those routes in their respective applications so that I can evaluate if I made the correct choice.
A façade vs the open/close principle is already explained by #Rene Link. In my personal experience, you have to think of it this way: Does the object hold the state of itself?
Let's say I have a façade that wraps the Azure Storage API for .NET (https://learn.microsoft.com/en-us/azure/storage/common/storage-samples-dotnet)
This facade holds information about how to authenticate against the storage API so that it the client can do something like this:
Azure.Authenticate(username, password);
Azure.CreateFile("My New Text File", "\\FILELOCATION");
As you can see in this example, I have not created an instance and i'm using static methods, therefore following the singleton pattern. While this makes for code that is more concise, I now have an issue if I need to authenticate to a given path with a different credential than the one already provided, I would have to do something like this:
Azure.Authenticate(username, password)
Azure.CreateFile("My New Text File", "\\FILELOCATION");
Azure.Authenticate(username2, password2);
Azure.CreateFile("My Restrictied Text File", "\\RESTRTICTEDFILELOCATION");
While this would work, it can be hard to determine why authentication failed when I call Azure.ReadFile, as I have no idea what username and password may have been passed into the singleton from thread4 on form2 (which is no where to found) This is a prime example of where you should be using an instance. It would make much more since to do something like this:
Using (AzureFacade myAzure = Azure.Authenticate(username, password))
{
Azure.CreateFile("My New Text File", "\\FILELOCATION"); // I will always know the username and password.
}
With that said, what happens if the developer needs to create a file in Azure in a method that has no idea what the username and password to Azure may be. A good example of this would be an application that periodically connects to Azure and performs some multi-threaded tasks. In said application, the user setups a connection string to azure and all mulit-threaded tasks are performed using that connection string. Therefore, there is no need to create an instance for each thread (as the state of the object will always be the same) However, in order to maintain thread safety, you don't want to share the same instance across all the threads. This is where a singleton, thread-safe pattern may come into play. (Spring's AuthenticationFacade according to #Rene Link) So that I could do something like this (psudocode)
Thread[] allTask = // Create 5 threads
Azure.Authenticate(username, password) // Authenticate for all 5 threads.
allTask.start(myfunction)
void myFunction()
{
Azure.CreateFile("x");
}
Therefore, the choice between an instance of a façade v. a singleton façade is completely dependent on the intended application of the facade, however both can definitely exist.

What is the exact difference between Adapter and Proxy patterns?

As I understood both Adapter and Proxy patterns make two distinct/different classes/objects compatible with each for communication. And both of them are Structural patterns. I am getting that both of them are pretty much similar with each other.
Can some one explain what exactly make(s) them different?
EDIT:
I went through this question. But I'd rather like to have a close comparison between Adapter and Proxy.
Adapter:
It allows two unrelated interfaces to work together through the different objects, possibly playing same role.
It modifies original interface.
UML diagram:
You can find more details about this pattern with working code example in this SE post:
Difference between Bridge pattern and Adapter pattern
Proxy:
Proxy provide a surrogate or place holder for another object to control access to it.
UML diagram:
There are common situations in which the Proxy pattern is applicable.
A virtual proxy is a place holder for "expensive to create" objects. The real object is only created when a client first requests/accesses the object.
A remote proxy provides a local representative for an object that resides in a different address space. This is what the "stub" code in RPC and CORBA provides.
A protective proxy controls access to a sensitive master object. The "surrogate" object checks that the caller has the access permissions required prior to forwarding the request.
A smart Proxy provides sophisticated access to certain objects such as tracking the number of references to an object and denying access if a certain number is reached, as well as loading an object from database into memory on demand
For working code, have a look at tutorialspoint article on Proxy.
Key differences:
Adapter provides a different interface to its subject. Proxy provides the same interface
Adapter is meant to change the interface of an existing object
You can find more details about these patterns in sourcemaking articles of proxy and adapter articles.
Other useful articles: proxy by dzone
From here:
Adapter provides a different interface to its subject. Proxy provides the same interface.
You might think of an Adapter as something that should make one thing fit to another that is incompatible if connected directly. When you travel abroad, for example, and need an electrical outlet adapter.
Now a Proxy is an object of the same interface, and possibly the same base class (or a subclass). It only "pretends" to be (and behaves like) the actual object, but instead forwards the actual behavior (calculations, processing, data access, etc.) to an underlying, referenced object.
Extrapolating to the electrical analogy, it would be OK that the use of an adapter is visible to the client - that is, the client "knows" an adapter is being used - while the use of a proxy might more often be hidden, or "transparent" - the client thinks an actual object is being used, but it is only a proxy.
In practice the concepts wrapper, adapter and proxy are so closely related that the terms are used interchangeably.
As the name suggests, a wrapper is literally something that wraps around another object or function. e.g. a function that calls another function, or an object that manages the lifecycle of another object and forwards requests and responses.
An adapter literally adapts the contract. That commonly refers to changing the interface of an object, or changing a method signature. And in both cases that can only be accomplished by wrapping it with a different object or function.
The word proxy is used for exactly the same thing. However, some sources will use it more explicitly to refer to an adapter to access a remote resource. Basically, that means that local calls will be forwarded to a remote object. And it may appear natural to define a common interface which can then be shared/reused both locally and remotely for those objects.
Note: The latter interpretation of the proxy pattern isn't really a thing any more. This approach made sense in a time where technologies like CORBA were hot. If you have a remote service to access, it makes more sense to clearly define Request, Response and Context objects, and reach for technologies like OpenAPI or XSD.
Difference between Adapter pattern and Proxy Pattern
ADAPTER PATTERN
Indian mobile charger (CLIENT) does not fit in USA switch board (SERVER).
You need to use adapter so that Indian mobile charger (CLIENT) can fit in USA switch board (SERVER).
From point 2, you can understand that the CLIENT contacts adapter directly. Then adapter contacts server.
PROXY PATTERN
In adapter pattern client directly contacts adapter. It does not contact server.
In proxy pattern, proxy and server implements the same interface. Client would call the same interface.
UNDERSTANDING THROUGH CODE
class client{
public void main(){
//proxy pattern
IServer iserver = new proxy();
iserver.invoke();
//adapter pattern
IAdapter iadapter = new adapter();
iserver.iadapter();
}
}
class server implements IServer{
public void invoke(){}
}
class proxy implments IServer{
public void invoke(){}
}
class adapter implements IAdapter{
public void invoke(){}
}
Reference: Difference between Adapter pattern and Proxy Pattern

Ninject provider can't resolve types registered within a named scope

I am using the NamedScoped Ninject extension in an attempt to create object graphs that are constructed everytime a command handler is constructed by the container. In other words, I want a fresh object graph for every command that might get processed by its corresponding handler.
I have used the .DefinesNamedScope("TopLevelOrhcestrator") binding when registering my "command handlers" as they are the top level for command processing.
A type in this named scope needs to be injected with the result of a method call on a type already registered in this named scope. I thought the best way to do this would be with a ninject provider.
Inside the provider I attempt to resolve the type in hopes I can call a method on it to pass into another object I am creating within this named scope. The problem I'm having is that when I ask the IContext for the instance inside the customer provider I get an exception that says "No matching scopes are available, and the type is declared InNamedScope(TopLevelOrchestrator).
context.Kernel.Get<TypeAlreadyRegisteredInScope>().MethodThatGetsAnotherDependency()
Is it possible to get types from the container inside a Ninject provider when they are registered inside a named scope?
EDIT
I apologize if the use case seems a bit odd, I am experimenting with some ideas about how to manage my units of work and other services/managers that may need a handle to the uow to complete a business usecase. I know its common for the unit of work to be "started" and then passed into all dependencies that may need to take part in a larger process. I was thinking I'd rather let my orchestrator take a unit of work factory so that it could deterministically destroy the UOW and it would be clear who the owner of a usecase is. What would get supplied to the managers/services would be a proxy to the unit of work that would be null until a real unit of work was started by the orchestrator. That's why I was attempting to link the proxy from the already registered type in my provider. This is all very experimental at this point and was testing some ideas.
I'd be happy to hear any further thoughts.
For MethodThatGetsAnotherDependency() to be able to .Get<>() an instance that is bound .InNamedScope(...) you will need to add the Context Preservation Extension.
This is because NamedScope is adding a parameter to the request context of the binding that has .DefinesNamedScope(...). As soon as that request is over, that context and it's parameters are forgotten. Now with the ContextPreservation extension the context is kept and reused for late / factory creations (Func<>, interface factory with .ToFactory() binding...). It think it should also work with providers.
If not, just switch to a factory instead of a provider.
However i have to admit that i don't fully understand why/what you are trying to achieve. There might be simpler ways.

Intercepting object creation in RavenDb

I am trying to run some code on objects that are loaded from RavenDB, and I need to do it just after the object has been loaded with its property values.
I've tried intercepting the deserialization process using a CustomCreationConverter and overriding ReadJson, but the object I can access at that point has all the properties set, except the one I need : the Id. Is there somewhere else I can slot into the pipeline in order to do this?
The reason you don't see the Id is because it's not part of the document, it's in the metadata as #id.
If you want to intercept client side, you can register a custom Conversion Listener. Create a class that implements IDocumentConversionListener and register it with documentStore.RegisterListener(). In the DocumentToEntity method, you can run your custom logic. The documentation is lacking on Listeners in general, but there is another topic that also uses them:
http://ravendb.net/kb/16/using-optimistic-concurrency-in-real-world-scenarios
The other option would be to add a bundle that intercepts on the server side. For that, you would use a Read Trigger.

Generic DataContract in Agatha WCF

I am trying to use Generic DataContract class so that I don't have to implement several types for a collection of different objects.
Exp :
I have a Profile object which contains a collection of objects.
So I want to have one Profile<Foo> and Profile<Foo1> where profile contains a collection of Foo or Foo1 objects.
I have been reading that WCF does not support generic classes and actually the error that I get is the following.
Type 'GL.RequestResponse.ProfileResponse1[T]' cannot be exported as a schema type because it is an open generic type. You can only export a generic type if all its generic parameter types are actual types.`
Now the ProfileResponse is this Profile object that I am trying to use.
Now in my host I am doing the following. :
ServiceConfig(typeof(ProfileHandler<EducationResponse>).Assembly,
typeof(ProfileRequest).Assembly,
typeof(Container)).Initialize();
This is dhe definition of the handler with the datacontract.
public class ProfileHandler<T> : RequestHandler<ProfileRequest,
ProfileResponse<T>>
The Container is using Windsor Container to register the objects.
The registration works fine but after I instantiated the Service Host for WCF processor, and call Open Method of the host I get the above error.
Is there really no way for me to write generic response requests for wcf with agatha ?
It feels like such a waste to have to define a Profile container class for each type being contained in that collection.
thanks.
One cannot have open generic handlers, because the server side needs to know what the type is.
One can use so called closed generic methods. This way the server side knows the types for witch to load the handler.
Also, one could potentially configure Agatha so that it allows to receive extra information related to the request. In this case, it would be the type wrapped in the response.
One could do this by defining a a BaseRequest class and having all the request extend this class. This class can have a property which takes the type of the response. Or the type to be wrapped in the response.
In the process, when examining the request, the process can get the type to be wrapped in the Response, so that i knows how to load the class.
I have not implemented this, since it would take too much time and I am not sure I want to be responsible for maintaining Agatha for our application, but this is how I would do it.