How to get MATLAB to recognise newly added static methods? - oop

I am using classes and static methods to 'scope' functions in a namespace, similar to C#. However, every time I add a new method to a class, at first it is not found. I have to restart the MATLAB environment (2007a) for the new methods to be recognised.
Surely there is an 'update' or 'refresh' type command that I can use so that I do not have to restart the MATLAB environment each time I add a function?

Issuing this call to CLEAR should do it:
clear classes
One unfortunate side effect of this is that it also effectively issues a clear all, which clears all of the variables in the workspace as well (however, this would happen anyway when you close and restart MATLAB). This clearing of the workspace actually serves a purpose, since it will remove any variables of the same type as the old version of your class, which potentially wouldn't work correctly with the new version of your class.
The function REHASH may work, but I doubt it (I think it deals more with file paths than class definitions).

Clearing instances of your class should work.
Suppose that you have an instance of "MyClass" in your base workspace:
foo = MyClass;
Now, suppose you edit MyClass and add new static method "bar":
foo.bar(); % Will cause error, as foo is instance of previous "MyClass"
However, "clear"-ing foo will remove the reference to the previous class:
clear('foo');
foo = MyClass;
foo.bar(); % this should now work.
This should be fine if you only have one or two instances of the class in your base workspace. If you have many instances of the class in your base workspace, then you may want to write a script to clear them:
varList = whos;
for iVar = 1:numel(varList)
if isequal( 'MyClass', varList(iVar).class )
clear( varlist(iVar).name );
end
end
clear('varList');
clear('MyClass');
If you have instances of the class in more locations, you may wish to extend the script as appropriate.
The last call to clear the class name might only be necessary if you are making modifications to classes in an inheritance hierarchy.

try "clear classname"

Related

Changing type of class field in inherited class

I am using newest Delphi 10.3.3
I have several main classes, which are extended from same parent class and also some, let's call it, Reflection classes, which has also same parent. I want instance of main class to have link to corresponding reflection instance, but I run to this issue (I simplified it to this example):
Main classes:
TMainClass = class
Link: TReflectionClass;
end;
TCarMainClass = class(TMainClass)
Link: TCarReflectionClass;
end;
Reflection classes:
TReflectionClass = class;
TCarReflectionClass = class(TReflectionClass);
The problem lies in Link field. I want Link field in TCarMainClass to be directly defined as TCarReflectionClass to avoid type-casting on lot of pieces of code (and also risking some errors), however if I define class like this, TCarMainClass.Link just hides TMainClass.Link - it is defined as different field with same name. That is not good because it consumes extra memory and mainly I can't access that field from parent class, which I want (as pointer to generic instance).
Of course I can solve this by making field private of common type and define property setter/getter which handles re-typing in each class. But that is lot of extra code for these classes and also overhead on each get/set because of calling getter/setter methods.
My question is - is there some easy hack I missed, to tell compiler I want field in child class to occupy same memory location as certain field in parent class?
Thanks
and mainly I can't access that field from parent class
While it's true that parent class can't access the descendant's field, there is nothing preventing you from synchronizing the 2.
procedure TCarMainClass.SetLink(const Value : TCarReflectionClass);
begin
FLink := Value;
TMainClass(Self).FLink := Value;
end;
Now, if you absolutely require no additionnal memory use and no setters, the only remaining option (that I can think of at this time) is as GolezTrol suggested, generics.
TMainClass<T : TReflectionClass> = class
Link: T;
end;
TCarMainClass = class(TMainClass<TCarReflectionClass>)
end;
But that would probably break your design though, because TCarMainClass would be incompatible with TMainClass<TReflectionClass>. (if you want to understand why, search for the terms covariance/contravariance).

Use a Class name stored in a variable to call a Class method?

