Where do you put program scope variables in UI driven application? - global-variables

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.

Related

How to use model in mvc architecture based application in flex

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.

ASP.Net StructureMap Injecting Previously Objects as Dependencies

(TLDR? Skip to the last couple of paragraphs for the questions...)
I have a classic ASP.Net site which was originally built around a data access layer consisting of static methods wrapping around ADO.Net. More recently, we've been introducing abstraction layers separated by interfaces which are glued together by StructureMap. However, even in this new, layered approach the repository layer still wraps around the old static ADO.Net classes (we weren't prepared to take on the task of implementing an ORM whilst simultaneously reorganising our application architecture).
This was working fine - until today. Whilst investigating some unexpected performance issues we've been having lately we noticed a couple of things about our data access classes:
Our SqlDataConnection instances aren't always being closed.
The connection objects are being stored in static variables.
Both of the above are bad practice and likely to be significantly contributing to our performance problems. The reason why the connections were being set in static variables was to share them across data access methods which is a good idea in theory - it's just a terrible implementation.
Our solution is to convert the static data access classes/methods into objects - with our core DataManager class being instantiated once at the beginning of a request and disposed once at the end (via a new PageBase class in the web layer - much of our code is not yet separated into layers). This means we have one instance of the data access class which gets used for the entire life cycle of the request and therefore only one connection.
The problem starts now when we get to the areas of the site using the newer layered architecture. With the older code, we could just pass a reference to the DataManager instance directly to the data access layer from the code behinds but this doesn't work when the layers are separated by interfaces and only StructureMap has knowledge of the different parts.
So, with all of the background out of the way here's the questions:
Is it possible for StructureMap to create instances by passing previously instantiated objects as dependencies - within the context of a single ASP.Net Page lifecycle?
If it is possible, how is this achieved? I haven't seen anything obvious in my searching and haven't had to do this in the past.
If it is not possible, what might be an alternative solution to the problem I've described above?
NOTE: This may or may not be relevant: we're calling ObjectFactory.BuildUp( this ) in a special base page for those pages which have been converted to use the new Architecture - ASP.Net doesn't provide a good access point.
Okay, this wasn't so hard in the end. Here's the code:
var instantiatedObject = new PropertyType();
ObjectFactory.Configure( x =>
{
x.For<IPropertyType>().Use( () => instantiatedObject );
x.SetAllProperties( p => p.OfType<IPropertyType>() );
}
);
We just put this in our PageBase class before the ObjectFactory.BuildUp( this ) line. It feels slightly dirty to be putting IoC configuration in the main code like this - but it's classic ASP.Net and there aren't many alternatives. I guess we could have provided some abstraction.

MVC principile in flex/as3

I am currently working on several flex projects, that have gone in a relative short amount of time from prototype to almost quite large applications.
Time has come for some refactoring to be done, so obviously the mvc principle came into mind.
For reasons out my control a framework(i.e. robotlegs etc.) is not an option.
Here comes the question...what general guidelines should I take into consideration when designing the architecture?
Also...say for example that I have the following: View, Ctrl, Model.
From View:
var ctrlInstance:Ctrl= new Ctrl();
ctrl.performControllerMethod();
In Controller
public function performControllerMethod():void{
//dome some sort of processing and store the result in the model.
Model.instance.result = method_scope_result;
}
and based on the stored values update the view.
As far as storing values in the model, that will be later used dynamically in the application, via time filtering or other operation, everything is clear, but in cases where data just needs to go in(say a tree that gets populated once at loading time), is this really necessary to use the view->controller->model->view update scheme, or can I just make the controller implement IEventDispatcher and dispatch some custom events, that hold necessary data, after the controller operation finished.
Ex:
View:
var ctrlInstance:Ctrl= new Ctrl();
ctrl.addEventListener(CustomEv.HAPPY_END, onHappyEnd);
ctrl.addEventListener(CustomEv.SAD_END, onSadEnd);
ctrl.performControllerMethod();
Controller
public function performControllerMethod():void{
(processOk) ? dispatchEvent(new CustomEv(CustomEv.HAPPY_END, theData)) : dispatchEvent(new CustomEv(CustomEv.SAD_END));
}
When one of the event handlers kicks into action do a cleanup of the event listeners(via event.currentTarget).
As I realize that this might not be a question, but rather a discussion, I would love to get your opinions.
Thanks.
IMO, this whole question is framed in a way that misses the point of MVC, which is to avoid coupling between the model, view, and controller tiers. The View should know nothing of any other tier, because as soon as it starts having references to other parts of the architecture, you can't reuse it.
Static variables that are not constant are basically just asking for trouble http://misko.hevery.com/2009/07/31/how-to-think-about-oo/. Some people believe you can mitigate this by making sure that you only access these globals by using a Controller, but as soon as all Views have a Controller, you have a situation where the static Model can be changed literally from anywhere.
If you want to use the principles of a framework without using a particular framework, check out http://www.developria.com/2010/04/combining-the-timeline-with-oo.html and http://www.developria.com/2010/05/pass-the-eventdispatcher-pleas.html . But keep in mind that established frameworks have solved most of the issues you will encounter, you're probably better off just using one.

