Factory Pattern Confusion - c#

When a client application requests for a new object,
I let the Factory class create that new object for me.
public class CarFactory{
public Car CreateCar()
{
//create a new car object and send back
}
}
The properties of the car object are populated by calling stored procedures which are stored in the database. In the database, we store the default values which can change eachday. The default tables are populated by external systems.
public class Car {
public List<string> DefaultTyres {get;set;}
public List<string> DefaultPetrolSpec {get;set;}
}
So when the factory (which the service layer calls) creates the Car object, the factory class calls the repository class that then calls the DB to populate Car's properties...but the relation of these layers sounds a bit strange...
public Car CreateCar()
{
//create a new car object and send back
//Call CarRepository.GetDefaultTyres(), CarRepository.GetDefaultPetrolSpec() etc.
}
Because I think my factory implementation is doing a lot. May be it shouldn't call the repository layers (which then call the DB to get the data for the car object).
What do you guys think? Should Factory classes communicate with DB? Is it ok if they do? if not then whose responsibilities should it be?

The answer depends on whether there could be multiple (implementations of) repositories or multiple databases/other data stores involved. If the answer to the above is yes (even if it is just an anticipated need/possibility at this point), it is better to have a repository layer to insulate the Factory class from the above mentioned changes when/if those changes happen.
Think of it differently: it is the responsibility of the factory class to know how to create cars; it is not its responsibility to know what DB to connect to/when/how. It is usually better to kepp responsibilities simple to facilitiate change and modular design