I'm probably over-thinking this/wasting time trying to avoid a bit of conditional code - so I thought I would ask. I've seen some other questions # this sort of thing but they were using php or some other language.
At the most basic, can I do something like this (I know the syntax is wrong):
Class * var = #"Playback_Up";
// call Class method to get default settings
NSMutableDictionary * dict = [var getPlaybackDefaults];
Why do I want to do this? To avoid a bunch of conditionals. I have an app where a using can select from a range of playback "types" - each type is handled by a subclass of a "Playback" class. It would be convenient to store the class names in an array and then when a selection is made (from a tableView) call the selected class, create an instance of it, etc.
Is this possible or am I digging myself into a hole here?
The correct syntax for your first line is:
Class var = NSClassFromString(#"Playback_Up");
The rest is fine, and I use this kind of technique more frequently than you might imagine.
(Except that "Playback_Up" should never be the name of a class of course.)
EDIT: Do note Paul.s's comment below. Using +class is preferred if you can hard-code the class at compile time.

Are there any "gotchas" to watch for in using a Class (object) within itself?

I've got a Registry class and there are a few Registry values that I want to access from within that Registry class. (There is a bit of a calculation with these values so I thought I'd just put all that code right in the Registry Class itself).
So we might have something within our RegistryRoutine.cls like:
Function GetMyValue() as integer
Dim R as new RegistryRoutine
<calculations>
GetMyValue=R.GetRegisetryValue (HKEY, key, value, etc.)
End Function
No, in general you won't see any problems (like member variables being overwritten or anything weird like that).
Where you could run into issues is if you have explicity shared variables that are being written to multiple times. But that's dangerous no matter what you do.
Do watch out for recursive cases - e.g., GetMyValue() should not call R.GetMyValue(), nor should GetRegistryValue() call GetMyValue().
It's rare that you actually want to do this, however.
Since you're not passing any arguments into GetMyValue(), we can assume that the current instance already has all the information it needs.
Since you're only returning an integer, not a RegistryRoutine instance, the client has no need for a new instance.
So, why not just call GetRegistryValue (without the R.)?
It's quite common for classes to work with instances of themselves. Consider, for example, how a tree structure works. Either a Node class has to keep track of its children, or has to keep track of its parent (or both). All the nodes are the same class.

naming a method - using set() when *not* setting a property?

Is setX() method name appropriate for only for setting class property X?
For instance, I have a class where the output is a string of an html table. Before you can you can call getTable, you have to call setTable(), which just looks at a other properties and decides how to construct the table. It doesn't actually directly set any class property -- only causes the property to be set. When it's called, the class will construct strHtmlTable, but you can't specify it.
So, calling it setTable breaks the convention of get and set being interfaces for class properties.
Is there another naming convention for this kind of method?
Edit: in this particular class, there are at least two ( and in total 8 optional ) other methods that must be called before the class knows everything it needs to to construct the table. I chose to have the data set as separate methods rather than clutter up the __construct() with 8 optional parameters which I'll never remember the order of.
I would recommend something like generateTable() instead of setTable(). This provides a situation where the name of the method clearly denotes what it does.
I would probably still use a setTable() method to actually set the property, though. Ideally, you could open the possibility of setting a previously defined table for further flexibility.
Yes, setX() is primarily used for setting a field X, though setX() may have some additional code that needs to run in addition to a direct assignment to a field. Using it for something else may be misleading to other developers.
I would definitely recommend against having a public setTable() and would say that setTable() could be omitted or just an unused private method depending upon your requirements.
It sounds like the activity to generate the table is more of a view of other properties on the object, so you might consider moving that to a private method on the object like generateHtmlTable(). This could be done during construction (and upon updates to the object) so that any subsequent calls to getTable() will return the the appropriate HTML.

God object - decrease coupling to a 'master' object

