How to separate model from gui? - user-interface

I hope this is not something very trivial and obvious.
I have some similar programs that I am working at. In each program I have to implement future about saving projects. I came with following design :
Project
-- Program1Project
-- Program2Project
The base class Project :
class Project
{
public:
void NewProject();
void SaveProejct();
void OpenProject();
protected:
virtual void New();
virtual void Save();
virtual void Open();
};
The virtual functions are reimplemented in the derived classes cause only the specific program knows how ( which objects to save to disk ) to actually save the project.
Also part of saving new or opening a project is showing the SaveAs/Open dialog from which the user will select where to save/open the project.
For example, the NewProject() is implemented in terms of the New method:
void Project::NewProject()
{
1. // Show dialog for whether to save existing project
2. // check whether the project was already saved
3. // if yes, only overwrite the existing project
4. // if no, show SaveAs Dialog
5. // ...
6. this->New();
}
Line 1 to 5 is code that all of my programs need, i.e the flow and order in which the dialogs are created and checks are performed is the same.
I was thinking whether the actual code that creates the dialogs should be placed in the Project::New and Project::Open methods. After some thinking I decide that it is not good solution cause the Project class is model class, and model class should not create GUI. So, I was thinking maybe the best place to write the code from line 1 to line 5 , is in the Save/Open buttons event handlers of the specific program. But that means that I will have to duplicate it for each program .
So the question is how should I separate the creating of dialogs which will be the same for all of my programs from the actual saving/opening of the projects in way that do not require duplicating of code ?

The GUI should refer to the model, not the model to the GUI, and that pretty much keeps the ties of the model free of the GUI. There's really no way to keep the GUI totally free of the model. At some point, you're going to have some sort of depedency, even if the implementation is hidden away from the GUI.

You could create a seperate class that acts as a controller between the model and the views. The controller could be a membe of the project for example and on line 1 you could call this->viewController->showDialog(callBackForYes, callBackForNo, callBackForCancel)
The viewController class could directly echo out the gui, or use view classes for different gui components.

Related

How can I design classes that follow SOLID without off loading violations of SOLID somewhere else?

