MATLAB functions refusing to function depending on placement - model-view-controller

I've written a very simple GUI in MATLAB that will convert temperatures. It is meant to serve as a tutorial for a class of students. A strange thing has happened though. As with any MVC design pattern, there is a model object, a view object and a controller function. In order to set the output field of the GUI (the converted temperature), you can run this line in the controller function itself:
set(views.outputTextField,'string',num2str(round(model.outTemp)));
where views.outputTextField is a GUI text field to display the converted temperature and model.outTemp is the converted temperature. Pretty straightforward. The views object has references to all the GUI uicontrols and this updates the field with the newly converted temperature in the model object.
However, I would rather have view functions in the view object, so I attempted to create a line like this:
views.updateOutputField = #()set(views.outputTextField,'string',...
num2str(round(model.outTemp)));
Same line as before, just that now it is an anonymous function in the view object. This way I could call the function from the controllers as simply views.updateOutputField(); and keep the view logic out of the controller logic. But this method won't work! (It will work with the get() function.)
Instead I have to do the following:
views.updateOutputField = #updateOutputField
function updateOutputField()
set(views.outputTextField,'string',num2str(round(model.outTemp)));
end
By separating out the function (redundantly) instead of just using an anonymous function, it works again. What!? This makes no sense to me. The view and model objects are global and the anonymous function works with get(). Does anyone have a clue what's going on here?

Both approaches are not equivalent. Values in the body of anonymous function (aka lambda) are being frozen, see example below:
>> ii = 2;
>> val = #() ii+2;
>> val()
ans =
4
>> ii=5;
>> val()
ans =
4
You can do following to make it work:
views.updateOutputField = #(outTemp) ...
If you want to know how MATLAB captures the workspace context, use function FUNCTIONS on anonymous function.
Your example is a little bit more complicated because your view and model exist in the nested workspace but the essence is the same.
As side note: kudos for teaching also an important design pattern (MVC) in Matlab class!

Mikhail has the right answer. I'll elaborate a bit...
From the MATLAB documentation for anonymous functions:
Anonymous functions commonly include
two types of variables:
Variables specified in the argument
list. These often vary with each
function call.
Variables specified in the body of the
expression. MATLAB captures these
variables and holds them constant
throughout the lifetime of the
function handle.
When you make a call to SET inside your anonymous function, you access fields of your two structure variables views and model. These values are held fixed at what they were when the anonymous function was created. That doesn't matter for the graphics handles stored in views, since these never change (unless you are deleting and recreating graphics objects). This is why calling GET in your anonymous function works fine, since it only uses the unchanged graphics handles in views. However, the values in model change, so you would want to pass them in to the anonymous function as an argument. For example:
views.updateOutputField = #(model) set(views.outputTextField,'String',...
num2str(round(model.outTemp)));
When you instead create your updateOutputField function, you are creating a nested function. Nested functions have access to the variables that exist in the outer function within which they are nested, which is why you don't have to pass views and model as arguments. When these variables change in the outer function, that change is visible in the nested function as well (unlike anonymous functions).

Related

Wrapping instance variables in accessor methods

Sandy Metz says (POODR book, page 26):
Because it is possible to wrap every instance variable in a method and to therefore treat any variable as if it's just another object, the distinction between data and a regular object begins to disappear.
I am not sure if I understand what she is explaining. When we define the accessors, we are wrapping the instance variables (data) on a method but methods are not objects. So what does she mean when she says that we can treat variables as if they're just another object?
The primary difference between data and objects is behaviour. Objects can modify their internal state without changing their interfaces, while data are static structures.
When we wrap data access within a method, we get the same benefits of an object - the interface remains static to consumers even if the underlying data structure needs to change.

QTP Descriptive Programmuing -Loading the objects created through function

I have 10 different test cases .I want to create different objects of SwfEdit, SwfButton etc just once say in function and then use those in different actions in QTP.
I tried creating a function and linked it to a test case,however it did not work.
So I am not sure what could be correct way to link all these objects across all the test cases.
If you insist on creating your objects in code instead of using the object repository, you'll need to store those objects in some type of global variable. A basic example might be for a function library:
' Declare your global variable to hold the object
Public MyObject
' Create your object from a function
Public Sub InitializeGlobalObject()
' Use Descriptive Programing to create your object
Set MyObject = Window("title:=something").Button("index:=0")
End Sub
This will allow you to create the object once and then refer to it by the variable
' Click the button
MyObject.Click
You may run into issues caching an object like this because it will tend to hold on to the last screen object that it matches, whereas the object repository will refresh the screen object each time you call it. You may need to call the 'Refresh' method on your object before you use it for the first time after it is displayed on the screen.
You should use object repository to add objects first if you are not intending to use descriptive language.
You should spy on each object and then add it.

