pass by refernce method in matlab - matlab

I'm developing a robotics application in Matlab for my thesis. I'm experienced in C#, PHP, js, etc etc.
I would love if objects I create could somehow be passed by reference. I heard that there are things called "handle objects" and others called "value objects". I can't find any specific documentation on how to create a "handle object" and it seems they are usually graphics objects.
I have a few design patterns that are easy to implement when passing by reference is possible. I would like certain objects to share 'simulation spaces', without making each space a global variable. I would like to avoid passing IDs around everywhere, in an effort to keep objects synchronized. I would like to share environmental objects between robots, without worrying about the fact that passing this object actually copies it. (this will lead to bugs over time)
I'm starting to feel like my only solution will be to have a weird global 'object broker' that has the latest copy of many common system objects. I hope to avoid this sort of thing!
Any advice would be amazing!

Handle objects are created by the following syntax
classdef myClass < handle
properties
% properties here
end
methods
% methods here
end
end
A good place to start looking in the documentation is the classes start page. Note that value and handle classes have only been implemented in R2008a, and are reasonably bug-free since R2009a (though more recent releases have improved performance quite a bit).
If you're coming from other languages, this section about the differences between Matlab and other languages OOP can be useful.

Your classes should inherit from the handle abstract class
classdef MyHandleClass < handle
% // class stuff
Class with this semantics can be passed by reference in a java like way.
Consider also this section of the guide.

Related

Speed advantage of defining function bodies in classdef file?

In C++ (at least as of a decade ago), there was speed advantage in defining the body of a class method in the header file, where the class is defined. No function call overhead was suffered because, in the compilation process, the invocation of such functions was replaced by the code in the body of the function. Subsquently, all source level optimizations (and all optimizations beyond source level) could be brought to bear.
Is there an analogous advantage to putting the body of class methods in the classdef file itself rather than in a separate m-file? I'm speaking specifically about the case where one defines a #myclass/myclass.m, with method m-files in the directory #myclass. The two options I'm considering is to have the code for the body of a method mymethod put into the classdef in #myclass/myclass.m versus being in a separate file #myclass/mymethod.m.
However, an very related auxiliary question would be how those two options compare with having everything defined in a myclass.m file, with no folder #myclass.
Please note that I have previously posted this to usenet
Summarizing the comments as the answer to this question: Using an #classFolder folder containing separate method m-files is faster than having a single m file containing the entireties of the function definitions in the classdef. This is the case even though OOP in general has sped up in 2015b.
I find this a happy answer because I see great value in separating the code implementation of a class's methods from the class definition itself. That's the whole idea of separating interface from implementation. I can look at the classdef and see only a map of the class rather than have those key information elements completely dispersed by the deluge of code that accompanies implementation.
It's just too bad that this doesn't work so well for weakly typed languages. What's listed in the classdef is just member names (properties or methods) with no specification of what class they are. So not as much information as in a strongly typed language. In fact, very little info about what the class, its properties, and its methods really are. Furthermore, there is nothing to ensure that the actual method implementation even complies with the argument list in the classdef. These kind of details helped prevent development errors in a strongly typed language, especially when one's body of classes get large.

Access methods with other classes in MATLAB

I am teaching myself how to use object oriented programming with MATLAB and have a question about access.
I have three current classes that need to interact with each other. One class, which I'll call main, is what the user will interface with (or the gui if I build one). Main stores all of the pertinent data that the use may want and has a few methods to perform some preprocessing and to construct the main object. Main also calls the constructors for the two other classes.
Another class, I'll call it instruction, loads information about the steps to process the data (this is a recursive process) and some other information.
The final class, which I'll call core, performs the core operations of the process.
Heres what my question is. Within main I have some "helper" methods that are used in the preprocessing. I want the access to these helper methods to be private so that the user cannot see or use them. Some of these helper functions also need to be used by the processes in core. My question is how do I grant access to the helper functions in main so that only main and core can access them? I have tried to understand the information provided here: http://www.mathworks.com/help/matlab/matlab_oop/selective-access-to-class-methods.html, but when I try something like:
classdef main < handle
%this is the main class
properties
core %the core object
instruction %the instruction object
end %properties
methods (Access = {?core,?main})
... %some code
end %methods
end %class
Matlab gives me this error:
Illegal value for attribute 'Access'.
Parameter must be a string.
Any help would be greatly appreciated!
Andrew
Btw, I realize that having three different classes is unnecessary here but as I stated I am just learning object oriented programming and when I started this project I thought it would be a good idea to have multiple classes because the total project will be over 5000 lines of code.
Is it possible you're using a relatively old version of MATLAB?
The ability to give access to class methods to specific classes was implemented in release 2012a.
If you're using a version of MATLAB older than that, you can only set method access attributes to public, protected or private.
Note that the documentation page you link to always refers to the current version of MATLAB (2014a at the moment). You can access old versions of the documentation via the website as well by logging into your MathWorks account.
If you have methods of main that need to be accessed by core, that could be a sign that you've designed your class relationships poorly. If core is a property of main, then perhaps it could be a method of core, and main could call it via core.
Selective access is needed quite rarely. The main reason for not using it, is that it breaks the encapsulation principle of OOP. I would consider changing your design, before implementing it.
For more information, check out the friend keyword in C++. Most likely you will find a lot of information on it, and why not to use it.

