modules contract by interface, diagram, logic, general informations - model-view-controller

Here is my question, I hope that I'll write it correctly because it is a precise question.
I wonder how to use the interfaces as a contract between two modules. When I draw the module diagrams I never knows which of the modules as the circle and which has the half-open circle. A clear way on how to make the distinction would be very appreciated!
I don't want an example on how to use an interface because I know the properties of the interfaces (behaviors, etc).
Let's say that I got 2 modules, one contains the Bussiness logic, so I'll call it "Model", the other contains the GUI so I'll call it "View".
The view needs a Treeview and a Matrix on each nodes. So we got a tree-like hierarchie that the Model knows about, and for each node we want to fill a matrix of values.
root
- node1
-- leaf1
-- leaf2
- node2
- node3
-- leaf3
-- leaf4
My guts are telling me that I should do something like this:
interface IModelHierarchicMatrix {
void setTreeViewValues(TreeViewModel treeview);
void getMatrixValues();
void setMatrixValues(int[] values);
}
class Model implements IModelHierarchicMatrix {
// the code where I override the interface's function
}
So nice, we can call the needed function for the GUI at the Model. But how can we tell the GUI's class that we need that kind of behaviors (class, etc)...
I find myself often doing this kind of thing:
interface IModelHierarchicMatrixGlue {
void acceptModel(IModelHierarchicMatrix model);
}
class Gui implements IModelHierarchicMatrixGlue {
private IModelHierarchicMatrix model;
...
#Override
public void acceptModel(IModelHierarchicMatrix model) {
if (this.model == null) {
this.model = model;
}
}
}
But I always wonder if it's a good way of creating the contract between the Model and the View.
If I got to create a bi-directional contract between the Modules, how should I do that? Because it might create a cyclic logic between the interfaces...
I hope my question was clear enough, thanks in advance.

Related

Abstract base class design in Go vs C++

I am still learning the Go way of doing things, coming from a C++ background. I am looking for feedback contrasting OOP inheritance to interface composition.
I have a design situation in a Go program where, if I was implementing in C++, I would solve with an abstract base class.
Suppose I need a base class, which has many implementors. The base class has shared methods that do work on abstract data items. Different Worker implementations provide CRUD operations on different item types, but workers all use the shared methods of the base class for general work.
In C++ I might do it this way
class IItem
{
// virtual methods
};
class IWorker
{
public:
// one of many virtual functions that deal with IItem CRUD
virtual IItem* createItem() = 0;
// concrete method that works on interfaces
void doWork()
{
IItem* item = createItem();
// do stuff with an IItem*
}
};
class Toy : public IItem
{
};
// one of many kinds of workers
class ElfWorker : public IWorker
{
public:
ElfWorker()
{
// constructor implicitly calls IWorker()
}
IItem* createItem() override
{
return new Toy;
}
};
In Go you don't have abstract virtual methods such as IWorker::createItem(). Concrete classes need to supply the base with an interface or function that do the right thing.
So I think it is the case that the Go code the ew.ItemCRUD interface has to be explicitly set with a pointer to an ElfWorker.
The elf knows how to createItem(), which in his case happens to be Toy object. Other workers would implement their own ItemCRUD for their data objects.
type Item interface {
// various methods
}
type ItemCRUD interface {
create() Item
// other CRUD
}
type Worker struct {
ItemCRUD // embedded interface
}
func (w *Worker) doWork() {
item := w.create()
// do stuff with item
}
type Toy struct {
}
type ElfWorker struct {
Worker // embedded
// ..
}
func NewElfWorker() *ElfWorker {
ew := &ElfWorker{}
ew.ItemCRUD = ew // <-- #### set Worker ItemCRUD explicitly ####
return ew
}
func (ew *ElfWorker) createItem() Item {
return &Toy{}
}
// more ElfWorker Item CRUD
func bigFunction(w *Worker) {
// ...
w.doWork()
// ..
}
So the part that I am wrestling a bit with is explicit setting. Seems like the "Go way" of composition does require this explicit step if I want the base Worker class to provide shared methods on Items.
Thoughts?
Beeing new to go myself, this answer is not backed by years of go experience :-)
I don't know, if the way you tackle this is the correct approach.
go allows interfaces to be implemented without explicit declaration. If you have elves, and you need them to do ItemCRUD methods, just implement them.
The method set will then match the interface and you can use the elf as a ItemCRUD where required.
To supply any elf object with a default ItemCRUD Implementation, you should implement an adapter for the ItemCRUD and compose the adapter with your abstract elf. The abstract methods could have a default implementation as log.Fatal("not implemented")
The concrete elves shadow the adapter's methods, this answers your question: It is not required to insert the object during creation.
Yet, since go has no generics, it may not be the right approach to have an ItemCRUD.
Im not entirely clear what the plan is with the above code and without understanding that its hard to suggest specific solutions, what is clear is you are very much coming to the party with an established OOP mindset (I did too) which is rarely helpful in finding the best solution in golang.
In Golang I wouldnt usually embed an interface in an implementation, interfaces are satisfied implicitly in Golang which allows for a nice separation of expectation and implementation which should generally be respected.
A reciever method should expect an interface, the implementation passed at runtime should just satisfy the signature of that interface implicitly.
So perhaps my doWork method needs to be able to createItems then it would be the doWork method that would accept any implementation of ItemCRUD which it could call to create an item. But this is me guessing at what you really want to do here, I suspect if you just separate implementation from interface you will probably answer your own question.