ASP.NET plugin architecture: reference to other modules

We're currently migrating our ASP Intranet to .NET and we started to develop this Intranet in one ASP.NET website. This, however, raised some problems regarding Visual Studio (performance, compile-time, ...).
Because our Intranet basically exists of modules, we want to seperate our project in subprojects in Visual Studio (each module is a subproject).
This raises also some problems because the modules have references to each other.
Module X uses Module Y and vice versa... (circular dependencies).
What's the best way to develop such an Intranet?
I'll will give an example because it's difficult to explain.
We have a module to maintain our employees. Each employee has different documents (a contract, documents created by the employee, ...).
All documents inside our Intranet our maintained by a document module.
The employee-module needs to reference the document-module.
What if in the future I need to reference the employee-module in the document-module?
What's the best way to solve this?
It sounds to me like you have two problems.
First you need to break the business orientated functionality of the system down into cohesive parts; in terms of Object Orientated design there's a few principles which you should be using to guide your thinking:
Common Reuse Principle
Common Closure Principle
The idea is that things which are closely related, to the extent that 'if one needs to be changed, they all are likely to need to be changed'.
Single Responsibility Principle
Don't try to have a component do to much.
I think you also need to look at you dependency structure more closely - as soon as you start getting circular references it's probably a sign that you haven't broken the various "things" apart correctly. Maybe you need to understand the problem domain more? It's a common problem - well, not so much a problem as simply a part of designing complex systems.
Once you get this sorted out it will make the second part much easier: system architecture and design.
Luckily there's already a lot of existing material on plugins, try searching by tag, e.g:
https://stackoverflow.com/questions/tagged/plugins+.net
https://stackoverflow.com/questions/tagged/plugins+architecture
Edit:
Assets is defined in a different module than employees. But the Assets-class defines a property 'AssignedTo' which is of the type 'Employee'. I've been breaking my head how to disconnect these two
There two parts to this, and you might want to look at using both:
Using a Common Layer containing simple data structures that all parts of the system can share.
Using Interfaces.
Common Layer / POCO's
POCO stands for "Plain Old CLR Objects", the idea is that POCO's are a simple data structures that you can use for exchanging information between layers - or in your case between modules that need to remain loosely Coupled. POCO's don't contain any business logic. Treat them like you'd treat the String or DateTime types.
So rather than referencing each other, the Asset and Employee classes reference the POCO's.
The idea is to define these in a common assembly that the rest of your application / modules can reference. The assembly which defines these needs to be devoid of unwanted dependencies - which should be easy enough.
Interfaces
This is pretty much the same, but instead of referring to a concrete object (like a POCO) you refer to an interface. These interfaces would be defined in a similar fashion to the POCO's described above (common assembly, no dependencies).
You'd then use a Factory to go and load up the concrete object at runtime. This is basically Dependency Inversion.
So rather than referencing each other, the Asset and Employee classes reference the interfaces, and concrete implementations are instantiated at runtime.
This article might be of assistance for both of the options above: An Introduction to Dependency Inversion
Edit:
I've got the following method GetAsset( int assetID ); In this method, the property asset.AssignedTo (type IAssignable) is filled in. How can I assign this properly?
This depends on where the logic sits, and how you want to architect things.
If you have a Business Logic (BL) Layer - which is mainly a comprehensive Domain Model (DM) (of which both Asset and Employee were members), then it's likely Assets and Members would know about each other, and when you did a call to populate the Asset you'd probably get the appropriate Employee data as well. In this case the BL / DM is asking for the data - not isolated Asset and Member classes.
In this case your "modules" would be another layer that was built on top of the BL / DM described above.
I variation on this is that inside GetAsset() you only get asset data, and atsome point after that you get the employee data separately. No matter how loosely you couple things there is going to have to be some point at which you define the connection between Asset and Employee, even if it's just in data.
This suggests some sort of Register Pattern, a place where "connections" are defined, and anytime you deal with a type which is 'IAssignable' you know you need to check the register for any possible assignments.
I would look into creating interfaces for your plug-ins that way you will be able to add new modules, and as long as they follow the interface specifications your projects will be able to call them without explicitly knowing anything about them.
We use this to create plug-ins for our application. Each plugin in encapsulated in user control that implements a specific interface, then we add new modules whenever we want, and because they are user controls we can store the path to the control in the database, and use load control to load them, and we use the interface to manipulate them, the page that loads them doesn't need to know anything about what they do.

