When should and shouldn't I extend a class, and is it valid for MVC? - actionscript-3

I am considering using class extension as a way to connect my model with my controller. I tried looking on the internet but could not find any information on this topic. This led me to the question of when a class should be extended and for what reasons.
This is my plan:
model class
controller extends model
new controller();
new view(controller);
Reason:
I can make all methods and variables that the view should not touch or alter protected (i.e. protected var myVar:String). This enables me to ensure that the view still has access to the data it needs but is unable to make accidental changes.
This whole thought process derived from the fact that I don't want my view to have any influence whatsoever, while still remaining independent (i.e. I can have multiple views of the same model without having to tell the controller that an additional view has been added).
To summarize:
When should a class be extended? When should it be avoided?
Is my plan a valid implementation of MVC?
Is there a better way to disconnect the view in a way that meets my demands?
Thank you for reading till the end.

The controller shouldn't extend the model - they do two separate things in the MVC triad and therefore should be two different classes. A valid reason to extend the Model class would be to add an extra feature to it, for example BigModel
Heres a summary of each part of MVC structure
The model manages the behavior and data of the application domain
The view renders the model into a form suitable for interaction, typically a user interface element
The controller receives input and initiates a response by making calls on model objects.

Your view will not have access to the protected methods of the model/controller. Protected does not mean read only, it means that only classes that extend the base class can access the protected properties or methods.
To have read only attributes in your model you should look at using private/protected properties and then creating a public getter function for each property (Property can then be read but not set).
Also to have access to the model from the view consider creating the Model as a Singleton so it can be accessed from anywhere in your application.
The controller dosen't usually do much else than listen for and dispatch events/notifications, sometimes for small projects you can make your Model class (Singleton) extend EventDispatcher and have it pretty much do everything you want, but this is not pure MVC and can quickly lead to technical debt if the project scope grows.

Related

JavaFX FXML Parameter passing from Controller A to B and back

I want to create a controller based JavaFX GUI consisting of multiple controllers.
The task I can't accomplish is to pass parameters from one Scene to another AND back.
Or in other words:
The MainController loads SubController's fxml, passes an object to SubController, switches the scene. There shall not be two open windows.
After it's work is done, the SubController shall then switch the scene back to the MainController and pass some object back.
This is where I fail.
This question is very similar to this one but still unanswered. Passing Parameters JavaFX FXML
It was also mentioned in the comments:
"This work when you pass parameter from first controller to second but how to pass parameter from second to first controller,i mean after first.fxml was loaded.
– Xlint Xms Sep 18 '17 at 23:15"
I used the first approach in the top answer of that thread.
Does anyone have a clue how to achieve this without external libs?
There are numerous ways to do this.
Here is one solution, which passes a Consumer to another controller. The other controller can invoke the consumer to accept the result once it has completed its work. The sample is based on the example code from an answer to the question that you linked.
public Stage showCustomerDialog(Customer customer) {
FXMLLoader loader = new FXMLLoader(
getClass().getResource(
"customerDialog.fxml"
)
);
Stage stage = new Stage(StageStyle.DECORATED);
stage.setScene(
new Scene(
(Pane) loader.load()
)
);
Consumer<CustomerInteractionResult> onComplete = result -> {
// update main screen based upon result.
};
CustomerDialogController controller =
loader.<CustomerDialogController>getController();
controller.initData(customer, onComplete);
stage.show();
return stage;
}
...
class CustomerDialogController() {
#FXML private Label customerName;
private Consumer<CustomerInteractionResult> onComplete
void initialize() {}
void initData(Customer customer, Consumer<CustomerInteractionResult> onComplete) {
customerName.setText(customer.getName());
this.onComplete = onComplete;
}
#FXML
void onSomeInteractionLikeCloseDialog(ActionEvent event) {
onComplete.accept(new CustomerInteractionResult(someDataGatheredByDialog));
}
}
Another way to do this is to add a result property to the controller of the dialog screen and interested invokers could listen to or retrieve the result property. A result property is how the in-built JavaFX dialogs work, so you would be essentially imitating some of that functionality.
If you have a lot of this passing back and forth stuff going on, a shared dependency injection model based on something like Gluon Ignite, might assist you.
I've used AfterBurner.fx for dependency injection, which is very slick and powerful as long as you follow the conventions. It's not necessarily an external lib if you just copy the 3 classes into your structure. Although you do need the javax Inject jar, so I guess it is an eternal reference.
Alternately, if you have a central "screen" from which most of your application branches out you could use property binding probably within a singleton pattern. There are some good articles on using singleton in JavaFX, like this one. I did that for a small application that works really great, but defining all of those bindings can get out of hand if there are a lot of properties.
To pass data back, the best approach is probably to fire custom Events, which the parent controller subscribes to with Node::addEventHandler. See How to emit and handle custom events? for context.
In complex cases when the two controllers have no reference to each other, a Event Bus as #jewelsea mentioned is the superior option.
For overall architecture, this Reddit comment provides some good detail: https://www.reddit.com/r/java/comments/7c4vhv/are_there_any_canonical_javafx_design_patterns/dpnsedh/