I have a controller that is violating Open and Closed Principle. I'm trying to figure out how to solve this with certain conditions. Here is the implementation.
struct BasicRecording
{
void show() {}
void hide() {}
};
struct AdvanceRecording
{
void show() {}
void hide() {}
};
class NotSolidRecordingSettingsController
{
BasicRecording br;
AdvanceRecording ar;
public:
void swithToAR();
void swithToBR();
};
void NotSolidRecordingSettingsController::swithToAR()
{
br.hide();
ar.show();
};
void NotSolidRecordingSettingsController::swithToBR()
{
ar.hide();
br.show();
};
The problem here is if I have a new recording settings, I would need to go back inside settings controller and add that new recording settings. If I inject the BasicRecording and AdvanceRecording in NotSolidRecordingSettingsController, then the Object instantiating NotSolidRecordingSettingsController will need to do the instantiating of BasicRecording and AdvanceRecording. But then that Object then violates OCP. Somebody has to create the object.
How can I design this to be OCP without just off loading the Not OCP part to some other thing?
Is there a particular design pattern for this kind of problem?
In the SOLID principles, OCP is really a consequence of SRP -- a class should have a single responsibility, and its code should only change when its internal requirements -- the requirements associated with its one job -- change.
In particular, a class shouldn't have to change because it's clients change. It may have a lot of clients and you don't want to mess with its code every time it gets new clients or the existing clients need to do something different. Hence OCP. Note that in OCP, "closed for modification" means you don't mess with it when you change the stuff that uses it. You do modify it when its own internal requirements change. That's just maintenance.
So OCP is about how classes relate to their clients, BUT, there are classes that have no clients. Their job is not to be services, and they are not used by other classes or to implement APIs, etc. These classes do not need to worry about OCP, because they naturally have no reason to change other than a change to their internal requirements.
A great example of such a class is what is sometimes called a "composition root" (googlable). Its single responsibility is to define how the system is built from its components. This is the guy that creates all the objects and injects them into everywhere they're needed.
You need a composition root that injects the settings panes into the controller (and whatever triggers them, because you can't have a method called switchToAR anymore). This class' job is to define the system by creating the required objects. When the arrangement of objects needs to change, then, that is a change to its internal requirements and you can go ahead and modify its code without violating SOLID.
(or you can have all that stuff read from configuration instead, but that is just implementing the composition root in config instead of your programming language. Sometimes that is a good idea, and sometimes not)

Is it bad to use ViewModelLocator to Grab other VM's for use in another Vm?

I am using MVVM light and figured out since that the ViewModelLocator can be used to grab any view model and thus I can use it to grab values.
I been doing something like this
public class ViewModel1
{
public ViewModel1()
{
var vm2 = new ViewModelLocator().ViewModel2;
string name = vm2.Name;
}
}
This way if I need to go between views I can easily get other values. I am not sure if this would be best practice though(it seems so convenient makes me wonder if it is bad practice lol) as I know there is some messenger class thing and not sue if that is the way I should be doing it.
Edit
static ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<ViewModel1>();
SimpleIoc.Default.Register<ViewModel2>();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
"CA1822:MarkMembersAsStatic",
Justification = "This non-static member is needed for data binding purposes.")]
public ViewModel1 ViewModel1
{
get
{
return ServiceLocator.Current.GetInstance<ViewModel1 >();
}
}
Edit
Here is a scenario that I am trying to solve.
I have a view that you add price and store name to. When you click on the textbox for store name you are transferred to another view. This view has a textbox that you type the store you are looking for, as you type a select list get populated with all the possible matches and information about that store.
The user then chooses the store they want. They are transferred back to the view where they "add the price", now the store name is filled in also.
If they hit "add" button it takes the price, the store name, and the barcode(this came from the view BEFORE "add price view") and sends to a server.
So as you can see I need data from different views.
I'm trying to understand what your scenario is. In the MVVMlight forum, you added the following context to this question:
"I have some data that needs to be passed to multiple screens and possibly back again."
For passing data between VMs, I would also - as Matt above - use the Messenger class of MVVMLight as long as it is "fire and forget". But it is the "possibly back again" comment that sounds tricky.
I can imagine some scenarios where this can be needed. Eg. a wizard interface. In such a case I would model the data that the wizard is responsible for collecting and then bind all Views to the same VM, representing that model object.
But that's just one case.
So maybe if you could provide a little more context, I would be happy to try and help.
Yes, you can do this, in as much as the code will work but there is a big potential issue you may run into in the future.
One of the strong arguments for using the MVVM pattern is that it makes it easier to write code that can be easily tested.
With you're above code you can't test ViewModel1 without also having ViewModelLocator and ViewModel2. May be that's not too much of a bad thing in and of itself but you've set a precedent that this type of strong coupling of classes is acceptable. What happens, in the future, when you
From a testing perspective you would probably benefit from being able to inject your dependencies. This means passing, to the constructor--typically, the external objects of information you need.
This could mean you have a constructor like this:
public ViewModel1(string vm2Name)
{
string name = vm2Name;
}
that you call like this:
var vm1 = new ViewModel1(ViewModelLocator.ViewModel2.name);
There are few other issues you may want to consider also.
You're also creating a new ViewModelLocator to access one of it's properties. You probably already have an instance of the locator defined at the application level. You're creating more work for yourself (and the processor) if you're newing up additional, unnecessary instances.
Do you really need a complete instance of ViewModel2 if all you need is the name? Avoid creating and passing more than you need to.
Update
If you capture the store in the first view/vm then why not pass that (ID &/or Name) to the second VM from the second view? The second VM can then send that to the server with the data captured in the second view.
Another approach may be to just use one viewmodel for both views. This may make your whole problem go away.
If you have properties in 1 view or view model that need to be accessed by a second (or additional) views or view models, I'd recommend creating a new class to store these shared properties and then injecting this class into each view model (or accessing it via the locator). See my answer here... Two views - one ViewModel
Here is some sample code still using the SimpleIoc
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<IMyClass, MyClass>();
}
public IMyClass MyClassInstance
{
get{ return ServiceLocator.Current.GetInstance<IMyClass>();}
}
Here is a review of SimpleIOC - how to use MVVMLight SimpleIoc?
However, as I mentioned in my comments, I changed to use the Autofac container so that my supporting/shared classes could be injected into multiple view models. This way I did not need to instantiate the Locator to access the shared class. I believe this is a cleaner solution.
This is how I registered MyClass and ViewModels with the Autofac container-
var builder = new ContainerBuilder();
var myClass = new MyClass();
builder.RegisterInstance(myClass);
builder.RegisterType<ViewModel1>();
builder.RegisterType<ViewModel2>();
_container = builder.Build();
ServiceLocator.SetLocatorProvider(() => new AutofacServiceLocator(_container));
Then each ViewModel (ViewModel1, ViewModel2) that require an instance of MyClass just add that as a constructor parameter as I linked initially.
MyClass will implement PropertyChanged as necessary for its properties.
Ok, my shot at an answer for your original question first is: Yes, I think it is bad to access one VM from another VM, at least in the way it is done in the code example of this question. For the same reasons that Matt is getting at - maintainability and testability. By "newing up" another ViewModelLocator in this way you hardcode a dependency into your view model.
So one way to avoid that is to consider Dependency Injection. This will make your dependencies explicit while keeping things testable. Another option is to use the Messenger class of MVVMLight that you also mention.
In order to write maintainable and testable code in the context of MVVM, ViewModels should be as loosely coupled as possible. This is where the Messenger of MVVMLight can help. Here's a quote from Laurent on what Messenger class was intended for:
I use it where decoupled communication must take place. Typically I use it between VM and view, and between VM and VM. Strictly speaking you can use it in multiple places, but I always recommend people to be careful with it. It is a powerful tool, but because of the very loose coupling, it is easy to lose the overview on what you are doing. Use it where it makes sense, but don't replace all your events and commands with messages.
So, to answer the more specific scenario you mention, where one view pops up another "store selection" view and the latter must set the current store when returning back to the first view, this is one way to do it (the "Messenger way"):
1) On the first view, use EventToCommand from MVVMLight on the TextBox in the first view to bind the desired event (eg. GotFocus) to a command exposed by the view model. Could be eg. named OpenStoreSelectorCommand.
2) The OpenStoreSelectorCommand uses the Messenger to send a message, requesting that the Store Selector dialog should be opened. The StoreSelectorView (the pop-up view) subscribes to this message (registers with the Messenger for that type of message) and opens the dialog.
3) When the view closes with a new store selected, it uses the Messenger once again to publish a message that the current store has changed. The main view model subscribes to this message and can take whatever action it needs when it receives the message. Eg. update a CurrentStore property, which is bound to a field on the main view.
You may argue that this is a lot of messaging back and forth, but it keeps the view models and views decoupled and does not require a lot code.
That's one approach. That may be "old style" as Matt is hinting, but it will work, and is better than creating hard dependencies.
A service-based approach:
For a more service-based approach take a look at this recent MSDN Magazine article, written by the inventor of MVVMLight. It gives code examples of both approaches: The Messenger approach and a DialogService-based approach. It does not, however, go into details on how you get values back from a dialog window.
That issue is tackled, without relying on the Messenger, in this article. Note the IModalDialogService interface:
public interface IModalDialogService
{
void ShowDialog<TViewModel>(IModalWindow view, TViewModel viewModel, Action<TViewModel> onDialogClose);
void ShowDialog<TDialogViewModel>(IModalWindow view, TDialogViewModel viewModel);
}
The first overload has an Action delegate parameter that is attached as the event handler for the Close event of the dialog. The parameter TViewModel for the delegate is set as the DataContext of the dialog window. The end result is that the view model that caused the dialog to be shown initially, can access the view model of the (updated) dialog when the dialog closes.
I hope that helps you further!