What Does the DRY Principle Actually Look Like in ASP.NET MVC?

I keep hearing about the DRY Principle and how it is so important in ASP.NET MVC, but when I do research on Google I don't seem to quite understand exactly how it applies to MVC.
From what I've read its not really the copy & paste code smell, which I thought it was, but it is more than that.
Can any of you give some insight into how I might use the DRY Principle in my ASP.NET MVC application?
DRY just means "Don't Repeat Yourself". Make sure that when you write code, you only write it one time. If you find yourself writing similar functionality in all of your Controller classes, make a base controller class that has the functionality and then inherit from it, or move the functionality into another class and call it from there instead of repeating it in all the controllers.
use filter attributes to manage aspects (authentication, navigation, breadcrumbs, etc)
use a layer supertype controller (apply common controller-level filters to it, see mvccontrib for an example)
write custom actionresults (like in mvccontrib - for example we made one called logoutresult that just does a FormsAuthentication.Logout()
use a convention for view names
most importantly - keep you controller actions dumb, look for reuse opportunities in services
Don't Repeat Yourself. It can apply to many different aspects of programming. The most basic level of this is prevent code smell. I haven't used ASP.NET so I can't get specific to it and MVC's.
In C++ Templating prevets multiple copies of the same function.
In C void * pointers can be used in a similar fashion, but with great care.
Inheriting from another function allows function allows other functions to use the same code base without having to copy the code.
Normalizing data in a database minimizes redundant data. Also adhereing to the DRY principle.
When you go over a "thought" in a project. Ask yourself.
Have I already wrote this code?
Will this code be useful elsewhere.
Can I save coding by building off of a previous class/function.
DRY is not specific to any one technology. Just make sure you look at your classes from a functionality standpoint (not even from a copy/paste coder view) and see where the duplication occurs. This process will probably not happen in one sitting, and you will only notice duplication after reviewing your code several months later when adding a new feature. If you have unit tests, you should have no fear in removing that duplication.
One advantage of MVC as related to not repeating yourself is that your controller can do tasks common to all pages in the one class. For example, validating against certain types of malicious requests or validating authentication can be centralized.
DRY should not only be applied to code, but to information in general. Are you repeating things in your build system? Do you have data which should be moved to a common configuration file, etc.
Well, the most common example that I can give about DRY and UI is using things like MasterPages and UserControls.
MasterPages ensure that you have written all the static HTML only once.
UserControls ensure reusability of code. Example, you will have a lot of forms doing basic stuff like CRUD. Now, ideally we want all users to see different pages for Create and Update though the forms fields in both will almost be the same. What we can do is combine all the common controls and put them into a control that can be reused over both the pages. This ensures that we are never retyping (or copy-pasting) the same code.
DRY is especially important in MVC because of the increase in the sheer number of files to accomplish the same task.
There seems to be a misconception that everything in a domain model has to be copied up as a special view model. You can have domain models be domain models but view models be something that know nothing of domain specifics and be more generic. For example:
Domain Model classes: Account, Asset, PurchaseOrder
View Model: List, Table, Tuple, SearchFormBackingModel:Checked options, Outputoptions, etc. The view itself might be much more view implementation specific.
The Tuple/Dictonary/Map might map to Account, Asset and PurchaseOrder single instances but a Table might be useful for a collection of them etc. You still have MVC but you have session data, not ready for transaction yet in a view model without necessarily having it violate the rules of your domain model which is where the rules should go. They will be less anemic and anti-pattern that way. You can pass these rules up front and use them there or just in back or both depending on how the system reads from clients etc.

Resources