What functions to put inside a class

If I have a function (say messUp that does not need to access any private variables of a class (say room), should I write the function inside the class like room.messUp() or outside of it like messUp(room)? It seems the second version reads better to me.
There's a tradeoff involved here. Using a member function lets you:
Override the implementation in derived classes, so that messing up a kitchen could involve trashing the cupboards even if no cupboards are available in a generic room.
Decide that you need to access private variables later on, without having to refactor all the code that uses the function.
Make the function part of an interface, so that a piece of code may require that its argument be mess-up-able.
Using an external function lets you:
Make that function generic, so that you may apply it to rooms, warehouses and oil rigs equally (if they provide the member functions required for messing up).
Keep the class signature small, so that creating mock versions for unit testing (or different implementations) becomes easier.
Change the class implementation without having to examine the code for that function.
There's no real way to have your cake and eat it too, so you have to make choices. A common OO decision is to make everything a method (unless clearly idiotic) and sacrifice the three latter points, but that doesn't mean you should do it in all situations.
Any behaviour of a class of objects should be written as an instance method.
So room.messUp() is the OO way to do this.
Whether messUp has to access any private members of the class or not, is irrelevant, the fact that it's a behaviour of the room, suggests that it's an instance method, as would be cleanUp or paint, etc...
Ignoring which language, I think my first question is if messUp is related to any other functions. If you have a group of related functions, I would tend to stick them in a class.
If they don't access any class variables then you can make them static. This way, they can be called without needing to create an instance of the class.
Beyond that, I would look to the language. In some languages, every function must be a method of some class.
In the end, I don't think it makes a big difference. OOP is simply a way to help organize your application's data and logic. If you embrace it, then you would choose room.messUp() over messUp(room).
i base myself on "C++ Coding Standards: 101 Rules, Guidelines, And Best Practices" by Sutter and Alexandrescu, and also Bob Martin's SOLID. I agree with them on this point of course ;-).
If the message/function doesnt interract so much with your class, you should make it a standard ordinary function taking your class object as argument.
You should not polute your class with behaviours that are not intimately related to it.
This is to repect the Single Responsibility Principle: Your class should remain simple, aiming at the most precise goal.
However, if you think your message/function is intimately related to your object guts, then you should include it as a member function of your class.

How do you go from an abstract project description to actual code?

Maybe its because I've been coding around two semesters now, but the major stumbling block that I'm having at this point is converting the professor's project description and requirements to actual code. Since I'm currently in Algorithms 101, I basically do a bottom-up process, starting with a blank whiteboard and draw out the object and method interactions, then translate that into classes and code.
But now the prof has tossed interfaces and abstract classes into the mix. Intellectually, I can recognize how they work, but am stubbing my toes figuring out how to use these new tools with the current project (simulating a web server).
In my professors own words, mapping the abstract description to Java code is the real trick. So what steps are best used to go from English (or whatever your language is) to computer code? How do you decide where and when to create an interface, or use an abstract class?
So what steps are best used to go from English (or whatever your language is) to computer code?
Experience is what teaches you how to do this. If it's not coming naturally yet (and don't feel bad if it doesn't, because it takes a long time!), there are some questions you can ask yourself:
What are the main concepts of the system? How are they related to each other? If I was describing this to someone else, what words and phrases would I use? These thoughts will help you decide what classes are useful to think about.
What sorts of behaviors do these things have? Are there natural dependencies between them? (For example, a LineItem isn't relevant or meaningful without the context of an Order, nor is an Engine much use without a Car.) How do the behaviors affect the state of the other objects? Do they communicate with each other, and if so, in what way? These thoughts will help you develop the public interfaces of your classes.
That's just the tip of the iceberg, of course. For more about this thought process in general, see Eric Evans's excellent book, Domain-Driven Design.
How do you decide where and when to create an interface, or use an abstract class?
There's no hard and fast prescriptions; again, experience is the best guide here. That said, there's certainly some rules of thumb you can follow:
If several unrelated or significantly different object types all provide the same kind of functionality, use an interface. For example, if the Steerable interface has a Steer(Vector bearing) method, there may be lots of different things that can be steered: Boats, Airplanes, CargoShips, Cars, et cetera. These are completely unrelated things. But they all share the common interface of being able to be steered.
In general, try to favor an interface instead of an abstract base class. This way you can define a single implementation which implements N interfaces. In the case of Java, you can only have one abstract base class, so you're locked into a particular inheritance hierarchy once you say that a class inherits from another one.
Whenever you don't need implementation from a base class, definitely favor an interface over an abstract base class. This would also be handy if you're operating in a language where inheritance doesn't apply. For example, in C#, you can't have a struct inherit from a base class.
In general...
Read a lot of other people's code. Open source projects are great for that. Respect their licenses though.
You'll never get it perfect. It's an iterative process. Don't be discouraged if you don't get it right.
Practice. Practice. Practice.
Research often. Keep tackling more and more challenging projects / designs. Even if there are easy ones around.
There is no magic bullet, or algorithm for good design.
Nowadays I jump in with a design I believe is decent and work from that.
When the time is right I'll implement understanding the result will have to refactored ( rewritten ) sooner rather than later.
Give this project your best shot, keep an eye out for your mistakes and how things should've been done after you get back your results.
Keep doing this, and you'll be fine.
What you should really do is code from the top-down, not from the bottom-up. Write your main function as clearly and concisely as you can using APIs that you have not yet created as if they already existed. Then, you can implement those APIs in similar fashion, until you have functions that are only a few lines long. If you code from the bottom-up, you will likely create a whole lot of stuff that you don't actually need.
In terms of when to create an interface... pretty much everything should be an interface. When you use APIs that don't yet exist, assume that every concrete class is an implementation of some interface, and use a declared type that is indicative of that interface. Your inheritance should be done solely with interfaces. Only create concrete classes at the very bottom when you are providing an implementation. I would suggest avoiding abstract classes and just using delegation, although abstract classes are also reasonable when two different implementations differ only slightly and have several functions that have a common implementation. For example, if your interface allows one to iterate over elements and also provides a sum function, the sum function is a trivial to implement in terms of the iteration function, so that would be a reasonable use of an abstract class. An alternative would be to use the decorator pattern in that case.
You might also find the Google Techtalk "How to Design a Good API and Why it Matters" to be helpful in this regard. You might also be interested in reading some of my own software design observations.
Also, for the coming future, you can keep in pipeline to read the basics on domain driven design to align yourself to the real world scenarios - it gives a solid foundation for requirements mapping to the real classes.

What's better: Writing functions, or writing methods? What costs more performance?

Currently I am making some decisions for my first objective-c API. Nothing big, just a little help for myself to get things done faster in the future.
After reading a few hours about different patterns like making categories, singletons, and so on, I came accross something that I like because it seems easy to maintain for me. I'm making a set of useful functions, that can be useful everywhere.
So what I did is:
1) I created two new files (.h, .m), and gave the "class" a name: SLUtilsMath, SLUtilsGraphics, SLUtilsSound, and so on. I think of that as kind of "namespace", so all those things will always be called SLUtils******. I added all of them into a Group SL, which contains a subgroup SLUtils.
2) Then I just put my functions signatures in the .h file, and the implementations of the functions in the .m file. And guess what: It works!! I'm happy with it, and it's easy to use. The only nasty thing about it is, that I have to include the appropriate header every time I need it. But that's okay, since that's normal. I could include it in the header prefix pch file, though.
But then, I went to toilet and a ghost came out there, saying: "Hey! Isn't it better to make real methods, instead of functions? Shouldn't you make class methods, so that you have to call a method rather than a function? Isn't that much cooler and doesn't it have a better performance?" Well, for readability I prefer the functions. On the other hand they don't have this kind of "named parameters" like methods, a.f.a.i.k..
So what would you prefer in that case?
Of course I dont want to allocate an object before using a useful method or function. That would be harrying.
Maybe the toilet ghost was right. There IS a cooler way. Well, for me, personally, this is great:
MYNAMESPACECoolMath.h
#import <Foundation/Foundation.h>
#interface MYNAMESPACECoolMath : NSObject {
}
+ (float)randomizeValue:(float)value byPercent:(float)percent;
+ (float)calculateHorizontalGravity:(CGPoint)p1 andPoint:(CGPoint)p2;
// and some more
#end
Then in code, I would just import that MYNAMESPACECoolMath.h and just call:
CGFloat myValue = [MYNAMESPACECoolMath randomizeValue:10.0f byPercent:5.0f];
with no nasty instantiation, initialization, allocation, what ever. For me that pattern looks like a static method in java, which is pretty nice and easy to use.
The advantage over a function, is, as far as I noticed, the better readability in code. When looking at a CGRectMake(10.0f, 42.5f, 44.2f, 99.11f) you'll may have to look up what those parameters stand for, if you're not so familiar with it. But when you have a method call with "named" parameters, then you see immediately what the parameter is.
I think I missed the point what makes a big difference to a singleton class when it comes to simple useful methods / functions that can be needed everywhere. Making special kind of random values don't belong to anything, it's global. Like grass. Like trees. Like air. Everyone needs it.
Performance-wise, a static method in a static class compile to almost the same thing as a function.
Any real performance hits you'd incur would be in object instantiation, which you said you'd want to avoid, so that should not be an issue.
As far as preference or readability, there is a trend to use static methods more than necessary because people are viewing Obj-C is an "OO-only" language, like Java or C#. In that paradigm, (almost) everything must belong to a class, so class methods are the norm. In fact, they may even call them functions. The two terms are interchangeable there. However, this is purely convention. Convention may even be too strong of a word. There is absolutely nothing wrong with using functions in their place and it is probably more appropriate if there are no class members (even static ones) that are needed to assist in the processing of those methods/functions.
The problem with your approach is the "util" nature of it. Almost anything with the word "util" it in suggests that you have created a dumping ground for things you don't know where to fit into your object model. That probably means that your object model is not in alignment with your problem space.
Rather than working out how to package up utility functions, you should be thinking about what model objects these functions should be acting upon and then put them on those classes (creating the classes if needed).
To Josh's point, while there is nothing wrong with functions in ObjC, it is a very strongly object-oriented language, based directly on the grand-daddy of object-oriented languages, Smalltalk. You should not abandon the OOP patterns lightly; they are the heart of Cocoa.
I create private helper functions all the time, and I create public convenience functions for some objects (NSLocalizedString() is a good example of this). But if you're creating public utility functions that aren't front-ends to methods, you should be rethinking your patterns. And the first warning sign is the desire to put the word "util" in a file name.
EDIT
Based on the particular methods you added to your question, what you should be looking at are Categories. For instance, +randomizeValue:byPercent: is a perfectly good NSNumber category:
// NSNumber+SLExtensions.h
- (double)randomizeByPercent:(CGFloat)percent;
+ (double)randomDoubleNear:(CGFloat)percent byPercent:(double)number;
+ (NSNumber *)randomNumberNear:(CGFloat)percent byPercent:(double)number;
// Some other file that wants to use this
#import "NSNumber+SLExtensions.h"
randomDouble = [aNumber randomizeByPercent:5.0];
randomDouble = [NSNumber randomDoubleNear:5.0 byPercent:7.0];
If you get a lot of these, then you may want to split them up into categories like NSNumber+Random. Doing it with Categories makes it transparently part of the existing object model, though, rather than creating classes whose only purpose is to work on other objects.
You can use a singleton instance instead if you want to avoid instantiating a bunch of utility objects.
There's nothing wrong with using plain C functions, though. Just know that you won't be able to pass them around using #selector for things like performSelectorOnMainThread.
When it comes to performance of methods vs. functions, Mike Ash has some great numbers in his post "Performance Comparisons of Common Operations". Objective-C message send operations are extremely fast, so much so that you'd have to have a really tight computational loop to even see the difference. I think that using functions vs. methods in your approach will come down to the stylistic design issues that others have described.
Optimise the system, not the function calls.
Implement what is easiest to understand and then when the whole system works, profile it and speed up what's slow. I doubt very much that the objective-c runtime overhead of a static class is going to matter one bit to your whole app.