How do I build a generic IEventHandler?

I've read https://aspnetboilerplate.com/Pages/Documents/EventBus-Domain-Events and also ABP's implementation of Entity event handlers https://github.com/aspnetboilerplate/aspnetboilerplate/tree/f10fa5205c780bcc27adfe38aaae631f412eb7df/src/Abp/Events/Bus/Entities
I have spent 8 hours at work trying to find a solution to my issue, but I failed to succeed.
I have certain entities that point to a single entity called DatumStatus, which records certain actions that generate different states, such as: approved, modified, reviewed, archived, etc.
I am trying to generate a generic EventHandler capable of modifying its status based on these actions.
An example based on a algorithm:
EventBus.Trigger(new ApproveEventData{
Repository = _certainRepository,
Ids = [1, 4, 5]
});
The handler itself would, in turn, handle this state transition
public void HandleEvent(ApproveEventData eventData)
{
eventData.Repository.Where(p => p.Id.IsIn(eventData.Ids)).ForEach(p => {
p.Approved = true;
p.ApprovalDate = DateTime.Now()
});
}
The problem is, I need to write a generic ApproveEventData and handler capable of firing the same HandleEvent for every single entities.
The "closest" I got is:
EventBus.Trigger(typeof(ApproveEventData<int>), (IEventData) new ApproveEventData<int> {
Repository = (IRepository<EntityWithStatus<int>, int>) _entityRepository,
Ids = selectedIds
});
[Serializable]
public class ApproveEventData<TPrimaryKey> : EventData
{
public IRepository<EntityWithStatus<TPrimaryKey>, TPrimaryKey> Repository;
public TPrimaryKey[] Ids;
}
The implementation above failes when casting the repository.
Could someone shed some light? Thanks!
I see two possible approaches.
Rely on covariance and contravariance. You can make the cast succeed by making an interface for EntityWithStatus an interface and making both IEntityWithStatus and IRepository covariant (add out to the generic type definition).
Rely on dynamic and leverage generic type inference. Basically have the Repository be dynamic.
I'd recommend number 1.

Does Processing 3 have class declarations?

Our school project has us make a game using Processing 3. After some studying with the language, our team is pretty confident we can work with the project, though we do have certain reservations of the chosen language.
However, there is one major question we are wondering and could not find an answer. In C++ and many others, when you create a new class in a new file you also create a header file you can include. Does Processing 3 have something similar? I know you can "include" files by adding more tabs, which is still weird but whatever. We would like to have some sort of declarations in advance so we can comment/describe classes and their methods, rather than force each member go through lots of code to find the proper point.
In short, we want to be able to do something like this:
Example.pde
class Example {
//Description
Example();
//Description
void doSomething(int variable);
}
//Other team members don't have to worry past this,
//as they have already seen the public interface
Example::Example()
{
//Constructor
}
void Example::doSomething(int variable)
{
//Function
}
Or do we have to always to like this:
Example.pde
class Example {
//Description
Example()
{
//Constructor
}
//Description
void doSomething(int variable)
{
//Function
}
}
Processing is written in Java, so you can only do things that Java supports. Java does not support header files, so no, you can't use header files in Processing.
However, it sounds like what you're really looking for is an interface.
interface Example {
void doSomething(int variable);
}
class MyExample implements Example{
public MyExample(){
//Constructor
}
void doSomething(int variable){
//Function
}
}
With this, you would only need to show other team members the interface, not the class. As long as they program to the interface, they don't need to ever see the class implementation.
More info on interfaces can be found in the Processing reference.

Customizing MEF

I have this situation where I want to use MEF in a chess project I'm workin on. Let's say I have a class constructor as in:
public class MoveManager
{
private Piece _piece;
public MoveManager(Piece piece)
{
_piece = piece;
}
Mode code here...
}
In this context I would have several classes that would derive from Piece like, Pawn, Rook, etc. If I put export attributes on all the classes the derive from Piece, the object being passed into the constructor is null. MEF loops through all classes the have the [Export(typeof(Piece))] and if it exceeds 1, it passes in null. So I cannot use MEF in this way. I'm going to use an Abstact Factory for getting the correct piece. Seems like the DI part of MEF can only take a single class that has the [Export(typeof(some base class))].
Can anyone shed some light on this?
I think you might be looking for the [Importing Constructor] arrtibute, which tells MEF how to use an exported class's constructor.
[Export(typeof(IPiece))]
class Pawn : IPiece
{
[ImportingConstructor]
public Pawn(ISomeDependency dep, [ImportMany] IEnumerable<IOtherDependency> depList)
{
//... do stuff with dependencies
}
}
This requires that an ISomeDependency is exported elsewhere (exactly once) and accepts any number of IOtherDependency's that might be exported too.
Supposing you did this with each piece, you could then:
[Export(typeof(IPieceList))]
class PieceList : IPieceList
{
[ImportingConstructor]
public PieceList([ImportMany] IEnumerable<IPiece> pieces)
{
// pieces now contains one of each piece that was exported above
}
}

