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

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.

Related

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

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.

Using Entity framework's code first reverse engineering - entity and business classes

After reverse engineering code first, I got entity classes and mapping. Most of the business classes (that I already have) have the same name as entity classes and most of the properties in entity and business classes are the same.
If I understand the implementation right, I should make partial classes with entity classes having all the properties and change the business classes by removing those properties and leaving only the business rules.
If that is correct, what to do about derived classes? Obviously entity classes need all properties from base class. Can I change the code in the entity classes so that the entity classes also inherit from the base classes?
Any thoughts would be welcome.
Perhaps you should remove your business classes. ORM is tool for loading and persisting objects - you don't have special set of objects for persistence and special set of objects for business logic. Use single set which consists of persisted properties and computed properties + business rules executed on persisted properties (store them in partial class). That will form something which is commonly called domain object - it has both data and logic related to its data. You can have separate classes performing logic on multiple domain objects (so the logic doesn't belong to the object itself). These classes are commonly called domain services.
are you saying that most of the properties in entity and business classes are the same ? It shouldn't be like that. Business classes should have only the business logic not the properties of entities. Business class will use entity classes to fulfill the business.
Here is a good example http://code.msdn.microsoft.com/ASPNET-MVC-Application-b01a9fe8/

Does Model Driven Architecture play nice with LINQ-to-SQL or Entity Framework?

