In a MVC architecture the model is used to store data used in the application. I create a class and use some static properties to store data so that it can be used throughout the application. For example if there is a datagrid, I use a static arraycollection in model class. Update it whenever a service is called and by using databinding update the dataprovider of the datagrid. I have read that singleton class can also be used to accomplish this task. Is the way I use for model class is better or there exists some other ways too?
As the discussion Tianshen referred to points out, there is hardly any difference between a bunch of static variables and a Singleton. Both can be seen as a form of global variables, with all the accompanying downsides. I'm not going to argue about how Singletons are evil here; plenty has been written about the subject already that you can easily find on the web.
However, I would like to present an alternative: Inversion of Control (IoC), also referred to as Dependency Injection (DI). I'll explain this pattern in short, but you can also find plenty of information for yourself. Take the ArrayCollection from your example; if you'd want to avoid the static variables or the Singleton pattern, you would have to create one instance and pass that instance around from object to object throughout your application and perhaps it would even have to be passed through an object that doesn't really need it, which wouldn't be very clean either.
In comes the IoC container (for a Flex app it would take the form of library you add to your project): with such a library, you can create/configure that ArrayCollection in one place and let the IoC "inject" that single instance in whatever class that needs it.
A concrete example: we might have a configuration file like this
<fx:Object>
<s:ArrayCollection id="myLetters">
<fx:String>A</String>
<fx:String>B</String>
</s:ArrayCollection>
</fx:Object>
and a class like this
public class MyClass {
[Inject(id="myLetters")]
public var letters:IList;
}
The IoC container would then inject the myLetters ArrayCollection instance whenever a MyClass would be instantiated. There are a lot of other injection techniques, but this example is just to give you an idea.
At the time of this writing I belive Parsley to be the most widely used IoC container for Flex.
You may read the this discussion that compares Singleton and Static. Though it is in C#, the similar Object-Oriented philosophies apply.
In short, Singleton gives you better flexibility. If you use Databinding for your Flex application, using Singleton would allow you to inherit EventDispatcher, with which you can dispatch custom change events. Custom change events would give your application better performance.
Related
I want to set up several ui elements based on system information at the time of the application start up (i.e. this is info not known a priori so to set it statically in the css or the fxml file).
Is the controller constructor the best place to do this?
A first consideration was to do that either on the start() or init() methods of the main class that extends Application but it seems the set up is rather preventing programmer from easily accessing ui elements all the way down the node hierarchy. (which on the other hand is extremely easy in the respective controller through the #FXML injection)
It depends on the kind of work you need done. If you need anything that relies on your application's stage, then perform it in the start method. If not, then it can be performed in the constructor, init, or start methods. Bear in mind that the launching mechanism expects Application subclasses to provide a no-arg constructor, so if you incorporate startup logic there, then avoid requiring constructor parameters.
However, if you're going to use a controller (which I would recommend), then this logic should occur in its initialize method, not in your application class.
If you need a reference to the stage from the controller, then you can find many such solutions to passing the reference to the controller here on SO, such as making the stage reference public and static in your application class, or having such a field in your controller that can be set from your application's start method.
i am using EF4 and StructureMap in an asp.net web application. I am using the repository/unit of work patterns as detailed in this post. In the code, there is a line that delegates the setup of an ObjectContext in global.asax.
EntityUnitOfWorkFactory.SetObjectContext(() => new MyObjectContext());
On the web page code-behind, you can create a generic repository interface like so ...
IRepository<MyPocoObject> ds = ObjectFactory.GetInstance<IRepository<MyPocoObject>>();
My question is what is a good approach to refactoring this code so that I can use more than one ObjectContext and differentiate between them in the code-behind? Basically i have two databases/entity models in my application and need to query them both on the same page.
The Unit of Work is used to manage persistence across multiple repositories, not multiple object contexts.
You're not going to be able to persist changes across multiple contexts using a unit of work, as the UoW is simply implemented as a wrapper for a ObjectContext. Therefore, you'll need two unit of works.
Overall, things are going to get messy. You're going to have two OCs newed up and disposed each HTTP request, not to mention transaction management is going to be a nightmare.
Must you have two ObjectContexts? What is the reasoning for this? If it's for scalability, don't bother; it's going to be too painful for other things like your repository, unit of work and http scope management.
It's hard to provide good advice without seeing how you have your repositories set up.
Try creating wrapper classes for each object context, each implementing IUnitOfWork and a secondary unique interface (IEfSqlContext1, etc which represents one of your models/contexts).
Then you can inject whichever context you want.
As I said though, try and avoid having two EDMX/Contexts. It's more trouble than it's worth.
I'm creating a MVC base application, in the past I've alwaysed use Cairngorm as the framework for my Flex applications. For this app I'm experimenting with other approaches to mvc, not other frameworks (pureMVC or Mate), but writing my own MVC base application.
My question is in Cairngorm I've always created the model as a singleton, but what ways can I pass data from the model to the view and not use a singleton.
I was thinking of injecting the model into views or is another approach sending events containing data to and from the model to the view via the controller?
Thanks
Stephen
Personally, I think the easiest way to deal with this situation is to inject the Model directly into the View (via a constructor, or other mechanism).
Simple, yet effective.
I would declare the data as public properties. You almost always need to update data in a View based on user gestures, so using constructor arguments alone isn't very flexible and can be problematic for MXML-based Views.
Then you can either use binding expressions in the parent View to supply the data or use an IoC framework such as Swiz or Mate to inject the data. The disadvantage to the former approach is that you end up putting a lot of public properties in your parent views just so they can "relay" data to the child views. The nice thing about IoC is that you can add only the properties each View actually uses and then inject the data only where it's really needed.
I've added functions to the Date prototype and I am wondering where is the best place to put the code in a Flex project?
The best practice for a Flex application is to create a utility class to manipulate instances of a class rather than to change the prototype of that class. For example, you might create a com.example.utils.DateUtil class with static functions that accept Date objects as arguments. The reason you want to follow this best practice is that Flex uses the compiler's strict setting by default, and trying to access non-standard functions added to the prototype of a sealed class will throw compiler errors. The alternative, turning off strict mode, is not advisable because the compiler will not be able to optimize your code as well as it could under strict mode.
Probably best to put it in a preinitialize handler for the Application - in case the prototype is used by any components as they're created.
Ok, so I know that global variables are considered bad, and the singleton pattern is overused. And I have read in many places that a class should do only one task and contain only those variables that allow it to accomplish that one task. However, while working on my latest project, I actually thought about these rules before writing any code and have noticed that I tend to break them at the very beginning of the program.
I'm currently working on an MFC dialog based application, but this question could be applied to any UI driven application. I have separate classes that handle state machines, file reading/writing, and hardware interfacing. All of these objects will need some type of UI control or property display/editing. In the MFC dialog applications, the dialog is the program, so it must exist until the program is closed. I've usually just put the objects in the main dialog class for the application and had the dialog class serve double duty; as both the main UI and the home for all other objects in the application. In other applications, I've created these objects globally and referenced them from wherever they were needed. Neither of these ways seem correct. The first option breaks the one class, one task rule, and the second relies on globals and also creates hidden dependencies. I could institute some type of dependency injection, but where would all these variables that I would inject reside?
I'm just wondering what others do to organize their programs without breaking the rules?
I find that storing singletons as public data attributes of the main dialog class of an MFC dialog application works OK for a quick and dirty program. However, as the program becomes larger and more complex, things begin to get untidy.
The point where storing singletons in the dialog class needs to be refactored is probably when you start passing pointers to the dialog around, so that other classes can access the singletons it contains.
The singletons can be moved into the global namespace. This is still a bit untidy, especially when there are a large number of them. Since you have to write a separate extern for each one in a header file then define each one somewhere, you soon end up with something that looks a lot like an old fashioned C program.
A neat thing to do is to make use of the singleton that the framework has already defined for you.- the application object which is always called theApp, a specialization of CWinApp. If you place your singletons as public data members of this, then any code can get easily get access to them .
Suppose that you called your application “solver”. The dialog application creation wizard will create a class CsolverApp. Now suppose you have a singleton called ‘theData’ an instance of the class ‘cData’.
Place your singleton in the theApp
class CsolverApp : public CWinApp
{
public:
cData theData;
…
Now to access this from anywhere in your code
#include “solver.h”
theApp.theData.somepublicmethod();
It does make sense to look at this from the MVC (Model - View - Controller) viewpoint. (That the naming of MFC is an homage to MVC is another sick joke on Microsoft's part; it is hard and unintuitive (but by no means impossible) to manage the types of abstractions that are necessary in "true" MVC within MFC.)
Specifically, it sounds like you've thought out the basis for MVC design; you have the classes that do the underlying business logic work (the Model), and you know they should be separated from the UI components (the View). The issue that comes in now is the third part of the MVC trinity; the Controller.
MFC makes this stuff tough by apparently purposefully obfuscating the MVC process, by making you start with a Dialog. In your instance, the Dialog that MFC is starting you off with should be the Controller, and NOT the View. What your Dialog (Controller) is doing for you is managing your UI components (View) and allowing them to interact with your "work" classes (Model). What makes this tough again is that your UI components, to be visible, most likely need to be attached to your Dialog to be visible.
To get this sort of thing right, you really have to basically implement your Controller as a high-level object that gets instantiated from your Dialog; your Dialog is where the initial control flow comes in, your Controller gets control flow, and from there, it should treat the Dialog as just another UI component (albeit one with special status).
This allows you to have the proper level of encapsulation; your Controller invokes your business logic (Model) classes, which can communicate with each other or with the Controller as appropriate; they are segregated from the View by the Controller, instead of being embedded in the UI components and (likely) taking the "easy way" of over-privileged access to UI elements ("Hmm, I need this object to get some input from the user; I could refactor, but it'll be so much easier to just throw a dialog box up, since I have the top-level window handle...").
Once your Controller object is the home to all of the business logic objects, things become easier; you can use the Controller to provide cross-object access for any objects that need other objects. Think about which classes need to be Singletons, and use them sparingly. Resources that need contention management (such as hardware resources) are great examples of "natural singletons"; things which lend themselves to a singleton approach. You may also choose to make your Controller a singleton; depending on the requirements for access to it. Specifically, in your Dependency Injection scenario, the Controller is where you'd instantiate the objects and manage the dependencies.
This is the basic MVC approach; but, like I say, MFC makes it unusually hard and unintuitive, because of the fundamental design of MFC. I learned MUCH more about MVC AFTER an initial VERY negative impression about it due to MFC; if you can, I recommend looking into what MVC implementations look like in other languages.
Good luck!
If I am understanding you correctly, it sounds like the lifetime of your dialog objects is too long. Rather than maintaining the dialogs for the duration of your program, you should consider creating and destroying them as they are needed.
Also, global variables (or singletons) are OK so long as the thing that the variable represents is truly a global thing that persists for the lifetime of the program, rather than just a place-holder for an object of lesser duration. Using globals for the wrong things for simplicity sake will come back to bite you eventually, even if the globals are stored on the main dialog.