C++ RAII, Prototype Design Pattern, and lazy initialization working in tandem

I'm trying my best to adhere to some strict design patterns while developing my current code base, as I am hoping I will be working on it for quite a while to come and I want it to be as flexible and clean as possible. However, in trying to combine all these design patterns to solve the current problem I am facing, I am running into some issues I'm hoping someone can advise me a bit on.
I'm working on some basic homebrewn GUI widgets that are to provide some generic click/drag/duplication behavior. On the surface, the user clicks the widget, then drags it somewhere. Having dragged it far enough, the widget will 'appear' to clone itself and leave the user dragging this new copy.
The Prototype design pattern obviously enters the foray to make this duplication functionality generalizable for many types of widgets. For most objects, the story ends there. The Prototype object is virtually an identical copy of the duplicated version the user ends up dragging.
However, one of the objects I want to duplicate has some fairly big resources attached to it, so I don't want to load them until the user actually decides to click and drag, and subsequently duplicate, that particular object. Enter Lazy initialization. But this presents me with a bit of a conundrum. I cannot just let the prototype object clone itself, as it would need to have the big resources loaded before the user duplicates the dummy prototype version. I'm also not keen on putting some logic into the object which, upon being cloned/duplicated, checks what's going on and decides if it should load in these resources. Instead, a helpful person suggested I create a kind of shell object and when it gets cloned, it were to return this more derived version containing the resources allowing for me to both use RAII and lazy initialization.
But I'm having some trouble implementing this, and I'm starting to wonder if I can even do it the way I'm thinking it should be done. Right now it looks like this:
class widgetSpawner : public widget {
public:
widgetSpawner();
~widgetSpawner();
private:
widget* mPrototypeWidget; // Blueprint with which to spawn new elements
};
class widgetAudioShell : public widget {
public:
widgetAudioShell(std::string pathToAudioFile);
widgetAudioShell( const widgetAudioShell& other );
~widgetAudioShell();
virtual widgetAudio* clone() const { return new widgetAudio(*this); };
private:
std::string mPathToAudioFile;
};
class widgetAudio : public widgetAudioShell {
public:
widgetAudio(AudioEngineAudioTrack &aTrack);
widgetAudio( const widgetAudio& other );
widgetAudio( const widgetAudioShell& other );
~widgetAudio();
virtual widgetAudio* clone() const { return new widgetAudio(*this); };
private:
AudioEngineAudioTrack &mATrack;
};
Obviously, this is not workable as the shell doesn't know the object that's using it to derive a new class. So it cannot return it via the clone function. However, if I keep the two inheritance-wise independent (as in they both inherit from widget), then the compiler complains about lack of co-variance which I think makes sense? Or maybe it's because I am again having the trouble of properly defining one before the other.
Essentially widgetAudioShell needs to know about widgetAudio so it can return a 'new' copy. widgetAudio needs to know about widgetAudioShell so it can read it's member functions when being created/cloned.
If I am not mistaken, this circular dependency is there because of my like of using references rather than pointers, and if I have to use pointers, then suddenly all my other widgets need to do the same which I'd find quite hellish. I'm hoping someone who's had their fingers in something similar might provide some wisdom?

