Notifying observers from nested structures - oop

Currently, I am trying to dissect some tight coupling between the data model and the UI in an application by introducing the MVC pattern. Basically, this means making the model aware of the associated views in order to have them informed whenever properties inside the model change.
The data model is represented by a nested structure:
Model
- Node
- Leaf
- Leaf
- Node
- Leaf
Each element inherits from a common abstract base class (StructuredNode).
The problem I've been thinking about is: observers should be able to subscribe to the Model (and only the Model), but each element should be able to emit change notifications. This could be achieved in two ways - either notifications are routed up the hierarchy until they reach the Model, where they get pushed to the observers, or by implementing notifications in the base class, with a static observers list, as in this example:
public abstract class Base {
private static Map<IObserver> observers;
protected synchronized void internalSubscribe(final IObserver observer) {
observers.add(observer);
}
protected synchronized void notifyObservers(final Base obj) {
for (IObserver observer : observers)
observer.changed(obj);
}
// .. other base class operations
}
In this implementation, only Model would offer a public subscribe method, which internally would delegate to the protected internalSubscribe method of the base class. At the same time, each derivative of the base class could send a change notification, like this:
// Perform some operations that change the object's internal state
// ...
// Then notify all observers
notifyObservers(this);
Is this rather good or rather bad practice (using a static observers list)? Any opinions on this? Are there alternative solutions?

A static observer list is not a common solution, and I would not consider it a good practice for a generic use model.
Observers would be notified of changes to models they are not interested in. This means that all the burden of identifying the model firing the notification falls on the observers, which probably have no good and efficient way of doing it other than going up the hierarchy and finding the root node... a lot of code, that must potentially be implemented several times in several observers. In the end it would be simpler for the observer to ignore considerations and just update or recalc, even when the updated model is not the one it's interested in.
Of course all this may not apply in your case. If you know you will not have more than one model of this class in your application, then you can very well go with this solution.
Anyway, the requirement of having only the Model with a public subscribe method should not constrain you to using a static observer container to share among all Model instances. As you said, there is another way. Routing the notifications up the hierarchy is IMHO the correct way to go.
If you want to avoid routing, then you could choose to have the nodes keep a reference to their model. This may be more efficient if you know the tree structure will be deep an not very dynamic. If nodes can be moved from one Model to another, than this is a bit risky and requires some further code to keep the reference updated.

Related

Who should create objects

I have a class Game and now I need to add players (IPlayer) to the game. And I'm thinking about two scenarios:
First approach
IPlayer AddPlayer()
In this scenario the caller does not have to worry about implementation of IPlayer. He get just an interface and cannot tamper with the object. The Game knows implementation details and can manage player's state, for example add points:
interface IPlayer
{
int Points { get; }
}
class Player : IPlayer
{
...
void AddPoints(int points);
}
Second approach
void AddPlayer(IPlayer player)
In this approach it's the caller who is responsible for delivering an object that meets the interface. Thus know sthe details.
I'm wondering: Is any of those approaches apparently better/worse?
Just a comment about my point of view:
My goal is to have clear API. And I think that the first approach is better. When I give a user my library then I give him just interface. All the details are maintained inside. (Similarly I could give an access to IGame that under the hood is an instance of Game)
I would strongly recommend using a "composition" approach as Unity does. Don't create classes/interfaces modeled around specific game entities. Have a GameObject class instead, exposing a collection of Components.
Each Component would add some features and behavior to the owning GameObject, like position, physics, stats and so on.
One GameObject instance can act as some sort of "game controller", spawning entities and keeping track of the score (or whatever rules your game has).

OOP - Form holds class instance or class holds form instance?

