Is there any advantage or disadvantage in using a Xamarin.Forms MessagingCenter to communicate between a ViewModel and methods - xamarin

I am looking into using one or other method and in particular method 2. Can anyone tell me the advantages and disadavantages of using the 2nd method over the 1st.
Method 1 - ViewModel.cs
PTBtnCmd = new Command<Templates.WideButton>((btn) =>
MessagingCenter.Send<CFSPageViewModel, Templates.WideButton>(
this, "PTBtn", btn));
Method 1 - MyPage.xaml.cs (SetLang etc.. methods in this file )
MessagingCenter.Subscribe<CFSPageViewModel, Templates.WideButton>(
this, "PTBtn", (s, btn) =>
{
Utils.SetState(btn.Text, vm.PT);
SetLangVisible(btn.Text);
SetLangSelected(btn.Text);
vm.CFSMessage = Settings.cfs.TextLongDescription();
});
or
Method 2 - ViewModel.cs (SetLang etc.. methods in this file )
PTBtnCmd = new Command<string>(SetMode);
private void SetMode(string btnText)
{
Utils.SetState(btnText, PT);
SetLangVisible(btnText);
SetLangSelected(btnText);
CFSMessage = Settings.cfs.TextLongDescription();
}
Would also like to hear comments on the idea of adding methods into the ViewModel.cs code. Would it be better for these to be in another file?

The MessagingCenter
helps you keep your code decoupled. Sometimes you will find yourself in a position
that requires you create a reference between certain code, but by doing so, you have to
compromise on reusability and maintainability.
Try to use it as a last resort; usually there is
another way to achieve your desired functionality. While sending a message can be very
powerful, using it too much can really eat into your readability.
A use case example for MessagingCenter would be a case where you need to update values in multiple
parts of your app. You can subscribe to a message from multiple places and thus execute
code in multiple places when a message is received. Another use case could be if some
background process is done, it can send a message and you can then inform the user in
your UI.

I would not use the messaging in the VM layer because your VM layer can then only be used in Xamarin.Forms. Some Mvm frameworks, like mvvmlight, offer a messaging capability. I would opt for that instead as you could then reuse your VMs in Wpf, Uwp or other UI frameworks other than XF.
Also i wouldn't use the messaging like you have. If probably just use databinding and raise PropertyChanged events in the VM which the view can react to.

To pass data between VMs I'd suggest navigation params or rethinking how you are using this data in general (use some sort of service or dumb down the UI depending on how "fat" your client app must be).
Messaging center as #Andy mentioned would cause reusability issues but this does not mean that you cannot use it. My approach is wrapping it in a separate service and using it in implementation. This will let you to do two things: creating more convenient or better way to use it in accordance to your use case and an option to swap out the implementation of your messenger to any other pub-sub library (or your own impl.) if you will need to use these VMs in WPF project.
Of course using something more universal across platforms would be a great option too but it also depends on how much you are "allowed"/can use third party stuff. At least with MAUI this causes some problems, but this is for another topic.

Related

Pattern for changing program options in a GUI

I'm adding a GUI to an existing command line app. The properties used by the app are held in class(es) and I'm creating a dialog that binds to those options objects. However, if I want to cancel out of that dialog I then have reset the values of my options objects, which is where I'm running into probs.
I could take an internal copy of the option objects and use that to re-populate the original object to allow the cancel/rollback but that seems cumbersome.
I can (somehow) implement an undo function on each class - is there a pattern for that?
I use the GUI controls standalone to hold values and only update the options objects when the dialog has been confirmed.
What's best practise?
You should consider creating a new class to be used just by the GUI.
GUIs have their own needs.
Make sure to take care of multi thread issues if you have more than one thread accessing the options object.
The design patterns that address undo functionality are called Command and Memento.
I think Memento would fit better on this case.
Take a look on this question on SO: Design Pattern for Undo Engine.
The following links are of interest (and many more):
http://www.coderanch.com/t/100676/patterns/Memento-Vs-Command-pattern
http://www.developer.com/design/article.php/3720566/Working-With-Design-Patterns-Memento.htm
http://www.colourcoding.net/blog/archive/2009/07/23/reversibility-patterns-memento-and-command.aspx

Separation of domain and ui layer in a composite

