Using sort of factory class ( instance creator ) in an MVC - actionscript-3

I am trying to centralize the building of all the view instances using a centralized class called Factory. Had instantiated the factory class inside model. But later on, this structure started creating problems.
So asking it here. Where should such "factory" classes be placed inside mvc. How should they interact with the model, view and controllers ?

Working with an MVC structure does not mean that you need to forget other best practices. It's just a way of structuring an application into 3 (or 4 in the case of RL) tiers that make sense and push you towards writing clean code.
Models should never ever ever do anything that is view related. A factory that spawns display objects should be placed in the view tier. When and how that factory is instantiated, initialized and used depends on a number of factors. Since you're using a DI/IOC framework, the obvious choice for instantiation is by setting up an injection rule. As to what parts will be using the factory there's a number of possibilities: it could be passed on to the context view by the context view mediator. Or you could choose to dedicate a command to do the heavy lifting. Or you could encapsulate its usage in a separate class that listens to system events and responds accordingly (a sort of view-less mediator)
One minor thing: Factory is way too generic a name for the class. It communicates no intent at all. You should choose meaningful, descriptive names for your classes. If the factory creates view instances, at the very least it should contain 'view' in its name. You have to find a name that is specific enough, but doesn't tie down to a certain implementation. It depends a little on what level the class operates.

Related

WPF+REST+EF: what is the best way to organize DTO's?

I have a WPF MVVM app with 3 layers:
UI
Services
DAL
and some item, for example Order. I need 3 DTO:
Class for MVVM layer, with PropertyChanged notification;
Class for Json deserializer (get objects by REST API)
Class for Entity Framework (cache data in DB).
Well, I can use ONE class for all three cases, but this will be mix of different attributes (from EF, JSon, MVVM) and excess dependencies of layers.
Another way: make 3 classes, each layer has own class, and use AutoMapper for fast convert between. No bad, but 3 almost identical (90%) copy of each DTO class... not elegant solution.
What is the best approach? What do you use?
Thanks.
What is the best approach? What do you use?
The second approach, i.e. you define your business objects in a separate assembly that you can reference from all your applications. These classes should not implement any client-specific interfaces such as INotifyPropertyChanged but be pure POCO classes that contains business logic only.
In your WPF application, you then create a view model class that implements the INotifyPropertyChanged interface and wraps any properties of the business object that it makes sense to expose to and bind to from the view.
The view model then has a reference to the model and the view binds to the view model. This is typically how the MVVM design pattern is (or should be) implemented in a WPF application. The view model class contains your application logic, for example how to notify the view when a data bound property value is changed, and the model contains the business logic that is the same across all platforms and applications.
Of course this means that you will end up with a larger number of classes in total but this is not necessarily a bad thing as each class has its own responsibility.
The responsibility of a view model is to act as a model for the application specific XAML view whereas the responsibility of the model class is to implement the business logic and the responsibility of the DTO class is to simply transfer the data between the different tiers. This is a far better solution - at least in my opinion and probably in most enterprise architect's opinions as well - than defining a single class that implements all kind of UI specific logic just for the sake of reducing the number of classes.

In MVC, can model make use of services to load some data into a list box of a view?

Is it legal In MVC, so that a "model" make use of "services" to load some data ( from web) so that the data after loading can be passed into a list box of a "view" ?
My focus is on "Can Model make use of Services directly for such purposes?"
V.
I agree with Anshu's answer but I'm personally flexible about this kind of thing on my own projects if I plan them to be very small scale, that is it doesn't seem to always be worth the time to create the clear MVC separation. There's also MVVM based on MVC, some decent info on that on wikipedia and you can find it elsewhere http://en.wikipedia.org/wiki/Model_View_ViewModel
There's no set in stone rules when it comes to design pattern usage, but if you set your own rules and work within them (particularly adhering to MVC in one or more layers of abstraction) can be helpful particularly on large projects or where a team is involved.
So the answer to your question about a model making use of services is yes this is possible, is it conforming to a strict MVC pattern, no.
The model should simply be the structure that holds the data in whatever way the data relates to other data, that's what the model is made up of. The controller handles the dirty work of making the calls to the service and updating the model. The view simply is bound to or updated when changes to the model occur and makes use of the controller (usually in as3 by using event handlers on ui components) to make the right updates to the model (or calls to then update the model).
You'll likely have extra helper classes that may sort of fit somewhere in between or outside of the parts that make up the model the view or the controller, this is okay but you should be conscious of what purpose these serve and document them well and make sure it wouldn't make sense for them to somehow be handled more elegantly within the whole setup.
I would say, its rather the responsibility of the Controller to make use of services and populate the model with the data obtained from services.
This link should provide more clarity about the responsibilities of Model, View and controller in Actionscript-3