What is the best (read: most technically correct) way to handle GUI's for class objects?
Say, for example, that I have a class to deal with I/O. Let's call it clsIO. I also have a form to allow the user to change various options/properties of this class, let's call it frmIO. The frmIO GUI is specific to the clsIO, it will not be used anywhere else in the application.
My application will always create an instance of the clsIO, it will load its default settings and begin its operation. The user may or may not need to show the frmIO 'settings form' so that he can configure it.
To me, it appears that the best way to handle this is to store an object reference to the form inside the class, and provide a ShowConfigForm() method, rather than instantiate the form, which in turn instantiates the class.
Is this sound design?
EDIT
I plan to reuse this class/form combo across multiple projects. I have already developed it in its own project, so i can easily transfer/import to other projects that may require it.
Simple pseudo code with my current design:
class clsIO
{
public bool Active{get;set;}
public int Port{get;set;}
public ShowConfigForm()
{
frmIO settings = new frmIO(this);
settings.Show();
}
}
class frmIO
{
private clsIO _IO;
public frmIO(clsIO IO){_IO = IO;};//constructor
private btnEnable_Click()
{
_IO.Active = true;
//etc etc
}
}
Here I only need to instantiate the clsIO. Not the other way around.
The way you've done, there's a tight coupling from clsIO to the frmIO ( which is the GUI class). This is not a good practice as this tight coupling will stop you form doing Unit Testing etc.. also in case you need clsIO to be re-used for some other operation, this tight coupling to fromIO stops you from doing so.
There need to be another class that puts them together by first instantiating the clsIO and then frmIO by passing the clsIO instance into frmIO.
This way you separate the concerns of each class and give the responsibility of wiring thins up to another one, which would be cleaner.
Furthermore you can improve the design by extracting an interface from clsIO class and using the interface type within the frmIO to refer to clsIO. this will help you to have a loose coupling bewteen the 2 classes.
let me know if you me to provide a code sample, if what I described doesnt make much sense.
Usually you would have a class containing the configuration. The form itself has a reference to that settings class. If the user changes a setting in the form, the form tells it to the settings class/object.
Now you can register your clsIO as an observer on the settings. Meaning whenever something changes, the clsIO gets notified and can update its operations (this way around, the settings would contain references to all of its observers). This is known as the observer pattern. Has its strength if many 'unknown' objects observe something. I mean, settings may be something, which would impact on many different classes/objects. The observers only decide on the settings, but never change them.
If you want to keep it simple, without much effort, just add a reference to the settings in your clsIO. It's a design you can choose. This one is simpler, so if its a small and simple application, it should be sufficient.
But what I think you should really do is, separate the form from the values. A form is just a view, while the actual values are contained in another class.

Worker vs data class

I have a data class which encapsulates relevant data items in it. Those data items are set and get by users one by one when needed.
My confusion about the design has to do with which object should be responsible for handling the update of multiple properties of that data object. Sometimes an update operation will be performed which affects many properties at once.
So, which class should have the update() method?. Is it the data class itself or another manager class ? The update() method requires data exchange with many different objects, so I don't want to make it a member of the data class because I believe it should know nothing about the other objects required for update. I want the data class to be only a data-structure. Am I thinking wrong? What would be the right approach?
My code:
class RefData
{
Matrix mX;
Vector mV;
int mA;
bool mB;
getX();
setB();
update(); // which affects almost any member attributes in the class, but requires many relations with many different classes, which makes this class dependant on them.
}
or,
class RefDataUpdater
{
update(RefData*); // something like this ?
}
There is this really great section in the book Clean Code, by Robert C. Martin, that speaks directly to this issue.
And the answer is it depends. It depends on what you are trying to accomplish in your design--and
if you might have more than one data-object that exhibit similar behaviors.
First, your data class could be considered a Data Transfer Object (DTO). As such, its ideal form is simply a class without any public methods--only public properties -- basically a data structure. It will not encapsulate any behavior, it simply groups together related data. Since other objects manipulate these data objects, if you were to add a property to the data object, you'd need to change all the other objects that have functions that now need to access that new property. However, on the flip side, if you added a new function to a manager class, you need to make zero changes to the data object class.
So, I think often you want to think about how many data objects might have an update function that relates directly to the properties of that class. If you have 5 classes that contain 3-4 properties but all have an update function, then I'd lean toward having the update function be part of the "data-class" (which is more of an OO-design). But, if you have one data-class in which it is likely to have properties added to it in the future, then I'd lean toward the DTO design (object as a data structure)--which is more procedural (requiring other functions to manipulate it) but still can be part of an otherwise Object Oriented architecture.
All this being said, as Robert Martin points out in the book:
There are ways around this that are well known to experienced
object-oriented designers: VISITOR, or dual-dispatch, for example.
But these techniques carry costs of their own and generally return the
structure to that of a procedural program.
Now, in the code you show, you have properties with types of Vector, and Matrix, which are probably more complex types than a simple DTO would contain, so you may want to think about what those represent and whether they could be moved to separate classes--with different functions to manipulate--as you typically would not expose a Matrix or a Vector directly as a property, but encapsulate them.
As already written, it depends, but I'd probably go with an external support class that handles the update.
For once, I'd like to know why you'd use such a method? I believe it's safe to assume that the class doesn't only call setter methods for a list of parameters it receives, but I'll consider this case as well
1) the trivial updater method
In this case I mean something like this:
public update(a, b, c)
{
setA(a);
setB(b);
setC(c);
}
In this case I'd probably not use such a method at all, I'd either define a macro for it or I'd call the setter themselves. But if it must be a method, then I'd place it inside the data class.
2) the complex updater method
The method in this case doesn't only contain calls to setters, but it also contains logic. If the logic is some sort of simple property update logic I'd try to put that logic inside the setters (that's what they are for in the first place), but if the logic involves multiple properties I'd put this logic inside an external supporting class (or a business logic class if any appropriate already there) since it's not a great idea having logic reside inside data classes.
Developing clear code that can be easily understood is very important and it's my belief that by putting logic of any kind (except for say setter logic) inside data classes won't help you achieving that.
Edit
I just though I'd add something else. Where to put such methods also depend upon your class and what purpose it fulfills. If we're talking for instance about Business/Domain Object classes, and we're not using an Anemic Domain Model these classes are allowed (and should contain) behavior/logic.
On the other hand, if this data class is say an Entity (persistence objects) which is not used in the Domain Model as well (complex Domain Model) I would strongly advice against placing logic inside them. The same goes for data classes which "feel" like pure data objects (more like structs), don't pollute them, keep the logic outside.
I guess like everywhere in software, there's no silver bullet and the right answer is: it depends (upon the classes, what this update method is doing, what's the architecture behind the application and other application specific considerations).