i'm wondering if there is a pattern how to separate the domain logic of a class from the ui responsibilities of the objects in the domain layer.
Example:
// Domain classes
interface MachinePart
{
CalculateX(in, out)
// Where do we put these:
// Draw(Screen) ??
// ShowProperties(View) ??
// ...
}
class Assembly : MachinePart
{
CalculateX(in, out)
subParts
}
class Pipe : MachinePart
{
CalculateX(in, out)
length, diamater...
}
There is an application that calculates the value X for machines assembled from many machine parts. The assembly is loaded from a file representation and is designed as a composite. Each concrete part class stores some data to implement the CalculateX(in,out) method to simulate behaviour of the whole assembly. The application runs well but without GUI. To increase the usability a GUi should be developed on top of the existing implementation (changes to the existing code are allowed). The GUI should show a schematic graphical representation of the assembly and provide part specific dialogs to edit several parameters.
To achieve these goals the application needs new functionality for each machine part to draw a schematic representation on the screen, show a property dialog and other things not related to the domain of machine simulation. I can think of some different solutions to implement a Draw(Screen) functionality for each part but i am not happy with each of them.
First i could add a Draw(Screen) method to the MachinePart interface but this would mix-up domain code with ui code and i had to add a lot of functionality to each machine part class what makes my domain model hard to read and hard to understand.
Another "simple" solution is to make all parts visitable and implement ui code in visitors but Visitor does not belong to my favorite patterns.
I could derive UI variants from each machine part class to add the UI implementation there but i had to check if each part class is suited for inheritance and had to be careful on changes to the base classes.
My currently favorite design is to create a parallel composite hierarchy where each component stores data to define a machine part, has implementation for UI methods and a factory method which creates instances of the corresponding domain classes, so that i can "convert" a UI assembly to a domain assembly. But there are problems to go back from the created domain hierarchy to the UI hierarchy for showing calculation results in the drawing for example (imagine some parts store some values during the calculation i want to show in the schematic representation after the simluation).
Maybe there are some proven patterns for such problems?
Agree with #Marjin, and to generalise his answer. What you need is Model-View-Controller of which MVP and MVVM are variants. From your comments I think you understand that, but need to understand how to implement the pattern. Without knowing your language & target architecture it's hard to give absolute specifics. Notwithstanding, I'd start with the Observer pattern (link has sample code).
The problem you're dealing with is how to provide observable access from the domain to the UI - without encumbering the domain with UI-specific code. Observer provides a means to do that. It does require domain changes, in particular to enable registration of observers and notification of changes. However there's nothing GUI-specific in that so it stays well encapsulated.
hth.
PS: If your app is a typical thin-client web app you'll need to modify the approach. And beware: lots of web app frameworks are advertised as "MVC", but the implementation is architecturally quite different to the Observer pattern.
You can take a look at the model-view-presenter (mvp) and model-view-viewmodel (mvvm) patterns.
Fowler's presentation model includes two sample applications; it also might be of interest to you.
I think that investigating these patterns will give you some ideas on how to continue. Mvvm looks a lot like your current solution; so i'd start there if I were you.
Maybe a View Helper can help. It's not a C++, but a Java EE pattern, but in your case it will definitely separate your domain objects from their presentation details...

Create a plugin, expose events