One thing I've learned over time is that there may be 5 answers to your question. And, all of them would be right. The real question is: is what you are doing make sense? If your factory is on the server and the connection to the database is closest there, then that is where the calls should be.
Now I'd sometimes ask myself the same questions as well as others. For example, should the factory create the tyres and the Petrol for the car when creating the car, or should the car be the one to know how to create itself.
So you may want to consider this: if you have a vast array of objects that your factory is creating (which is usually why you have a factory pattern) then it may make sense that all of your elements have a base class / interface that exposes a Create method. (I'm posting a very quick and dirty example, doing reflection to create the type could keep the factory even more generic)
Example:
public interface FactoryObject
{
void Create();
void Destroy();
}
public class Car:FactoryObject
{
public void Create()
{
//TODO: Create my tyres and my petrol
//TODO: Create my fenders and body
}
}
public class Bicycle:FactoryObject
{
public void Create()
{
//TODO: Create my tyres but I do not need petrol
//TODO: Create my fenders but I have no body
}
}
public class Factory
{
public FactoryObject GetFactoryObject(Type type)
{
FactoryObject returnedObject = null;
if ( type is Car ) returnedObject = new Car();
elseif (type is Bicycle) returnedObject = new Bicycle();
if (returnedObject != null)
returnedObject.Create();
return returnedObject;
}
}
In this fashion your factory knows to create a FactoryObject, however it has no bound knowledge of HOW to build that object. More importantly it doesn't care.

If you have an additional class that handles the actual DB connection, I think it's fine. What I mean by such a class is one that performs the actual connection, handles some connection/query exceptions etc. The Factory class should not know DB-related stuff, it should delegate that to another class/object.
This abstraction layer to the DB can as well be a whole hierarchical tree of classes, not just a single class. Something like this:
Each of those subclasses knows how to handle a connection to that specific RDBMS.
PS: Note that this is just an example, you may not have to do it like this. Also, having such a hierarchy can complicate things a little, because it is possible that you need a Factory for these classes as well.

Related

Entity from database directly linked to viewModel - bad practice?

I'm using Entity Framework together with MVVM.
My layers look like this:
View
ViewModel: Provides data and commands for the view.
Service: Provides access to the DAL. Contains business logic.
DAL: Provides access to the database. I'm using the repository pattern together with a UnitOfWork.
The properties in my ViewModels are more or less directly bound to an entity from my database. Example:
public class MyViewModel
{
private MyEntity _myEntity;
private MyService _myService;
// A property which is bound to my view (bidirectionally)
public string TextToDisplay
{
get { return _myEntity.SomeText; }
set
{
if (_myEntity.SomeText != value)
{
_myEntity.SomeText = value;
RaisePropertyChanged("TextToDisplay");
}
}
}
// Method called by a command when the "Save"-button is pressed
private void Save()
{
_myService.Save(_myEntity);
}
}
public class MyService
{
private MyRepository _myRepository;
private IUnitOfWork _unitOfWork;
public void Save(MyEntity myEntity)
{
_myRepository.Insert(myEntity);
_unitOfWork.Save();
}
}
So when Save is called, the database-generated attributes/properties (like ID) are updated/generated automatically.
Does this lead to side-effects? Is it a bad practice?
How do you handle it? Do you "detach" or copy objects when passing them from your database to your viewmodel? Or should the object passed to the viewmodel even be another type? How can I handle this perfectly?
Does this lead to side-effects? Is it a bad practice?
No. You are not violating any principles of the MVVM pattern and this is as close to ideal as possible as you have fully separated concerns and more importantly abstracted away from the DAL technology you are using with an abstract Model/Service implementation layer which not everyone does (some devs would inject the DbContext-derived class as the Model object and call Save() directly).
How do you handle it? Do you "detach" or copy objects when passing them from your database to your viewmodel? Or should the object passed to the viewmodel even be another type? How can I handle this perfectly?
You could go further by making sure you depend on abstractions instead of concretions by either passing IMyEntity objects around or making sure that MyEntity is a base class and a more specialised EF DAL class is handled and passed around the DAL layer, but I've previously found this to be overkill for these types of applications.
I prefer not to use copy objects due to the code bloat. I have used the child/base-class entity hierarchy before very effectively, however, it is more work and there is no real reason to do so unless you know for a fact that you need to cater for multiple child-types from the start.

Class Design and Collections

If I have a class defined as:
public class Car{
public int doors {get;set}
public int wheels {get;set}
public string make {get;set}
public string model {get;set}
public Car(){}
}
And I want to create a collection of this class. In the past I have understand it was acceptable to create a collection class:
public class CarCollection{};
That would return a collection of Cars.
With Generic List now I understand that we should not be creating collection classes, but instead creating generic list of the object inheriting some collection type.
My question is where should this code go, and what definition should the method have? For example should I just add a public method to my car class:
public List<Car> GetAllCars()
{
...
}
If so, it seems weird to instantiate a Car Class to get a collection of cars, but I know declaring it as a shared class isn't the right option either. How should we be designing our collections of classes, and where should we be including them?
It all depend how you want to use the collection of the cars. But in the scenario you mentioned in the comment, I would suggest looking into repository pattern, which would be an intermediate layer between the business logic and database.
So you would have you Car class as a model, and a repository e.g.: CarRepository. This repository would have a method for returning the list of all your cars. All the logic for populating this list would be in that class, and it would not pollute other places of the application and increase maintainability of the code.
public class CarRepository {
public List<Car> GetAllCars() {
// read data from DB and return list
}
public Car GetSingle(int carId) {
// here you just return single car
}
}
This is just to give you an idea how this might be done. Going further you can extend this concept introducing interfaces for easy testing and swapping implementations for the repository. You could then have single interface, with multiple implementations - one for reading from DB and e.g. second one for reading from XML file.
There is a lot of reading material regarding that on the Internet.

How to store/deal with data available to other classes in c#

I'm writing a CAD program. Let's say I have in input class, this class reads various data from a text file and creates lots of lists/dictionaries and .... These data need to be accessed by other methods in other classes to be modified. Now here is how I have done it so far:
I have one static class: Building.cs When I create/or load a project this class holds all the data like list of columns, beams, points, etc. All of these are stored as private fields. I can access these using the class's public methods like GetColumns or GetPoints ...
Now I also have non-static classes. They contain 2-3 public methods. and do some stuff on various parts of the building.
public static class Building
{
private static List<Column> columns;
private static List<Beams> beams;
private static List<Points> points;
public static List<Column> GetColumns()
{
return Columns;
}
}
public class ColumnsService()
{
private List<Columns> columns;
public GroupColumns(List<Columns> columns)
{
this.columns = columns;
}
public void Group()
{
// group columns
}
}
var columns = Building.GetColumns();
var columnsService = new ColumnsService(columns);
columnsService.Group();
I was wondering is this the way to go? How else can I store the data. The data needs to be accessible throughout the lifetime of the program to most of the classes. What are the best practices.
What, semantically, is a Building?
To me, the name implies that it's an instance of a structure. That, in the overall business domain, there can be many "buildings" and at any given moment one is interacting with one of them.
If that's the case, then it seems unintuitive to me to make it static. If there's more than one, it should be an instance model. It would contain attributes which describe it and operations which interact with it. The business domain being modeled should drive the structure of this object before any consideration is given to how other objects are going to interact with it.
So let's assume we make it an instance model:
public class Building
{
// attributes and operations
}
Then, as you ask, how do other objects interact with it?
Depends on the interactions.
Let's say an object needs to "render" a building in some way. Let's call it BuildingPrinter for lack of a better term. Clearly it needs a Building to "print". So it requires one for that operation:
public class BuildingPrinter
{
public void Print(Building building)
{
// implementation
}
}
Or perhaps you have an object which "wraps" a building in some way. Something which can't meaningfully exist without a building, regardless of the operations performed. I can't think of one for that particular business domain, so let's just call it a BuildingWidget. Since it needs a building to exist at all, it requires one:
public class BuildingWidget
{
private Building currentBuilding;
private BuildingWidget() { }
public BuildingWidget(Building building)
{
currentBuilding = building;
}
}
The point is, from the perspective of the models which construct the overall domain, if something is required then it must be supplied. The models shouldn't go out to some global data store, tightly coupling with that data store, to get what they need. This is called the Dependency Inversion Principle.
But where will the consuming code which orchestrates the interactions of these models get instances of a Building? There are a number of potential solutions to that.
Two common patterns would be to have a static factory or a repository. For example:
public class BuildingFactory
{
public static Building FetchBuilding(int buildingId)
{
// implementation
}
}
This factory might have a static cached building object. The building itself isn't static, but for performance reasons an instance of it is cached statically so that it's not constantly re-fetched from a backing data store (such as a database). You might also add methods to invalidate the cache and re-fetch, or encapsulate that logic into the factory itself (such as always re-fetch after 5 minutes or after 10 accesses or some other rule). (Behind the scenes, this factory might even use a repository, shown below, to re-fetch that instance. In which case, you guessed it, a BuildingRepository would be required on the BuildingFactory constructor.)
This factory object may also be responsible for creating a building based on some specifications, if for example you have reason to make the Building constructor private.
Or, to re-fetch from data, consider a repository:
public class BuildingRepository
{
public Building GetBuilding(int buildingId)
{
// fetch from database
}
public Building SaveBuilding(Building building)
{
// save to database, return updated version
}
}
Then other code throughout the domain, including the consuming code, can use these objects to get/save buildings. The factory is static, so that can be invoked anywhere. The repository is instance but doesn't need to be globally distinct, so that can be instantiated anywhere (or pulled form a dependency injection container).

Generic Interface w/ Polymorphism to handle Objects

Previous Post removed; Updated:
So I have a unique issue, which is possibly fairly common though. Properties are quite possibly are most commonly used code; as it requires our data to keep a constant value storage. So I thought how could I implement this; then I thought about how easy Generics can make life. Unfortunately we can't just use a Property in a Generic without some heavy legwork. So here was my solution / problem; as I'm not sure it is the best method- That is why I was seeking review from my peers.
Keep in mind the application will be massive; this is a very simple example.
Abstract:
Presentation Layer: The interface will have a series of fields; or even data to go across the wire through a web-service to our database.
// Interface:
public interface IHolder<T>
{
void objDetail(List<T> obj);
}
So my initial thought was an interface that will allow me to Generically handle each one of my objects.
// User Interface:
public class UI : IHolder
{
void objDetail(List<object> obj)
{
// Create an Instance
List<object> l = new List<object>();
// Add UI Fields:
l.Add(Guid.NewGuid());
l.Add(txtFirst.Text);
l.Add(txtLast.Text);
// l to our obj
obj = l;
return;
}
}
Now I have an interface; which has been used by our UI to put information in. Now; this is where the root of my curiosity has been thrown into the mixture.
// Create an Object Class
public class Customer : IHolder
{
// Member Variable:
private Guid _Id;
private String _First;
private String _Last;
public Guid Id
{
get { return _Id; }
set { _Id = value; }
}
public String First
{
get { return _First; }
set { _First = value; }
}
public String Last
{
get { return _Last; }
set { _Last = value; }
}
public virtual objDetail(List<Customer> obj)
{
// Enumerate through List; and assign to Properties.
}
}
Now this is where I thought it would be cool; if I could use Polymorphism to use the same interface; but Override it to do the method differently. So the Interface utilizes a Generic; with the ability to Morph to our given Object Class.
Now our Object Classes; can move toward our Entity interface which will handle basic Crud Operation.
I know this example isn't the best for my intention; as you really don't need to use Polymorphism. But, this is the overall idea / goal...
Interface to Store Presentation Layer UI Field Value
Implement the Properties to a Desired Class
Create a Wrapper Around my Class; which can be Polymorphed.
Morphed to a Generic for Crud Operation
Am I on the right path; is this taboo? Should I not do this? My application needs to hold each instance; but I need the flexibility to adapt very quickly without breaking every single instance in the process. That was how I thought I could solve the issue. Any thoughts? Suggestions? Am I missing a concept here? Or am I over-thinking? Did I miss the boat and implement my idea completely wrong? That is where I'm lost...
After pondering on this scenario a bit, I thought what would provide that flexibility while still ensuring the code is optimized for modification and business. I'm not sure this is the right solution, but it appears to work. Not only does it work, it works nicely. It appears to be fairly robust.
When is this approach useful? Well, when you intend to decouple your User Interface from your Logic. I'll gradually build each aspect so you can see the entire structure.
public interface IObjContainer<T>
{
void container(List<T> object);
}
This particular structure will be important. As it will store all of the desired content into it.
So to start you would create a Form with a series of Fields.
Personal Information
Address Information
Payment Information
Order Information
So as you can see all of these can be separate Database Tables, but belong to a similar Entity Model you are manipulating. This is quite common.
So a Segregation Of Concern will start to show slightly, the fields will be manipulated and passed through an Interface.
public interface IPersonalInformation
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
So essentially the Interface is passing its variable, to the Interface. So you would culminate an interface to handle that entire form or individual interfaces that you wish to call so that they remain reusable.
So now you have a series of Interfaces, or a single once. But it contains all these variables to use. So you would now create a class:
public class CustomerProperties: IPersonalInformation, IOrderInformation
{
// Implement each Interface Property
}
Now you've created a container that will hold all of your values. What is nifty about this container is you can reuse the same values for another class in your application or choose different ones. But it will logically separate the User Interface.
So essentially this is acting similar to a Repository.
Now you can take these values and perform the desired logic. What becomes wonderful now, is after you've performed your logic you pass the object into our Generic List. Then you simply implement that method in another class for your goal and iterate through your list.
The honesty is it appears to work well and decouple nicely. I feel that it was a lot of work to do something similar to a normal Repository and Unit Of Work, this answers the question but weather or not it is ideal for your project I would look into Repository, Unit Of Work, Segregation Of Concern, Inversion Of Control, and Dependency Injection. They may do this same approach cleaner.
Update:
I thought about it after I wrote this up, I noticed you could actually implement those property values into the Generic List structure bypassing a series of interfaces; but that would introduce consistency issues as you'd have to be aware of what data is being passed in each time, in order. It's possible, but may not be ideal.

MVC3 Exposing repository functionality through service

I've been playing around with asp.net MVC3 a bit and have been struggling to decide where to place my business logic. I've settled on using a service layer for now:
public class AnimalsService : IAnimalsService
{
private readonly IAnimalsRepository _animalsRepository;
public AnimalsService(IAnimalsRepository animalsRepository)
{
_animalsRepository = animalsRepository;
}
public IQueryable<Animal> GetFiveLeggedAnimals()
{
...
}
}
The controller would look something like this:
public class AnimalsController : Controller
{
private readonly IAnimalsService _animalsService;
public AnimalsController(IAnimalsService animalsService)
{
_animalsService = animalsService;
}
public ViewResult ListFiveLeggedAnimals()
{
var animals = _animalsService.GetFiveLeggedAnimals();
return View(animals);
}
}
I have basic CRUD logic in the repository (All, Find, UpdateOrInsert, Delete). If I want to use these CRUD methods in my controller:
1) Do I have to create wrapper methods in the service for these respository calls?
2) Would it not make more sense for me to just include the GetFiveLeggedAnimals method and other business logic in the repository?
3) Could I implement the IAnimalsRepository interface in the AnimalsService and then call the base methods (I realise this is possible but I assume its bad practice)?
1) Do I have to create wrapper methods in the service for these respository calls?
Mostly, yes. Typically, you want to offer CRUD for your domain models in the service layer. This way, the controller does not need to work with the repository directly (in fact, it never should). You can add more more sophisticated logic later without having to change external code. For example, consider you wanted to implement a newsfeed. Now every time a five-legged animal is inserted, you want to create a news item and push it to five-legged-animal-fans. Another common example is email notifications.
2) Would it not make more sense for me to just include the GetFiveLeggedAnimals method and other business logic in the repository?
Business logic should be in the Service Layer or in the Domain Model objects themselves, and only there. In fact (see 3), I wouldn't specifically offer an IAnimalRepository at all, if possible.
For instance, in a NoSQL-Environment, the database driver pretty much is a repository. On the other hand, when using a complex ORM mapping and stored procedures (where part of the biz logic is in the DB), you don't really have a choice but offer explicit interfaces that know the stored procedures.
I'd go for a IRepository<T> and use the Query Object pattern, if possible. I think LINQ can also be considered a Query Object / Repository based pattern.
3) Could I implement the IAnimalsRepository interface in the AnimalsService and then call the base methods (I realise this is possible but I assume its bad practice)?
To call the base methods, you'd have to inherit from a concrete implementation, e.g. from ConcreteAnimalsRepository.
Also, if your service implements the IAnimalsRepository interface directly or indirectly, it makes the (unfiltered) CRUD operations available to everyone.
My take: Don't inherit, aggregate. A service layer has a repository, but it isn't a repository itself: The service layer handles all the additional application logic (permissions, notifications) and the repository is a very thin wrapper around the db layer.
As an extreme example, what if deleting something directly was forbidden, and only the service would be allowed to make use of it when inserting a newer revision of sth.? This can be easily built when aggregating.
Repository by definition should be a generic collection-like class that abstracts DB interactions. It would contain typical methods for persistence like Get(object id), Add(T), Remove(T) and possibly implement IQueryable<T>.
The service would look like the following code.
public class AnimalsService : IAnimalsService
{
private readonly IRepository<Animal> _repository;
public AnimalsService(IRepository<Animal> repository)
{
_repository = repository;
}
public IEnumerable<Animal> GetFiveLeggedAnimals()
{
// animal specific business logic
}
}
I think is not good to use simple CRUD operation in the Controller and have a wrapper in the Service class, you should keep all business logic in the service layer, not in controller
for example you want to create a new Animal
in the controller you will have method
look at the example
// not good design
public ActionResult Create(AnimalInput input)
{
Animal animal = new Animal { Name = input.Name}; // set the other propreties
// if you have a CRUD operations in service class you will call
animalService.UpdateOrInsert(animal);
}
// better disign
public ActionResult Create(AnimalInput input)
{
animalService.Create(input.Name);
}
in the service class implementation you should have
follow
public void Create(string name)
{
Animal animal = new Animal { Name = input.Name};
animalRepository.UpdateOrInsert(animal);
}
for the methods like GetAll or GetFiveLeggedAnimals(); you can have wrapper in the service classes I think it's ok . And I want to give you adives allways when you write some code in controller or in Service class keep in mind how you will test this code
and don't forget about SOLID

Categories