Entity Framework Code First, pointing to the entities

I get the exception 'The entity type [TYPE] is not part of the model for the current context.' when trying to run my application.
My best guess so far is that it doesn't recognize my type as a type that it has mapped. This could very well be since it is a type loaded at runtime. This type comes from a different assembly.
How does EF: CF find all it's entities to map, and how can I make it find my types ?
EF is not designed to support this feature directly. EF is ORM and ORM is mostly created for purpose when you specify types you want to use and map at design time and simply use them at runtime. It doesn't mean that it is not possible to create types at runtime (with code mapping) but it is much more complex.
Context must know about all types it should map and about their mapping. If you create context with no reference to your new type it simply doesn't know about it. How to solve it? I can think about two options:
Emit context code as well and make sure that emitted context code contains public property of type DbSet<YourEmittedEntityType> (to use default mapping conventions) or emit OnModelCreating method as well to specify custom mapping.
Emit configuration (derived from EntityTypeConfiguration<YourEmittedEntityType>) class for your new entity as well. This class will specify mapping of new entity to your database table. Once you have your configuration you can manually create DbModelBuilder register all necessary entity type configuration including your new ones created at runtime, build DbModel, compile it and use DbCompiledModel to construct new instance of the DbContext. Just make user you cache DbCompiledModel for subsequent usages because its construction is very time consuming.
In both cases make sure that table used to persist and retrieve new entity is already created and turn off any database initializers - you must maintain your database manually.
Sure this is only the first step. Now you need to emit / generate code which will use your new entity and context - be aware that EF doesn't work with interfaces and inheritance is handled specially so in the most scenarios you need code working with your emitted type directly.

Am I overdoing it with my Factory Method?