I have an object called Parameters that gets tossed from method to method down and up the call tree, across package boundaries. It has about fifty state variables. Each method might use one or two variables to control its output.
I think this is a bad idea, beacuse I can't easily see what a method needs to function, or even what might happen if with a certain combination of parameters for module Y which is totally unrelated to my current module.
What are some good techniques for decreasing coupling to this god object, or ideally eliminating it ?
public void ExporterExcelParFonds(ParametresExecution parametres)
{
ApplicationExcel appExcel = null;
LogTool.Instance.ExceptionSoulevee = false;
bool inclureReferences = parametres.inclureReferences;
bool inclureBornes = parametres.inclureBornes;
DateTime dateDebut = parametres.date;
DateTime dateFin = parametres.dateFin;
try
{
LogTool.Instance.AfficherMessage(Variables.msg_GenerationRapportPortefeuilleReference);
bool fichiersPreparesAvecSucces = PreparerFichiers(parametres, Sections.exportExcelParFonds);
if (!fichiersPreparesAvecSucces)
{
parametres.afficherRapportApresGeneration = false;
LogTool.Instance.ExceptionSoulevee = true;
}
else
{
The caller would do :
PortefeuillesReference pr = new PortefeuillesReference();
pr.ExporterExcelParFonds(parametres);
First, at the risk of stating the obvious: pass the parameters which are used by the methods, rather than the god object.
This, however, might lead to some methods needing huge amounts of parameters because they call other methods, which call other methods in turn, etcetera. That was probably the inspiration for putting everything in a god object. I'll give a simplified example of such a method with too many parameters; you'll have to imagine that "too many" == 3 here :-)
public void PrintFilteredReport(
Data data, FilterCriteria criteria, ReportFormat format)
{
var filteredData = Filter(data, criteria);
PrintReport(filteredData, format);
}
So the question is, how can we reduce the amount of parameters without resorting to a god object? The answer is to get rid of procedural programming and make good use of object oriented design. Objects can use each other without needing to know the parameters that were used to initialize their collaborators:
// dataFilter service object only needs to know the criteria
var dataFilter = new DataFilter(criteria);
// report printer service object only needs to know the format
var reportPrinter = new ReportPrinter(format);
// filteredReportPrinter service object is initialized with a
// dataFilter and a reportPrinter service, but it doesn't need
// to know which parameters those are using to do their job
var filteredReportPrinter = new FilteredReportPrinter(dataFilter, reportPrinter);
Now the FilteredReportPrinter.Print method can be implemented with only one parameter:
public void Print(data)
{
var filteredData = this.dataFilter.Filter(data);
this.reportPrinter.Print(filteredData);
}
Incidentally, this sort of separation of concerns and dependency injection is good for more than just eliminating parameters. If you access collaborator objects through interfaces, then that makes your class
very flexible: you can set up FilteredReportPrinter with any filter/printer implementation you can imagine
very testable: you can pass in mock collaborators with canned responses and verify that they were used correctly in a unit test
If all your methods are using the same Parameters class then maybe it should be a member variable of a class with the relevant methods in it, then you can pass Parameters into the constructor of this class, assign it to a member variable and all your methods can use it with having to pass it as a parameter.
A good way to start refactoring this god class is by splitting it up into smaller pieces. Find groups of properties that are related and break them out into their own class.
You can then revisit the methods that depend on Parameters and see if you can replace it with one of the smaller classes you created.
Hard to give a good solution without some code samples and real world situations.
It sounds like you are not applying object-oriented (OO) principles in your design. Since you mention the word "object" I presume you are working within some sort of OO paradigm. I recommend you convert your "call tree" into objects that model the problem you are solving. A "god object" is definitely something to avoid. I think you may be missing something fundamental... If you post some code examples I may be able to answer in more detail.
Query each client for their required parameters and inject them?
Example: each "object" that requires "parameters" is a "Client". Each "Client" exposes an interface through which a "Configuration Agent" queries the Client for its required parameters. The Configuration Agent then "injects" the parameters (and only those required by a Client).
For the parameters that dictate behavior, one can instantiate an object that exhibits the configured behavior. Then client classes simply use the instantiated object - neither the client nor the service have to know what the value of the parameter is. For instance for a parameter that tells where to read data from, have the FlatFileReader, XMLFileReader and DatabaseReader all inherit the same base class (or implement the same interface). Instantiate one of them base on the value of the parameter, then clients of the reader class just ask for data to the instantiated reader object without knowing if the data come from a file or from the DB.
To start you can break your big ParametresExecution class into several classes, one per package, which only hold the parameters for the package.
Another direction could be to pass the ParametresExecution object at construction time. You won't have to pass it around at every function call.
(I am assuming this is within a Java or .NET environment) Convert the class into a singleton. Add a static method called "getInstance()" or something similar to call to get the name-value bundle (and stop "tramping" it around -- see Ch. 10 of "Code Complete" book).
Now the hard part. Presumably, this is within a web app or some other non batch/single-thread environment. So, to get access to the right instance when the object is not really a true singleton, you have to hide selection logic inside of the static accessor.
In java, you can set up a "thread local" reference, and initialize it when each request or sub-task starts. Then, code the accessor in terms of that thread-local. I don't know if something analogous exists in .NET, but you can always fake it with a Dictionary (Hash, Map) which uses the current thread instance as the key.
It's a start... (there's always decomposition of the blob itself, but I built a framework that has a very similar semi-global value-store within it)