Design pattern advice: Using an array of custom objects as a singleton

After a lot of studying, I am starting to code my first app.
In my code I have a class called "Measurement". I want to implement an array of Measurements. This array of Measurements needs to be accessible across multiple view controllers, so I have created a custom class called "MeasurementsArray" for the array, and made it into a singleton.
I have done this, and the code works as expected. But now that I have it working, I want to make sure that I have easy to understand code, and that I am following conventional objective-c design patterns.
If it weren't for fact that I need the array of Measurements to be a singleton, it would seem that this array belongs inside the "Measurement" class as a class method. But my understanding is that there can be only one instance of a class when it is a singleton.
But somehow, having a separate class named "MeasurmentsArray" seems a little hacky to me.
My question:
Am I approaching this the right way, or am I missing something?
If I do need the split off the array of Measurements to a separate class in order to have it be a singleton, does "MeasurementsArray" seem like an appropriate class name? If not, please provide a naming convention you would use for this type of situation.
Edit: After some inital answers, some clarification regarding the function of the app might help.
It is a fitness application that records, saves and tracks body fat percentage and body weight. Every time the user records his body fat and weight, it becomes an instance of the class "Measurement". The array of Measurements is needed in order to track changes in weight and body fat over time. A singleton is needed because multiple view controllers need access to the array.
A singleton is needed because multiple
view controllers need access to the
array.
There are other, better ways to share data between objects than to rely on a singleton.
View controllers are usually created either by the application delegate or by another view controller. The application's data model (in this case, that's your measurements array) is often also created ether by the application delegate. So when the app delegate creates a view controller, it can also give that controller a pointer to the data model. If that controller creates any view controllers, it can likewise share its pointer to the data model.
Passing the data model along from app delegate to view controller and from one view controller to the next makes your code easier to maintain, test, reconfigure, and reuse because it avoids depending on some predetermined, globally accessibly object.
Having a singleton at all may be a wrong move. There are times that a singleton is appropriate, but there's usually a better choice.
It sounds like you may already be implementing something resembling the Model-View-Controller pattern, which would be appropriate. In this context, this array of measurements is part of your model, and it may make sense for it to be a separate class, but there's likely no need for it to be a singleton.
The name MeasurementsArray is implementation-specific. I would be more inclined to call it just Measurements or to give it a name reflecting what the measurements are measuring.
In fact I wonder about the name of your Measurement class. What is it measuring? What does it actually represent?
If you post some code, we might be able to provide more specific ideas.
Based on your update and a bit of thinking, you might want to think about The Repository Pattern. Rather than having your controllers hold the array, they have access to the repository from which they can get it.
My thinking here is that your array of measurements might be supplied by a MeasurementRepository and that while now the data might be a single simple array that the repository just holds, it might evolve to something that is stored in a database per user and with variation over time, so that your repository supplies more complex access.
Rather than having this repository be a singleton (though that is certainly sometimes done), it might better be just created once and then injected into everything that needs it. See http://en.wikipedia.org/wiki/Dependency_injection and Uncle Bob's blog
I feel that a separate class is probably overkill unless it has several methods of its own, in which case it might be justified. This problem may just be an artefact of your app's structure not (yet) being well defined. Is data going to be persistent across sessions? If so, will there be a "manager" class on which you could put a property to retrieve the array; something like allMeasurements on the MeasurementStore class? Another option would be to store the array in your app delegate.
I find that if I continue working on an app, it becomes obvious how I should structure it.
Edit: To elaborate, there's nothing "wrong" with your approach; there's probably just nicer ways to do it.
If I understand you correctly, the measurements array represents past measurements of a specific user.
If that is the case- you're not looking for a singleton at all.
remember that a singleton is a single value PER APPLICATION, and what you're looking for here is a single value PER USER.
Don Roby is absolutely right- Measurements is probably a property of the User class. for example (I'm using c# notation, but you get the hang of it...):
public class User
{
public string Name {get; set;}
public int Id {get; set;}
public Measurement[] Measurements {get; set;} //one array per-user...
}

Pattern for Ownership and References Between Multiple Controllers and Semi-Shared Objects?

For example, I have window (non-document model) - it has a controller associated with it. Within this window, I have a list and an add button. Clicking the add button brings up another "detail" window / dialog (with an associated controller) that allows the user to enter the detail information, click ok, and then have the item propagated back to the original window's list. Obviously, I would have an underlying model object that holds a collection of these entities (let's call the singular entity an Entity for reference).
Conceivably, I have just one main window, so I would likely have only one collection of entities. I could stash it in the main window's controller – but then how do I pass it to the detail window? I mean, I probably don't want to be passing this collection around - difficult to read / maintain / multithread. I could pass a reference to the parent controller and use it to access the collection, but that seems to smell as well. I could stash it in the appDelegate and then access it as a "global" variable via [[NSApplication sharedApplication] delegate] - that seems a little excessive, considering an app delegate doesn't really have anything to do with the model. Another global variable style could be an option - I could make the Entity class have a singleton factory for the collection and class methods to access the collection. This seems like a bigger abuse than the appDelegate - especially considering the Entity object and the collection of said entities are two separate concerns. I could create an EntityCollection class that has a singleton factory method and then object methods for interaction with the collection (or split into a true factory class and collection class for a little bit more OO goodness and easy replacement for test objects). If I was using the NSDocument model, I guess I could stash it there, but that's not much different than stashing it in the application delegate (although the NSDocument itself does seemingly represent the model in some fashion).
I've spent quite a bit of time lately on the server side, so I haven't had to deal with the client-side much, and when I have, I just brute forced a solution. In the end, there are a billion ways to skin this cat, and it just seems like none of them are terribly clean or pretty. What is the generally accepted Cocoa programmer's way of doing this? Or, better yet, what is the optimum way to do this?
I think your conceptual problem is that you're thinking of the interface as the core of the application and the data model as something you have to find a place to cram somewhere.
This is backwards. The data model is the core of the program and everything else is grafted onto the data model. The model should encapsulate all the logical operations that can be performed on the data. An interface, GUI or otherwise, merely sends messages to the data model requesting certain actions.
Starting with this concept, it's easy to see that having the data model universally accessible is not sloppy design. Since the model contains all the logic for altering the data, you can have an arbitrarily large number of interfaces accessing it without the data becoming muddled or code complicated because the model changes the data only according to its own internal rules.
The best way to accomplish universal access is to create a singleton producing class and then put the header for the class in the application prefix headers. That way, any object in the app can access the data model.
Edit01:
Let me clarify the important difference between a naked global variable and a globally accessible class encapsulated data model.
Historically, we viewed global variables as bad design because they were just raw variables. Any part of the code could alter them at will. This nakedness led to obvious problems has you had to continuously guard against some stray fragment of code altering the global and then bringing the app down.
However, in a class based global, the global variable is encapsulated and protected by the logic implemented by the encapsulating class. This encapsulation means that while any stray fragment of code may attempt to alter the global variable inside the class, it can only do so if the encapsulating class permits the alteration. The automatic validation reduces the complexity of the code because all the validation logic resides in one single class instead of being spread out all over the app in any random place that data might be manipulated.
Instead of creating a weak point as in the case of a naked global variable, you create strong and universal validation and management of the data. If you find a problem with the data management, you only have to fix it in one place. Once you have a properly configured data model, the rest of the app becomes ridiculously easy to write.
My initial reaction would be to use a "modal delegate," a lot like NSAlerts do. You'd create your detail window by passing a reference to a delegate, which the detail window would message when it is done creating the object. The delegate—which would probably be the controller for the main window—could then handle the "done editing" message and add the object to the collection. I'd tend to not want to pass the collection around directly.
I support the EntityCollection class. If you have a list of objects, that list should be managed outside a specific controller, in my opinion.
I use the singleton method where the class itself manages it's own collections, setup and teardown. I find this separates the database/storage functionality from the controllers and keeps things clean. It's nice and easy to just call [Object objects] and have it return a reference to my list of objects.