How do I pass arguments / parameters to model

Following the tutorial how to create a joomla 2.5 component I'm stucked to pass arguments from view.html.php to my model.
$items = $this->get('TableData');
and my TableData model would expect to get the following arguments
public function getTableData($table, $index_column, $columns) {}
You can not do this using the view's get method. Instead you would have to grab the model into the view and call the function directly in the view:
$model = $this->getModel();
$items = $model->getTableData($table, $index_column, $columns);
Alternately, you could create different entry points in the model that would be able to figure these input options either from state information or preset. Many would argue that this would lead to a better application design, since using my code above is putting what should be model logic in the view.
This is just an addon to David's answer.
Because most of the data usually comes from POST / GET methods, depending on your application, you may want to look at how loadFormData() from loadFormData JModelForm or populateState gets overridden in specific Joomla components.
Basically the state of model is set directly from POST data, using JInput.
Also, although it's not a rule or something, 3 parameters is a maximum I would pass to a method. For flexibility I would rather pass an array with can be later extended without changing the method signature.

Understanding Html.ActionLink(..., ..., ...) syntax in MVC3

I'm doing a tutorial on MVC 3 and I stumbled upon the helper #Html.ActionLink(genre.Name, "Browse", new {genre = genre.Name}).
Now I understand what the values do and that the third value is a route parameter value but this is the first time I'm seeing this kind of syntax which is really bugging me for some reason.
What I mean exactly is new {genre = genre.Name}. I've come to understand that "new" precedes object/type declaration, however, this time it's simply the "new" keyword and the curly brackets. How exactly is this processed?
The syntax new { prop = val } creates an anonymous type. It's essentially the same as creating an instance of a class, except you're declaring the class and the instance all in one shot. Some people think that anonymous types are not statically typed or are not type safe. This isn't true. The types of the properties are inferred from the values they are assigned. This construction is used frequently in MVC and in linq.
Note that this syntax is not specific to MVC. You can use it anywhere it's convenient. I make a fair amount of use of anonymous types in day-to-day coding.
It's simple.. the first parameter is the link you want to display, so genre.Name can corresponds to Rock. The second argument is the action, the third argument your Controller class. The last parameter is the route values in the form of an anonymous object (an object you will never use again, the MVC engine uses the anonymous object in this case).
So your action(method) takes a string argument.
For example:
"Home" is the link the user sees (the first argument), Home (the second argument) is the action (method) to your Controller class, and it takes a string argument.
class HomeController
{
public ActionResult GenreAction(string genre)
{
}
}
When a request is made, it becomes Home/GenreAction/genre
It's a C# language feature called Anonymous Type, introduced with C# 3.5 if I'm not mistaken.

Bullet Chart Example

I'm referencing the bullet chart example at D3 v2.4.2 github repository.
I have a few question to help clarify what is happening in this example.
1) In the bulletChart function there are 8 declarations in the form
bullet.ranges = function(x) {}, bullet.markers = function(x) {} etc. Where is this bullet object coming from? Is it built into the library? I thought we had already set the variable ranges to the function bulletRanges, or are these 2 different ranges variables?
2) What is actually going on inside these functions?
3) Last question. When the bulletChart function starts executing does it start executing the bullet function as execution comes to it or does it wait for an explicit call? Because I never actually see bullet(g) called explicitly?
This library can be really confusing. Any help greatly appreciated.
1) The bullet at the start of the name refers to the function of the same name created in line 70. The calls add members to the object, which is also callable. It's basically a way of allowing to customise the returned object. In OO terms, bullet is an object and the functions define accessors for its members. The functions bulletRanges etc. provide similar functionality for the outer bulletChart function. In OO terms, think nested objects.
2) See 1. The functions are accessors for the variables that are defined inside the bullet function and allow to customise the behaviour this way. Again, the OO equivalent would be private members of an object that are exposed through accessors.
3) The return value of the bullet function is the callable object. This is what bulletChart returns. So the function call in the example happens in lines 19 and 36 (through a d3 function) by passing variable chart to the .call function. The assignment of chart in line 5 is what invokes the code that constructs the objects and callable closures.
If you're unfamiliar with Javascript, it might help to look up some tutorial material on its more exotic features, like closures.

Resources