Turn-Based-Strategy Game - Where to Store User State

I'm writing a turn-based strategy game. Each player in the game has a team of units which can be individually controlled. On a user's turn, the game currently follows a pretty constant sequence of events:
Select a unit -> Move the selected unit -> Issue a command -> Confirm
I could implement this by creating a game class that keeps track of which of these stages the player is in and providing methods to move from one stage to the next, like this:
interface TeamCommander {
public void select(Coordinate where);
public void move(Coordinate to);
public void sendCommand(String command);
public void execute();
}
However, that would allow the possibility of a method being called at the wrong time (for example, calling move() before calling select()), and I would like to avoid that. So I currently have it implemented statelessly, like this:
interface UnitSelector {
public UnitMover select(Coordinate where);
}
interface UnitMover {
public UnitCommander move(Coordinate to);
}
interface UnitCommander {
public CommandExecutor sendCommand(String command);
}
interface CommandExecutor {
public void execute();
}
However, I'm having difficulty presenting this information to the user. Since this is stateless, the game model does not store any information about what the user is currently doing, and thus the view can't query the model about it. I could store some state in the GUI, but that would be bad form. So, my question is: does anyone have an idea about how to resolve this?
First, there's something I'm not getting here: You have to be storing persistent state somewhere, even if it is only in the View / GUI. Without persistent state you cannot have a game. I'm guessing you're using either ASP or PHP; if so, use sessions to track state.
Secondly, build your state logic into that so it is known where in the input sequence you are for each player / each unit in that player's team. Don't try to get fancy with it. B requires A, C requires B and so on. While you're writing it, just give yourself a scaffold by throwing exceptions if the call order comes up incorrect (which you should be checking on every user input as I assume this is an event driven rather than loop-driven game), and debug it from there.
As an aside: I get suspicious when I see interfaces with a single method as in your second example above. An interface typically informs of there being a unique SET of functionalities which different classes each fulfill -- unless you are trying to construct multiple different classes which use slightly different sets of individual method signatures, don't do what you're doing there. It is all fine and good to say "code to an interface and not an implementation", but you need to first take the top down approach, saying, "How does my ultimate client code (in your root game logic class or method) need to call for such-and-such to occur?" and keep asking that question up the call stack (i.e. at each subsequent sub-call codepoint). If you try to build it from the bottom up, you will end up with the confusing and unnecessarily complicated code I see there. The only other exception to this which I see on a regular basis is the command pattern, and that is generally intended to look like
void execute();
or
void execute(Object data);
...But typically not a whole slew of slightly different method signatures (again possible, but unlikely). My gut feeling comes from my experience with such constructs in that they usually don't make sense and you end up completely refactoring code that uses them.