My newly created system was created using the Model Driven Architecture approach so all I have is the model (let's say comprehensive 'Order' and 'Product' classes). These are fully tested classes that support the business of my application. Now it's time to persist these classes as objects on the harddrive and at some later time retrieve them in the same state (thinking very abstractly here). Typically I'd create an IOrderRepository interface and eventually a ADO.NET-driven OrderRepository class with methods such as GetAll(), GetById(), Save(), etc... or at some point a BinaryFormatter-driven OrderRepostiroy class that serves a similar purpose through this same common interface.
Is this approach just not conducive to LINQ-To-Sql or the Entity Framework. Something that attempts to build my model from a pre-existing DB structure just seems wrong. Could I take advantage of these technologies but retain this 'MDA' approach to software engineering?
... notice I did not mention that this was a Web App. It may or may not be -- and shouldn't matter.
In general, I think that you should not make types implementing business methods and types used for O/R mapping the same type. I think this violates the single responsibility principle. The point of your entity types is to bridge the gap between relational space and object space. The point of your business types is to have collections of testable behavior. Instead, I would suggest that you project from your entity types onto your business types when materializing objects from the database. Separating these two allows your business methods and data mappings to evolve independently, which is very important, especially if you cannot always control the schema of the database. I explain this idea more fully in this presentation.

When is it OK for an abstract base class to have (non-static) data members?

I guess the question title sums it up. Is there a time when it would be considered good design for an ABC to have data members? I have been wondering if there is a situation where this is OK. The only ones I can come up with all are static, and even then it's kind of a stretch.
I don't see why an ABC couldn't properly have per-instance (aka non-static) data members, as needed to support the methods it supplies to subclasses. Take the common case in which an ABC exists to supply a Template Method DP (the hook methods being abstract) -- if part of the function of the organizing method is to update some instance variables (for example, a count of how many times the method was called), then obviously those variables should also be supplied by the ABC. Can you explain better why you think that's bad design?!
An abstract class can have whatever members it needs to support the functionality it supplies to the classes that inherit from it. That's not to say these would be directly accessible to the subclasses: they might be read and changed only through method calls made by the subclasses or their clients.
I see this in plugin architectures, like Paint.NET's.
Inversion of Control might require this. For example you have a bunch of classes that take an instance of Logger, the abstract class they're based off might have a constructor store it in an member variable or private property (assuming of course you remember to call the base constructor grin)
It is OK, when your data member in your abstract class contains base code for inheriting classes
I would think about using an interface, when the data member is just to describe your class
Yes, its possible to provide member variables in an abstract base class with the intention that its subclasses will use those members to make a concrete implementation.
Here's a concrete example, using a car analogy that we've all come to love.
Let's say we make Car an abstract base class, which has placeholders for wheels, chassis, and an engine for its its subclasses to use:
abstract class Car {
Wheels wheels
Chassis chassis
Engine engine
abstract void accelerate();
abstract void decelerate();
}
Now, for a class that extends Car, the members are already there to use, so the responsibility of a subclass is to populate those member variables:
class NiceCar extends Car {
Decoration decoration;
public NiceCar() {
wheels = new ChromeWheels();
chassis = new LightweightCompositeChassis();
engine = new LotsOfHorsepowerEngine();
decoration = new CoolRacingStripes();
}
void accelerate() {
engine.feedFuel();
}
void decelerate() {
wheels.applyBrakes();
}
}
As can be seen, the abstract base class can work as a blueprint for which components (member variables) should be filled in to get a full functionality of a class. In this case, the Car provides basic parts of a car to be used in a concrete implementation. NiceCar uses those member fields and adds some for its own features, such as a decorative paint job.
I suspect that you are drawing too tight a circle around your concept of an abstract base class.
An abstract base class (as opposed to a pure interface) is a class that intends for some of its functionality to be used by child classes. It will thus have some functionality along with methods that are intended to be over-ridden (the interface part). There is no reason why this functionality should not have member variables associated with it.
Many frameworks are based off of inheritance. These will almost inevitably have abstract classes with member variables. For instance, DirectShow is the multimedia streaming framework in Windows. The sources, encoders, decoders, etc. are all implemented in what are called "filters". There are base classes for various types of filters. Each of them will have member variables for the upstream and downstream filters, the negotiated media types, etc.
As others have mentioned one adds instance fields to any sort of class when one needs to store state. This holds true of abstract or concrete classes - there is no difference.
Why should it make difference ? After all an abstract class is just like anyclass except it can't be instsntiated, requiring subclassing etc to complete the class.
If it's a state used by all inherited classes, I think it's mandatory to move it to the base class. Even though the base is abstract. I think most people that are into refactoring would agree with me on this.
There might be several reasons why some state should be in the base. Reducing code duplication is a good reason enough.

Why do most system architects insist on first programming to an interface?

Almost every Java book I read talks about using the interface as a way to share state and behaviour between objects that when first "constructed" did not seem to share a relationship.
However, whenever I see architects design an application, the first thing they do is start programming to an interface. How come? How do you know all the relationships between objects that will occur within that interface? If you already know those relationships, then why not just extend an abstract class?
Programming to an interface means respecting the "contract" created by using that interface. And so if your IPoweredByMotor interface has a start() method, future classes that implement the interface, be they MotorizedWheelChair, Automobile, or SmoothieMaker, in implementing the methods of that interface, add flexibility to your system, because one piece of code can start the motor of many different types of things, because all that one piece of code needs to know is that they respond to start(). It doesn't matter how they start, just that they must start.
Great question. I'll refer you to Josh Bloch in Effective Java, who writes (item 16) why to prefer the use of interfaces over abstract classes. By the way, if you haven't got this book, I highly recommend it! Here is a summary of what he says:
Existing classes can be easily retrofitted to implement a new interface. All you need to do is implement the interface and add the required methods. Existing classes cannot be retrofitted easily to extend a new abstract class.
Interfaces are ideal for defining mix-ins. A mix-in interface allows classes to declare additional, optional behavior (for example, Comparable). It allows the optional functionality to be mixed in with the primary functionality. Abstract classes cannot define mix-ins -- a class cannot extend more than one parent.
Interfaces allow for non-hierarchical frameworks. If you have a class that has the functionality of many interfaces, it can implement them all. Without interfaces, you would have to create a bloated class hierarchy with a class for every combination of attributes, resulting in combinatorial explosion.
Interfaces enable safe functionality enhancements. You can create wrapper classes using the Decorator pattern, a robust and flexible design. A wrapper class implements and contains the same interface, forwarding some functionality to existing methods, while adding specialized behavior to other methods. You can't do this with abstract methods - you must use inheritance instead, which is more fragile.
What about the advantage of abstract classes providing basic implementation? You can provide an abstract skeletal implementation class with each interface. This combines the virtues of both interfaces and abstract classes. Skeletal implementations provide implementation assistance without imposing the severe constraints that abstract classes force when they serve as type definitions. For example, the Collections Framework defines the type using interfaces, and provides a skeletal implementation for each one.
Programming to interfaces provides several benefits:
Required for GoF type patterns, such as the visitor pattern
Allows for alternate implementations. For example, multiple data access object implementations may exist for a single interface that abstracts the database engine in use (AccountDaoMySQL and AccountDaoOracle may both implement AccountDao)
A Class may implement multiple interfaces. Java does not allow multiple inheritance of concrete classes.
Abstracts implementation details. Interfaces may include only public API methods, hiding implementation details. Benefits include a cleanly documented public API and well documented contracts.
Used heavily by modern dependency injection frameworks, such as http://www.springframework.org/.
In Java, interfaces can be used to create dynamic proxies - http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/Proxy.html. This can be used very effectively with frameworks such as Spring to perform Aspect Oriented Programming. Aspects can add very useful functionality to Classes without directly adding java code to those classes. Examples of this functionality include logging, auditing, performance monitoring, transaction demarcation, etc. http://static.springframework.org/spring/docs/2.5.x/reference/aop.html.
Mock implementations, unit testing - When dependent classes are implementations of interfaces, mock classes can be written that also implement those interfaces. The mock classes can be used to facilitate unit testing.
I think one of the reasons abstract classes have largely been abandoned by developers might be a misunderstanding.
When the Gang of Four wrote:
Program to an interface not an implementation.
there was no such thing as a java or C# interface. They were talking about the object-oriented interface concept, that every class has. Erich Gamma mentions it in this interview.
I think following all the rules and principles mechanically without thinking leads to a difficult to read, navigate, understand and maintain code-base. Remember: The simplest thing that could possibly work.
How come?
Because that's what all the books say. Like the GoF patterns, many people see it as universally good and don't ever think about whether or not it is really the right design.
How do you know all the relationships between objects that will occur within that interface?
You don't, and that's a problem.
If
you already know those relationships,
then why not just extend an abstract
class?
Reasons to not extend an abstract class:
You have radically different implementations and making a decent base class is too hard.
You need to burn your one and only base class for something else.
If neither apply, go ahead and use an abstract class. It will save you a lot of time.
Questions you didn't ask:
What are the down-sides of using an interface?
You cannot change them. Unlike an abstract class, an interface is set in stone. Once you have one in use, extending it will break code, period.
Do I really need either?
Most of the time, no. Think really hard before you build any object hierarchy. A big problem in languages like Java is that it makes it way too easy to create massive, complicated object hierarchies.
Consider the classic example LameDuck inherits from Duck. Sounds easy, doesn't it?
Well, that is until you need to indicate that the duck has been injured and is now lame. Or indicate that the lame duck has been healed and can walk again. Java does not allow you to change an objects type, so using sub-types to indicate lameness doesn't actually work.
Programming to an interface means respecting the "contract" created by
using that interface
This is the single most misunderstood thing about interfaces.
There is no way to enforce any such contract with interfaces. Interfaces, by definition, cannot specify any behaviour at all. Classes are where behaviour happens.
This mistaken belief is so widespread as to be considered the conventional wisdom by many people. It is, however, wrong.
So this statement in the OP
Almost every Java book I read talks about using the interface as a way
to share state and behavior between objects
is just not possible. Interfaces have neither state nor behaviour. They can define properties, that implementing classes must provide, but that's as close as they can get. You cannot share behaviour using interfaces.
You can make an assumption that people will implement an interface to provide the sort of behaviour implied by the name of its methods, but that's not anything like the same thing. And it places no restrictions at all on when such methods are called (eg that Start should be called before Stop).
This statement
Required for GoF type patterns, such as the visitor pattern
is also incorrect. The GoF book uses exactly zero interfaces, as they were not a feature of the languages used at the time. None of the patterns require interfaces, although some can use them. IMO, the Observer pattern is one in which interfaces can play a more elegant role (although the pattern is normally implemented using events nowadays). In the Visitor pattern it is almost always the case that a base Visitor class implementing default behaviour for each type of visited node is required, IME.
Personally, I think the answer to the question is threefold:
Interfaces are seen by many as a silver bullet (these people usually labour under the "contract" misapprehension, or think that interfaces magically decouple their code)
Java people are very focussed on using frameworks, many of which (rightly) require classes to implement their interfaces
Interfaces were the best way to do some things before generics and annotations (attributes in C#) were introduced.
Interfaces are a very useful language feature, but are much abused. Symptoms include:
An interface is only implemented by one class
A class implements multiple interfaces. Often touted as an advantage of interfaces, usually it means that the class in question is violating the principle of separation of concerns.
There is an inheritance hierarchy of interfaces (often mirrored by a hierarchy of classes). This is the situation you're trying to avoid by using interfaces in the first place. Too much inheritance is a bad thing, both for classes and interfaces.
All these things are code smells, IMO.
It's one way to promote loose coupling.
With low coupling, a change in one module will not require a change in the implementation of another module.
A good use of this concept is Abstract Factory pattern. In the Wikipedia example, GUIFactory interface produces Button interface. The concrete factory may be WinFactory (producing WinButton), or OSXFactory (producing OSXButton). Imagine if you are writing a GUI application and you have to go look around all instances of OldButton class and changing them to WinButton. Then next year, you need to add OSXButton version.
In my opinion, you see this so often because it is a very good practice that is often applied in the wrong situations.
There are many advantages to interfaces relative to abstract classes:
You can switch implementations w/o re-building code that depends on the interface. This is useful for: proxy classes, dependency injection, AOP, etc.
You can separate the API from the implementation in your code. This can be nice because it makes it obvious when you're changing code that will affect other modules.
It allows developers writing code that is dependent on your code to easily mock your API for testing purposes.
You gain the most advantage from interfaces when dealing with modules of code. However, there is no easy rule to determine where module boundaries should be. So this best practice is easy to over-use, especially when first designing some software.
I would assume (with #eed3s9n) that it's to promote loose coupling. Also, without interfaces unit testing becomes much more difficult, as you can't mock up your objects.
Why extends is evil. This article is pretty much a direct answer to the question asked. I can think of almost no case where you would actually need an abstract class, and plenty of situations where it is a bad idea. This does not mean that implementations using abstract classes are bad, but you will have to take care so you do not make the interface contract dependent on artifacts of some specific implementation (case in point: the Stack class in Java).
One more thing: it is not necessary, or good practice, to have interfaces everywhere. Typically, you should identify when you need an interface and when you do not. In an ideal world, the second case should be implemented as a final class most of the time.
There are some excellent answers here, but if you're looking for a concrete reason, look no further than Unit Testing.
Consider that you want to test a method in the business logic that retrieves the current tax rate for the region where a transaction occurrs. To do this, the business logic class has to talk to the database via a Repository:
interface IRepository<T> { T Get(string key); }
class TaxRateRepository : IRepository<TaxRate> {
protected internal TaxRateRepository() {}
public TaxRate Get(string key) {
// retrieve an TaxRate (obj) from database
return obj; }
}
Throughout the code, use the type IRepository instead of TaxRateRepository.
The repository has a non-public constructor to encourage users (developers) to use the factory to instantiate the repository:
public static class RepositoryFactory {
public RepositoryFactory() {
TaxRateRepository = new TaxRateRepository(); }
public static IRepository TaxRateRepository { get; protected set; }
public static void SetTaxRateRepository(IRepository rep) {
TaxRateRepository = rep; }
}
The factory is the only place where the TaxRateRepository class is referenced directly.
So you need some supporting classes for this example:
class TaxRate {
public string Region { get; protected set; }
decimal Rate { get; protected set; }
}
static class Business {
static decimal GetRate(string region) {
var taxRate = RepositoryFactory.TaxRateRepository.Get(region);
return taxRate.Rate; }
}
And there is also another other implementation of IRepository - the mock up:
class MockTaxRateRepository : IRepository<TaxRate> {
public TaxRate ReturnValue { get; set; }
public bool GetWasCalled { get; protected set; }
public string KeyParamValue { get; protected set; }
public TaxRate Get(string key) {
GetWasCalled = true;
KeyParamValue = key;
return ReturnValue; }
}
Because the live code (Business Class) uses a Factory to get the Repository, in the unit test you plug in the MockRepository for the TaxRateRepository. Once the substitution is made, you can hard code the return value and make the database unneccessary.
class MyUnitTestFixture {
var rep = new MockTaxRateRepository();
[FixtureSetup]
void ConfigureFixture() {
RepositoryFactory.SetTaxRateRepository(rep); }
[Test]
void Test() {
var region = "NY.NY.Manhattan";
var rate = 8.5m;
rep.ReturnValue = new TaxRate { Rate = rate };
var r = Business.GetRate(region);
Assert.IsNotNull(r);
Assert.IsTrue(rep.GetWasCalled);
Assert.AreEqual(region, rep.KeyParamValue);
Assert.AreEqual(r.Rate, rate); }
}
Remember, you want to test the business logic method only, not the repository, database, connection string, etc... There are different tests for each of those. By doing it this way, you can completely isolate the code that you are testing.
A side benefit is that you can also run the unit test without a database connection, which makes it faster, more portable (think multi-developer team in remote locations).
Another side benefit is that you can use the Test-Driven Development (TDD) process for the implementation phase of development. I don't strictly use TDD but a mix of TDD and old-school coding.
In one sense, I think your question boils down to simply, "why use interfaces and not abstract classes?" Technically, you can achieve loose coupling with both -- the underlying implementation is still not exposed to the calling code, and you can use Abstract Factory pattern to return an underlying implementation (interface implementation vs. abstract class extension) to increase the flexibility of your design. In fact, you could argue that abstract classes give you slightly more, since they allow you to both require implementations to satisfy your code ("you MUST implement start()") and provide default implementations ("I have a standard paint() you can override if you want to") -- with interfaces, implementations must be provided, which over time can lead to brittle inheritance problems through interface changes.
Fundamentally, though, I use interfaces mainly due to Java's single inheritance restriction. If my implementation MUST inherit from an abstract class to be used by calling code, that means I lose the flexibility to inherit from something else even though that may make more sense (e.g. for code reuse or object hierarchy).
One reason is that interfaces allow for growth and extensibility. Say, for example, that you have a method that takes an object as a parameter,
public void drink(coffee someDrink)
{
}
Now let's say you want to use the exact same method, but pass a hotTea object. Well, you can't. You just hard-coded that above method to only use coffee objects. Maybe that's good, maybe that's bad. The downside of the above is that it strictly locks you in with one type of object when you'd like to pass all sorts of related objects.
By using an interface, say IHotDrink,
interface IHotDrink { }
and rewrting your above method to use the interface instead of the object,
public void drink(IHotDrink someDrink)
{
}
Now you can pass all objects that implement the IHotDrink interface. Sure, you can write the exact same method that does the exact same thing with a different object parameter, but why? You're suddenly maintaining bloated code.
Its all about designing before coding.
If you dont know all the relationships between two objects after you have specified the interface then you have done a poor job of defining the interface -- which is relatively easy to fix.
If you had dived straight into coding and realised half way through you are missing something its a lot harder to fix.
You could see this from a perl/python/ruby perspective :
when you pass an object as a parameter to a method you don't pass it's type , you just know that it must respond to some methods
I think considering java interfaces as an analogy to that would best explain this . You don't really pass a type , you just pass something that responds to a method ( a trait , if you will ).
I think the main reason to use interfaces in Java is the limitation to single inheritance. In many cases this lead to unnecessary complication and code duplication. Take a look at Traits in Scala: http://www.scala-lang.org/node/126 Traits are a special kind of abstract classes, but a class can extend many of them.