How do I expose events to my plugin users?
I know that I should use:
$('#myPluginDiv').trigger('eventName', ["foo", "bar"]);
to trigger the event but I'm looking for best practices describing how to declare and invoke events in plugins.
I think you can inspect some of the most used plugins and make your own assumptions. We have no standards on this, just code convention.
Colorbox (source: https://github.com/jackmoore/colorbox/blob/master/jquery.colorbox.js) defines a prefix and some constants for the event names. It also have a function for triggering and running the callbacks.
jQuery UI (source: https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.widget.js) also have a common function on the widget class for triggering events (usage: https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.dialog.js), but you can see that the events are hard coded on the middle of the source, instead of constants on the top like on Colorbox.
I personally think, and do it in my own plugins, that creating constants is much better if you have a lot of events to trigger, but its not necessary if you will fire only 2 or 3 events.
A helper function is a must have and should be part of your template.
The event names I use and see around all follow the standard CamelCase e.g. beforeClose.
Some advocate the use of a prefix for events like on Colorbox's cbox_open or even click.myPlugin (see: http://api.jquery.com/on/#event-names)
Conclusion: try to follow best practices and conventions for programming in general and watch for the better examples out there.
in plugin create object litereal like
var plugin = {
show:function(){
// code for show()
}
};

CodeIgniter: Decision making for creating of library & helper in CodeIgniter

After developing in CodeIgniter for awhile, I find it difficult to make decisions when to create a custom library and when to create a custom helper.
I do understand that both allow having business logic in it and are reusable across the framework (calling from different controller etc.)
But I strongly believe that the fact that CI core developers are separating libraries from helpers, there has to be a reason behind it and I guess, this is the reason waiting for me to discover and get enlightened.
CI developers out there, pls advise.
i think it's better to include an example.
I could have a
class notification_lib {
function set_message() { /*...*/}
function get_message() {/*...*/}
function update_message() {/*...*/}
}
Alternatively, i could also include all the functions into a helper.
In a notification_helper.php file, i will include set_message(), get_message(), update_message()..
Where either way, it still can be reused. So this got me thinking about the decision making point about when exactly do we create a library and a helper particularly in CI.
In a normal (framework-less) php app, the choice is clear as there is no helper, you will just need to create a library in order to reuse codes. But here, in CI, I would like to understand the core developers seperation of libraries and helpers
Well the choice comes down to set of functions or class. The choice is almost the same as a instance class verses a static class.
If you have just a simply group of functions then you only need to make a group of functions. If these group of functions share a lot of data, then you need to make a class that has an instance to store this data in between the method (class function) calls.
Do you have many public or private properties to store relating to your notification messages?
If you use a class, you could set multiple messages through the system then get_messages() could return a private array of messages. That would make it perfect for being a library.
There is a question I ask myself when deciding this that I think will help you as well. The question is: Am I providing a feature to my framework or am I consolidating?
If you have a feature that you are adding to your framework, then you'll want to create a library for that. Form validation, for example, is a feature that you are adding to a framework. Even though you can do form validation without this library, you're creating a standard system for validation which is a feature.
However, there is also a form helper which helps you create the HTML of forms. The big difference from the form validation library is that the form helper isn't creating a new feature, its just a set of related functions that help you write the HTML of forms properly.
Hopefully this differentiation will help you as it has me.
First of all, you should be sure that you understand the difference between CI library and helper class. Helper class is anything that helps any pre-made thing such as array, string, uri, etc; they are there and PHP already provides functions for them but you still create a helper to add more functionality to them.
On the other hand, library can be anything like something you are creating for the first time, any solution which might not be necessarily already out there.
Once you understand this difference fully, taking decision must not be that difficult.
Helper contains a group of functions to help you do a particular task.
Available helpers in CI
Libraries usually contain non-CI specific functionality. Like an image library. Something which is portable between applications.
Available libraries in CI
Source link
If someone ask me what the way you follow when time comes to create Helpers or Libraries.
I think these differences:
Class : In a nutshell, a Class is a blueprint for an object. And an object encapsulates conceptually related State and Responsibility of something in your Application and usually offers an programming interface with which to interact with these. This fosters code reuse and improves maintainability.
Functions : A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value. You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP gives you option to create your own functions as well.
So go for Class i.e. libraries if any one point matches
global variable need to use in two or more functions or even one, I hate using Global keyword
default initialization as per each time call or load
some tasks are private to entity not publicly open, think of functions never have public modifiers why?
function to function dependencies i.e. tasks are separated but two or more tasks needs it. Think of validate_email check only for email sending script for to,cc,bcc,etc. all of these needs validate_email.
And Lastly not least all related tasks i.e. functions should be placed in single object or file, it's easier for reference and remembrance.
For Helpers : any point which not matches with libraries
Personally I use libraries for big things, say an FTP-library I built that is a lot faster than CodeIgniters shipped library. This is a class with a lot of methods that share data with each other.
I use helpers for smaller tasks that are not related to a lot of other functionality. Small functions like decorating strings might be an example. Or copying a directory recursively to another location.

What design pattern? I need two modes in my app, edit and view

If I need two modes in my application what design pattern would I use so I can prevent ugly conditional code? App is currently MVC, but I don't want conditional code in my controllers and don't want two controllers for each view unless I have to.
Any suggestions?
A different subclass for each implementation, with shared functionality either in a common superclass or using the Template Method pattern.
Perhaps the State Pattern?
Abstract Factory, or Proxy. Your controller would contain some kind of Factory or Proxy instance that is used to retrieve a "mode" and act on it accordingly.
It is difficult to say for sure without more information, but I would suggest the strategy pattern. You could use the same controller and just swap out the strategy object to produce the desired change in behavior.
Here is an article you may find useful:
http://www.javaworld.com/javaworld/jw-04-2002/jw-0426-designpatterns.html
take a look at JSR-168, java portlet and its reference implementation, it should be similar to what you are trying to achieve.
The appropriate place for such a decision is the controller of MVC. I would recommend you write it there first. If it really is repetitive, it may be straightforward to figure out how to clean it up: you can move the conditional logic into a base class, or depending on the language, may be able to handle it with some sort of filter. You may also be able to create some "factory" for the views, which understands the "mode" of your application. Architecturally, though, all this is in the controller.
You are right to not want it in the view. This would be pretty messy. You probably want two versions of the views, one for "view" and one for "edit".
In the end, this is what controllers are for. Good luck!
In CafeTownsend demo made with PureMVC there is a similar situation where there are two different views and two separate Mediators. You absolute don't need conditional code for that. I don't know what technology and programming language you are using, but in Flex it will be a ViewStack with the ListView and EditView as children:
Corresponding mediator is registered by demand when the view is created. You can check other implementations using previous link.

Resources