Is there a way to make a region of code "read only" in visual studio?

Every so often, I'm done modifying a piece of code and I would like to "lock" or make a region of code "read only". That way, the only way I can modify the code is if I unlock it first. Is there any way to do this?
The easiest way which would work in many cases is to make it a partial type - i.e. a single class whose source code is spread across multiple files. You could then make one file read-only and the other writable.
To declare a partial type, you just use the partial contextual keyword in the declaration:
// MyClass.First.cs:
public partial class MyClass
{
void Foo()
{
Bar();
}
void Baz()
{
}
}
// MyClass.Second.cs:
public partial class MyClass
{
void Bar()
{
Baz();
}
}
As you can see, it ends up as if the source was all in the same file - you can call methods declared in one file from the other with no problems.
Compile it into into a library dll and make it available for reference in other projects.
Split up the code into separate files and then check into a source control system?
Given your rebuttal to partial classes... there is no way that I know of in a single file, short of documentation. Other options?
inheritance; but the protected code in the base-class (in an assembly you control); inheritors can only call the public/protected members
postsharp - stick the protected logic in attributes declared externally
However, both of these still require multiple files (and probably multiple assemblies).
I thought about this, but I would prefer to keep the class in one file. – danmine
Sorry, mac. A bit of voodoo as a SVN pre-commit might catch it but otherwise no solution other than // if you change this code you are fired
This is totally unnecessary if you're using a version control system. Because once you've checked it in, it doesn't matter what part of the code you edit, you can always diff or roll back. Heck, you could accidentally wipe out all the source code and still get it back.
I'm getting a really bad "code smell" from the fact that you want to lock certain parts of the code. I'm guessing that maybe you're doing too much in one class, in which case, refactor it to a proper set of classes. The fact that, after the 10+ years visual studio has existed, this feature isn't available, should suggest that perhaps your desire to do this is a result of poor design.

Resources