How to call a remoteObject method that is outside of my TitleWindow component on Flex?

I have a TitleWindow component. It allows me to save some data provided through 3 TextInput.
That data "fills" a DropDownList which is in another TitleWindow component, not inside the original one.
How can I call the remoteObject method that fills (or refresh) my DropDownList?
Any ideas will be appreciated!
You can simply use a Singleton as a model if you'd like, this will allow you to share data, but beware keep data only that needs to be shared in here or it will just become a global nightmare.
Using a singleton means you'll have a class that you can only ever have one instance of. If you put properties in that class any time you reference it it will be the same memory throughout the application execution.
http://blog.pixelbreaker.com/actionscript-3-0/as30-better-singletons
Marking the singleton class or individual properties as Bindable will make it so you can watch for the changes and call a function.
http://livedocs.adobe.com/flex/3/html/help.html?content=databinding_8.html
Putting this together you have something like this:
[Singleton.as]
package
{
[Bindable]
public class Singleton
{
public var myListData:Array;
public static var instance:Singleton;
public static function getInstance():Singleton
{
if( instance == null ) instance = new Singleton( new SingletonEnforcer() );
return instance;
}
public function Singleton( pvt:SingletonEnforcer )
{
// init class
}
}
}
internal class SingletonEnforcer{}
Somewhere else you want to get a handle on this
[MyTitleWindow.as]
var instance:Singleton = Singleton.getInstance();
instance.myListData = [1,2,3];
[MyTitleWindowWithAList]
var instance:Singleton = Singleton.getInstance();
BindingUtils.bindSetter(funcUpdateList, instance, "myListData");
private function funcUpdateList(data:Object)
{
myList.dataProvider = data as Array;
}
Another option is to create an event that carries your data payload, dispatch that event from the first title window, and capture it, the problem with this is you have to register the listeners on the PopUpManager or SystemManager I believe because the TitleWindow's aren't direct children of the Application I believe.
Singletons are a bad idea and you should not get in the habit of using them. Instead, just dispatch an event from the View and catch it from something else that has access to your Service object.
Note that your Service should not be part and parcel of any View--the responsibility of a View is displaying data and capturing requests from the user to change the data, not communicating with a server.
For examples of an application written with this pattern in mind, check out
[Refactoring with Mate] (http://www.developria.com/2010/05/refactoring-with-mate.html) - The example has View source enabled
The same application done with RobotLegs - again, View Source is enabled.
Note that these are written against some popular frameworks, but they are written in such a way that you can easily replace that framework code with something else, even your own code.
For reference, here is the naiive implementation, where the service layer is being called directly in the Views. You couldn't call a different service without changing the Views, though the use of the static service means you could use it from elsewhere.
That static usage survived into the later examples, though today I would never write something depending on a globally accessible object. In part this is because I discovered Test Driven Development, and it is impossible to replace the "real" static object with an object that lets you isolate what you are testing. However, the fact that most of the code in the 2 "better" examples is insulated from that static object means that it is trivial to replace it with one that is provided some other way.
The lesson here is if you're going to use static, global objects, lock them away behind as much abstraction as you can. But avoid them if you're at all interested in best practice. Note that a Singleton is a static global object of the worst kind.

Question on class implementation with interface

I have created the following classes for sharing images. They implement an interface, but I need a way of switching between them with user interaction. I've done it the following way:
As you can see, service 1 and service 2 implement iSharingServices, and inherit from PolimorphSharing.
PolimorphSharing is simply and an abstract class that implements the methods I want public from Service 1 and Service 2. Those methods will then be overridden on the Service 1 and Service 2.
Because I need a way to switch the service in runtime, I've created a gateway class that inherits from PolimorphSharing. I can then call it the following way:
private var sharingService:PolimorphSharing = new SharingServicesGW('svc1').createService();
This all works flawlessly, and I can now switch between services with no problem whatsoever. However, I feel there's something wrong about it, so I would like to ask you guys for some advice on how to better implement this.
Any opinions here would be appreciated. I feel like I'm kind of implementing the factory pattern here the hard way.
UPDATE:
Just adding some more insight to this. Basically the idea here is for my client to be able to upload images with various different public sharing services such as imageshack, imgur etc. I want my client to be able to select the service in which the image is to be published to (hence the "switching between them with user interaction" bit of the question.
The method that does the uploading bit, is requestShareImage(), processResults() simply turns whatever gets returned to a unique format, so my client can read off it always the same way. getObject() is my accessor, and onIOError will handle exceptions with any of the public API's
Thanks all in advance,
SharingServicesGW IS a factory. However, there's no need for it to - and it shouldn't - inherit from PolimorphSharing. Also you're doing it a bit skewed. The client should be using objects of the interface type, not the abstract type.
Your interface should be defining the public API, not your abstract base class. In fact in AS3 interfaces can only define public members, while pseudo abstract classes can enforce implementation of protected members.
-- EDIT --
here's a UML diagram of how I would do it

Associating an Object with other Objects and Properties of those Objects

I am looking for some help with designing some functionality in my application. I already have something similar designed but this problem is a little different.
Background:
In my application we have different Modules. Data in each module can be associated to other modules. Each Module is represented by an Object in our application.
Module 1 can be associated with Module 2 and Module 3. Currently I use a factory to provide the proper DAO for getting and saving this data.
It looks something like this:
class Module1Factory {
public static Module1BridgeDAO createModule1BridgeDAO(int moduleid) {
switch (moduleId)
{
case Module.Module2Id: return new Module1_Module2DAO();
case Module.Module3Id: return new Module1_Module3DAO();
default: return null;
}
}
}
Module1_Module2 and Module1_Module3 implement the same BridgeModule interface. In the database I have a Table for every module (Module1, Module2, Module3). I also have a bridge table for each module (they are many to many) Module1_Module2, Module1_Module3 etc.
The DAO basically handles all code needed to manage the association and retrieve its own instance data for the calling module. Now when we add new modules that associate with Module1 we simply implement the ModuleBridge interface and provide the common functionality.
New Development
We are adding a new module that will have the ability to be associated with other Modules as well as specific properties of that module. The module is basically providing the user the ability to add their custom forms to our other modules. That way they can collect additional information along with what we provide.
I want to start associating my Form module with other modules and their properties. Ie if Module1 has a property Category, I want to associate an instance From data with that property.
There are many Forms. If a users creates an instance of Module2, they may always want to also have certain form(s) attached to that Module2 instance. If they create an instance of Module2 and select Category 1, then I may want additional Form(s) created.
I prototyped something like this:
Form
FormLayout (contains the labels and gui controls)
FormModule (associates a form with all instances of a module)
Form Instance (create an instance of a form to be filled out)
As I thought about it I was thinking about making a new FormModule table/class/dao for each Module and Property that I add. So I might have:
FormModule1
FormModule1Property1
FormModule1Property2
FormModule1Property3
FormModule1Property4
FormModule2
FormModule3
FormModule3Property1
Then as I did previously, I would use a factory to get the proper DAO for dealing with all of these. I would hand it an array of ids representing different modules and properties and it would return all of the DAOs that I need to call getForms(). Which in turn would return all of the forms for that particular bridge.
Some points
This will be for a new module so I dont need to expand on the factory code I provided. I just wanted to show an example of what I have done in the past.
The new module can be associated with: Other Modules (ie globally for any instance of that module data), Other module properties (ie only if the Module instance has a certian value in one of its properties)
I want to make it easy for developers to add associations with other modules and properties easily
Can any one suggest any design patterns or strategy's for achieving this?
If anything is unclear please let me know.
Thank you,
Al
You can use springs Dependency Injection feature. This would help you achieve the flexibility of instantiating the objects using an xml configuration file.
So, my suggestion would be go with the Springs.

Model view controller

I have a tree control in my GUI (with naturally lots of GUI/platform specific functions to handle the nodes).
I have a data model with its own complex set of nodes, children, properties etc..
I want the tree to display a representation of the model, be able to send messages to the nodes inside the model and be told to redraw itself when the model changes.
But I don't want the GUI code to need to know the details of the model's data types and I don't want to pollute the model by linking it to the GUI classes.
I can't get my head around how the controller is supposed to do this and what functions it should provide?
(this is in C++ but that shouldn't matter)
GUI "controls" don't quite fit neatly into a model-view-controller pattern because they typically have their own internal model rather than accepting a reference to one. If the control is structured that way, you'll need an adapter class that "data-binds" the control's internal model to the underlying data model.
This can accomplish something similar to what model-view-controller would, except that the adapter class plays the role both of a view hookup component (updating the GUI from the data model) and a controller (interpreting GUI events into model actions).
Qt provides a group of classes for model-view programming. You can hook a tree view to a filesystem model, for example, and neither directly know anything about each other (except a pointer to the model in the view).
Your requirements are:
Tree displays representation of model
Nodes in tree can send messages to nodes inside model
Tree redraws itself based on model changes
I don't know exactly what kind of data you're working with here, but a hierarchical model is a fairly simple thing. I'll take it as a given you know how to iterate hierarchical data and populate a tree view.
Your controller should have member function(s) for sending messages to the model. The parameters should be a model element and the message you want to send. This way, the UI is completely unaware of how the message gets to the element, but can get the messages through.
The last requirement is more tricky, and depends on a few things (e.g., the lifetime of the controller, application architecture, etc.) I'm going to assume the controller lives as long as the tree view does. If that's the case, then your controller should provide a way to set a callback on model changes. Then, when the controller changes the model, it can callback to the UI without being aware of the UI.
i think your troubles start with an unfortunate choice of words. the 'control' thingies doesn't have anything to do with the 'controller' in MVC. that's why some GUI libraries use other names (widgets is a common one).
your 'tree control' is the view, not the controller. it should be tied to the GUI, both for display, and to get GUI events and turn them into 'tree events'.
the controller gets those 'tree events' and does the necessary modifications to the model. that's where you couple the 'action' with the 'response'.
First Solution: You can implement a "Subject observer" pattern between model and view, with model as the subject and view as the observer. Whenever there is a change in the state of model, it can fire a event to all the observers those are registered, they can update themselves.
Second Solution: Introduce a controller, which registers with model as observer. Upon receiving a event for update from Model, it can update the view. Even you can decouple view from controller using one more subject observer pattern between controller and view
Third Solution: Use MVP pattern. Model view Presenter. This pattern used whenever there is no much computation in controller i.e., job of the controller is just to update its corresponding view. Here controller becomes Presenter.
You need a controller that sits outside the display widget but has the state of the tree (in MFc there are CTreeView/CTreeCtrl classes - there is a similiar separation in Qt) the tree controller handles all the data storage and calls redraws on the tree widget.
Changes in the tree widget get sent to the tree controller - so this controller needs to know about the gui functions.
The model will need set/get functions for all the relevant parameters for the nodes. But these can return simple types so aren't dependent on the gui.
Updating the view form the model requires sending a message, if you don't want the model to know about your gui messaging the best you can do is register a callback function (a void pointer to a function) from the tree controller - and call this to do an update.
This update function can then query the model for the changes.