GUI Pattern Question: PropertyChangeListener vs. Specialized View Interface

I'd like to pair a Model with it's View through an interface. I want to control when and how often the view is updated. So something like PropertyChangeListener wouldn't work well (where an event is fired after each property is set).
I'm not developing for a specific GUI framework. The goal here is the ability to swap out different GUI front ends (right now for testing, but might be useful later for different versions of the app). These might be Swing, or it might be a web browser (via GWT, for example).
Below is my approach. The view implements an interface to provide a method to update. This is triggered by the controller when it determines it's done updating the model. This still feels ok to me, since the Controller is only interacting with the view through the model, the controller is not dependent on a particular implementation of the View.
So, I guess my question(s) are
does this work well?
Is this standard practice?
Does this pattern have a name?
Rough code sample (Java):
// Controller, manages Items (the model)
class ItemList {
void addItem(Item item) {
}
void doStuffWithItems() {
// perform some set of operations, such as sorting or layout
for (Item item : items) {
// ....
}
// now with everything in it's final position:
for (Item item : items) {
item.updateView();
}
}
}
// Model
class Item {
private int top;
private int left;
private int width;
private int height;
// Can remember it's previous position/size:
public void savePostion() {
}
// And recall it for the Controller to use:
public public Position getSavedPosition() {
}
// Plus some other useful functions:
public boolean intersectsWith(Item other) {
}
public void updateView() {
this.view.update();
}
void setView(ItemView view) {
this.view = view;
}
}
// Interface used by View implementations
public interface ItemView {
// Trigger the view to reflect the current state of the model
void update();
}
// Example, as a Swing component
class ItemComponent extends JComponent implements ItemView {
private Item item;
public ItemComponent(Item item) {
this.item = item;
item.setView(this);
}
// ItemView#update
public void update() {
// update the component's size/position
setBounds(new Rectangle(item.getLeft(), item.getTop(), item.getWidth(), item.getHeight()));
}
#Override
public void paint(Graphics g) {
// ...
}
}
I would avoid forcing the View to implement an interface only for change notification. Create a separate "update now" event on the model instead.
The model should not be controlling or know about the view directly. The view should register a callback with the controller so the controller can tell the view when to update, that's why its the controller. You could have the model allow external listeners for a modelChangedEvent. Then the view could register with the model in that respect without the model knowing there was a view. See the J2EE blueprint for MVC and how there is an indirect event notification of state change in the model.
For traditional applications that run on the desktop of a computer I recommend variants of the Passive View. The class responsible for creating and managing the form is a thin shell that passes events to the UI Object. The UI_Object interact with the form via a interface. In term the UI Object implements a UI_View Interface and registers itself with a View Controller that is situated lower in the object hierarchy.
The UI_Object then execute object implementing the Command Pattern which modifies the model. The command object can interacts with the various views via the interfaces exposed by the View Control.
What this does is allow you to rip off the form classes and replace them with stub classes that implement the form interfaces. The stub classes are used for automated testing especially for integration tests.
The interfaces precisely define the interaction between the Form, the UI_Object, Commands and the views. They can be designed to be relatively language agnostic so they can make porting between platform easier.
What you are missing in your example are command objects. You need this structure
ItemViewForms
ItemViewImplementation
ItemViewFormInterface
ItemViewCommands
ItemViewInterface
MyModel
Incorporate ItemList in the ItemViewImplementation
ItemComponent would register with the ItemViewImplementation using the ItemViewInterface.
The sequence of events would look something like this
User wants to update the Item
Clicks on the UI (assuming that UI
involves clicking with a mouse)
The Form tells the
ItemViewImplementation through the
ItemViewInterface that X has been
done with Y parameters.
The ItemViewImplementation then
creates a command object with the
parameters it needs from Y.
The Command Object take the Y
Parameters modifies the model and
then tells the
ItemViewImplementation through the
ItemViewInterface to update the UI.
The ItemViewImplementation tells the
ItemViewForms to update the UI
through the ItemViewFormInterface.
The ItemViewForms updates.
The advantage of this approach is that the interaction of each layer is precisely defined through interfaces. The Software ACTIONS are localized into the command objects. The Form layers is focused on display the result. The View layer is responsible for routing actions and response between the Commands and Forms. The Commands are the only things modifying the model. Also you have the advantage of ripping off the Forms Implementation to substitute any UI you want including mock object for unit testing.

Resources