Part of our core product is a website CMS which makes use of various page widgets. These widgets are responsible for displaying content, listing products, handling event registration, etc. Each widget is represented by class which derives from the base widget class. When rendering a page the server grabs the page's widget from the database and then creates an instance of the correct class. The factory method right?
Private Function WidgetFactory(typeId)
Dim oWidget
Select Case typeId
Case widgetType.ContentBlock
Set oWidget = New ContentWidget
Case widgetType.Registration
Set oWidget = New RegistrationWidget
Case widgetType.DocumentList
Set oWidget = New DocumentListWidget
Case widgetType.DocumentDisplay
End Select
Set WidgetFactory = oWidget
End Function
Anyways, this is all fine but as time has gone on the number of types of widgets has increased to around 50 meaning the factory method is rather long. Every time I create a new type of widget I go to add another couple of lines to the method and a little alarm rings in my head that maybe this isn't the best way to do things. I tend to just ignore that alarm but it's getting louder.
So, am I doing it wrong? Is there a better way to handle this scenario?
I think the question you should ask yourself is: Why am I using a Factory method here?
If the answer is "because of A", and A is a good reason, then continue doing it, even if it means some extra code. If the answer is "I don't know; because I've heard that you are supposed to do it this way?" then you should reconsider.
Let's go over the standard reasons for using factories. Here's what Wikipedia says about the Factory method pattern:
[...], it deals with the problem of creating objects (products) without specifying the exact class of object that will be created. The factory method design pattern handles this problem by defining a separate method for creating the objects, whose subclasses can then override to specify the derived type of product that will be created.
Since your WidgetFactory is Private, this is obviously not the reason why you use this pattern. What about the "Factory pattern" itself (independent of whether you implement it using a Factory method or an abstract class)? Again, Wikipedia says:
Use the factory pattern when:
The creation of the object precludes reuse without significantly duplicating code.
The creation of the object requires access to information or resources not appropriate to contain within the composing object.
The lifetime management of created objects needs to be centralised to ensure consistent behavior.
From your sample code, it does not look like any of this matches your need. So, the question (which only you can answer) is: (1) How likely is it that you will need the features of a centralized Factory for your widgets in the future and (2) how costly is it to change everything back to a Factory approach if you need it in the future? If both are low, you can safely drop the Factory method for the time being.
EDIT: Let me get back to your special case after this generic elaboration: Usually, it's a = new XyzWidget() vs. a = WidgetFactory.Create(WidgetType.Xyz). In your case, however, you have some (numeric?) typeId from a database. As Mark correctly wrote, you need to have this typeId -> className map somewhere.
So, in that case, the good reason for using a factory method could be: "I need some kind of huge ConvertWidgetTypeIdToClassName select-case-statement anyway, so using a factory method takes no additional code plus it provides the factory method advantages for free, if I should ever need them."
As an alternative, you could store the class name of the widget in the database (you probably already have some WidgetType table with primary key typeId anyway, right?) and create the class using reflection (if your language allows for this type of thing). This has a lot of advantages (e.g. you could drop in DLLs with new widgets and don't have to change your core CMS code) but also disadvantages (e.g. "magic string" in your database which is not checked at compile time; possible code injection, depending on who has access to that table).
The WidgetFactory method is really a mapping from a typeId enumeration to concrete classes. In general it's best if you can avoid enumerations entirely, but sometimes (particularly in web applications) you need to round-trip to an environment (e.g. the browser) that doesn't understand polymorphism and you need such measures.
Refactoring contains a pretty good explanation of why switch/select case statements are code smells, but that mainly addresses the case where you have many similar switches.
If your WidgetFactory method is the only place where you switch on that particular enum, I would say that you don't have to worry. You need to have that map somewhere.
As an alternative, you could define the map as a dictionary, but the amount of code lines wouldn't decrease significantly - you may be able to cut the lines of code in half, but the degree of complexity would stay equivalent.
Your application of the factory pattern is correct. You have information which dictates which of N types is created. A factory is what knows how to do that. (It is a little odd as a private method. I would expect it to be on an IWidgetFactory interface.)
Your implementation, though, tightly couples the implementation to the concrete types. If you instead mapped typeId -> widgetType, you could use Activator.CreateInstance(widgetType) to make the factory understand any widget type.
Now, you can define the mappings however you want: a simple dictionary, discovery (attributes/reflection), in the configuration file, etc. You have to know all the types in one place somewhere, but you also have the option to compose multiple sources.
The classic way of implementing a factory is not to use a giant switch or if-ladder, but instead to use a map which maps object type name to an object creation function. Apart from anything else, this allows the factory to be modified at run-time.
Whether it's proper or not, I've always believed that the time to use a Factory is when the decision of what object type to create will be based upon information that is not available until run-time.
You indicated in a followup comment that the widget type is stored in a database. Since your code does not know what objects will be created until run-time, I think that this is a perfectly valid use of the Factory pattern. By having the factory, you enable your program to defer the decision of which object type to use until the time when the decision can actually be made.
It's been my experience that Factories grow so their dependencies don't have to. If you see this mapping duplicating itself in other places then you have cause for worry.
try categories your widgets, maybe based on their functionality.
if few of them are logically depending on each other, create them with single construction

Where would you use a Builder Pattern instead of an Abstract Factory?

I've seen this question rise here and there a few times, but I never found and answer I was happy with.
From Wikipedia:
Builder focuses on constructing a complex object step by step. Abstract Factory emphasizes a family of product objects (either simple or complex). Builder returns the product as a final step, but as far as the Abstract Factory is concerned, the product gets returned immediately.
But to the client isn't it the same thing? He gets the full object once it's built, so to him there is no added functionality.
The only way I see it is as a way or organizing the constructor code in steps, to force a structure for the implementation of the builders. Which is nice, but hardly a great step from the abstract factory.
This next bit from Wikipedia is a good reference to get to my point:
Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.
If that's so, what kind of complexity would have to be introduced in your system where you would change from a Abstract Factory to a Builder?
My point is that I can't find and example where it's clear that an Abstract Factory won't suffice and you would need a Builder instead.
The AbstractFactory is for a family of related products. The Builder is for one product.
The Builder is for building a complex product step by step, while the AbstractFactory is to build in an abstract way (that is, once for several implementations) a less complex product.
Examples of what the difference means to the calling code:
To the client code using an AbstractFactory, each method call builds one object. The client has to assemble them together. On the other side, a builder would assemble them internally, and deliver the full object graph as the last step of the building.
The builder allow to pass and check parameters one by one for the client code. But he may build the final product in one step (for example, a call to a constructor, passing in all parameters at once, even sophisticated ones that have been build themselves). So the product of a builder could be an immutable object (or graph of) (which is priceless in multi-threaded environment, for performance and memory reasons).
UPDATED in response to this comment :
Lino > It's still bothering me, though :). I mean, if you are building composite objects, and you take the director out, passing the responsibility of calling the builder methods to the clients, then it works for me. Only then the builder would seem a perfect fit. But with the director, it doens't seem like much...
Precisely, the Builder has no director, it lets each client create a complex product according to it's specific needs. The client is the director, because the director's implementation is not reused.
If you need to reuse a few times a complex building process, then you can have a method to encapsulate this (and this method is your "director").
On the contrary, for the AbstractFactory, you typically need a reusable Director, that create products alike (provided with a Factory implementation).
Some very good answers here already. I'm just offering an analogy.
Say you wanted a new desk for your new office. You go to a 'factory' and see selections then pick one of the shelf. If it fits your needs, great!
Now you have a larger office with really fancy shaped walls. Now you need a desk with the top shaped to fit your office. And you want a different legs to suit the rest of the furniture and also to fit your new Aeron chair.
You go back to the same factory, no luck. You go to a carpenter who can custom 'build' what you want. You give your specs and requirements and the 'builder' will tell you certain limitations. After a few iteration, you got the perfect desk!
Ok, a lame story but just to lighten things up :P
One good example where you'd want a builder is if you were building something piece by piece based on command line arguments. For example, consider a builder with methods like...
setName()
setType()
setOption()
A builder could also be combined with an abstract factory where the director asks the factory for a concrete product. Again, this could be done with just a factory pattern by passing the args list to the factory but what if the args were instead messages coming from a server or a client.
Sometimes the aesthetics of one pattern just fit nicer than the aesthetics of the other.
Builder is useful for configuration. Abstract Factory is useful when you don't want callers to care about the actual implementation. Two different purposes.
You could, in fact, mix the two patterns. For example Java's DocumentBuilderFactory is a classic abstract factory: if you read the docs, you'll see the process that it uses to pick an implementation. However, the DocumentBuilders that it produces can be configured afterward (although they don't follow the prototypical "builder" approach of having each configuration method return the object being configured).
Builder is an inversion of control, like the Template Method Pattern. The various functions on your concrete builder are customizable steps in a process. Abstract Factory is "just" polymorphism, where the output happens to be a newly-constructed object. The various functions on a concrete factory are different customizable processes, each presumably resulting in a different object.
So, you need a builder when you need there to be a common overall "plot" for constructing your objects, but with individual "scenes" within that plot being different. You need a factory when there is not necessarily anything at all in common between different implementations.
I think you could conceivably use both at once, with the Abstract Factory acting as the director in the Builder pattern, and each concrete factory directing things differently. However, that goes beyond the "napkin" limit for UML diagrams ;-)
I use an Abstract Factory when I will need to build multiple child factories to create different types of objects. These child factories all implement or extend the Abstract Factory. I use a Builder when there's only one type of object that needs to be built.
I'm not sure if this is the correct usage, but it is how I've seen it done, and how I've done it in the past.
Let's consider an analogy.
You're at a Fast Food chain, where the fast food you actually get is quite complex. Not only is it complex, but only certain people can take your order for certain types of food. Now, you don't know that, because the manager of the store decided to put one person behind one cash register. But if you look at him carefully, it's actually an advanced hologram because it's "abstract". An abstract order taker. Now, when you talk to the hologram, and place your order, the hologram computer reroutes (polymorphism) that order to an implant in the brain of a human order taker. The implant makes the human actually punch in the order to a real register. There are few of these "concrete" mind-controlled human beings being ordered about by the hologram. Now, when the real human being punches in the order, it get's sent to a computer in the back where there's an assembly line, or a "builder", for each type of food being built. Orders are sent to different kinds of assembly lines based on the human being and his cash register.
So, the hologram is the abstract factory, the mind-controlled humans at the registers are the concrete factories, and the assembly lines are the builders. This is a way you can actually visualize the flow of an abstract factory working WITH the builder pattern. Sometimes it's best to see how design patterns work together in order to see how they're different.
If you're looking for extra credit, try implementing this with generics. It doesn't require as much code as you might think.
For more information on when to use the Builder Pattern and its advantages you should check out my post for another similar question here
In practice, you'll probably use DI + IOC in order to do what a builder used to do. FYI.
Good answers, would like to add mine in the hopes I discover that my understanding is correct.
If you have a new office, and only need new desks, you would use a Builder. A desk will always be a desk, but there are many different configurations for a desk, i.e., size, shape, presence of a hutch, drawers, etc.
If you have a new office, and the inside is completely bare, you would need various objects and would use an Abstract Factory that creates Furniture, from which our Desk descends. In this case, Desk as we know is a "complex" object, so it uses the Builder pattern, but here it is part of a directing Abstract Factory. The Abstract Factory would also create simple objects, like very specific lamps (StraightFunkyLamp), via a StraightFunkyLampFactory class.