N-tier architecture design separation of concerns - n-tier-architecture

I realize there have already been a number of posts on n-tier design and this could possibly be me over thinking things and going round in circles, but I have myself all confused now and would like to get some clarity from the community please.
I am trying to separate a project I created, (and didn't design architecturally very well to start with), out into different layers (each in their own project):
UI
Business Objects
Logic / Business
DAL
The UI should only call the Logic layer to get its stuff
The Business Objects should not call or have references to anything else, just be a way of storing the data
The Logic / BUSINESS layer should hold all of the methods to get, create, update, delete (CRUD) objects in the system and would have references to both the BO and the DAL. It would apply the business logic to the operations then delegate the actual CRUD to the DAL.
The DAL would just do the CRUD operations on the DB. It would have a reference to the BO's as it would return them for the Gets etc.
My question is should the Logic classes only call their equivalent DAL class and just call logic classes instead? In other words, CompanyLogic class should only call CompanyDAL class. So if it wanted to get A Client object by ID it would call ClientLogic.GetClientByID(int) rather than the ClientDAL.GetClientByID(int).
The reason I thought it maybe should stay on the its own layer was that:
It would seem to loosen the coupling between projects
What about the Logic, if getting a client object had some logic validation in it (possibly not the best example, but hope it gets the point across).
EDIT:
I am not sure if it is bad design by me but at the moment the BUSINESS layer has a number of classes including ClientBULL and CompnayBULL, both classes have a call to one another. I use an interface for each class and have a factory to build the objects to try and reduce any coupling but they can not exist without each other now due to calling methods in both classes. Is this a bad idea?

Well, here's my comments on your design:
Logic is a bad name for what essentially is a layer assigned to abstract persistence. I would probably call it "Repository" or "Persistence" or DAO (data access objects) instead of "Logic", which is ambiguous and could absolutely mean anything.
If you really want to decouple your business layer from your DAL, your Logic layer should only accept interfaces to the DAL, and not concrete DAL classes.
There are two schools of thought as to where validation should reside. Some are completely fine with validation sitting at the UI layer; others would rather throw exceptions or pass messages from the business layer. Whichever way you go, just be consistent, don't duplicate validations in multiple places, and you'll be fine.
Go ahead and try coding it would probably be the best piece of advice I could give you. It's well and fine thinking it through, but at one point you'll need to see it while you're coding it and only then will subtle quirks and pitfalls reveal themselves. Whatever prototypes you can come up with will definitely be valuable to the direction your development and design takes you.
Goodluck!
Update
Re your edit: Within the same namespace or assembly, calls to concrete classes are definitely fine. I think it will be overly convoluted for you to need to put up interfaces for business logic -- I mean is there more than one set of rules you should follow?
I'm a believer of keeping things simple and following YAGNI. Don't make an interface until there are more than two classes that are going to implement/already implementing that interface (the DAL is always an exception to this though).

Related

Should I seperate model classes or have them as a single unit?

My game logic model consists of multiple connected classes. There are Board, Cell, Character, etc. Character can be placed (and moved) in Cell (1-1 rel).
There are two approaches:
Make each class of model implement interfaces so that they can be mocked and each class can be tested independently. It forces me to make implementation of each class to not rely on another. But in practice it's hard to avoid Board knowing about Cells too much and Characters knowing how Cell storing mechanism works. I have a Character.Cell and Cell.CurrentCharacter properties. In order for setters to work correctly (not go recursively) they should rely on each others implementation. It feels like the model logic should be considered as a single unit.
Make all public members to return interfaces but use exact classes inside (can involve some downcasting). The cons here are such that I should test the whole model as a single and can't use mocking to test different parts independently. Also there is no sense to use dependency injection inside model, only to get another full model implementation from controller.
So what to do?
UPDATE
You can propose other options.
Why are these the only 2 options?
If you intend to have different versions/types of the classes then interfaces/abstract base classes are a good option to enforce shared behaviour and generalize many operations. However the idea of building the classes independently without knowledge of each other is ridiculous.
It is always a good idea to separate class storage/behaviour to the class/layer it belongs. E.g. no business logic code in the data layer, etc. but the classes need to know about each other in order to function properly. If you make everything independent and based on interfaces you run the risk of over generalizing the application and reducing your efficiency.
Basically if you think you would need to ever downcast the incoming objects to more than one type it's a good idea to look at the design and see if you are gaining anything for the performance loss and nasty casting code you are about to write. If you will be required to handle every type of downcast object you have not gained anything and using polymorphism and a base class is a much better way to go.
Using interfaces does not eliminate your trouble in testing. You will still have to instantiate some version of the objects to test most of the functions on the cell/board anyway. Which for full regression testing will require you test each character's interaction with both.
Don't get me wrong, your character class should most likely have a base class or have an interface. All characters will (I'm sure) share many actions and can benefit from this design. E.g. Moving a character on the board is a fairly generic operation and can be made independent of the character except for a few pieces of information (such as how the character moves, if they are allowed to move, etc.) which should be part of said base class/interface.
When it is reasonable, design classes independently so that they can be tested on their own, but do not use testing as a reason to write bad code. Simple stubs or basic testing instances can be created to help with component testing and takes far less time and effort than fixing unnecessarily complex code.
Interfaces have a purpose, but if you will not be treating 2 classes the same... that is not it.
*Using MVC gives you a leg up on testing as well. If done correctly you should be able to swap out any of the layers to ease your testing of a single layer.

Faking a Method of the Object Under Test

Is there a reason why you shouldn't create a partial fake of an object or just fake one method on the object that you are testing of it for the sake of testing another method? This might be helpful to save you from making an entire new mock object, or when there is an external dependency in the method you are faking which you can't reasonably get rid of and would like to keep out of all the other unit tests?
The objects you want to do this for are trying to do too many things. In particular, if you have an external dependency, you would normally create an object to isolate that dependency. The Façade pattern is one example of this. If your objects weren't designed with testability in mind you may have to do some refactoring. Take a look at Michael Feathers' PDF on working with legacy code(PDF). He also has a book by the same title that goes into much more detail.
It is a very bad idea to mock/fake part of a class to test another.
Doing this, you are not testing what the real code does in the conditions under test leading to unreliable test results.
It also increases the maintenance burden of the faked part of the class. If this is in effect for the whole test program, the fake implementation also makes other tests on the faked method harder.
You need to ask yourself why you need to fake out the part under test.
If it is because the method is accessing a file or database, then you should define an interface and pass an instance of that interface to the class constructor or method. This allows you to test different scenarios in the same test application.
If it is because you are using singletons, you should rethink your design to make it more testable: removing singletons will remove implicit dependencies and maintenance nightmares.
If you are using static methods/free-standing functions to access data in a registry or settings file, you should really move that out of the function under test and pass the data as a parameter or provide a settings provider interface. This will make the code more flexible and robust.
If it is to break a dependency for the purpose of testing (e.g. faking out a vector method to test a method in a matrix class) then you should not be faking that -- you should treat the code under test as what is defined by the class under test by its public interface: methods; pre-conditions, post-conditions, invariants, documentation, parameters and exception specifications.
You can use knowledge of the implementation details to test special edge cases, but trigger those through the main API, not by faking an implementation detail.
For example, suppose you faked std::vector::at() but the implementation switched to use operator[] instead. Your test would break or silently pass.
If the method you want to fake is virtual (as in, not static and not final), then you can subclass your object in your test, override the method in the subclass, and exercise the subclass in the test. No mock-object libraries required.
(Ideally you should consider refactoring, this is not a great long-term solution. But it is a way to get legacy code under test so you can start the refactoring process more easily.)
The Extract and Override technique described in Chapter 3 of Roy Osherove's The Art of Unit Testing does seem to be a way to fake part of the class under test (pp. 71-77). Osherove does not address the concerns raised in some of the other answers to this question.
In addition, Michael Feathers discusses this in Working Effectively with Legacy Code. He terms the resulting class a testing subclass (227) and the technique Subclass and Override Method (401). Now, granted, Feathers is not giving an exposition of pristine techniques that are recommended on new code. But he still gives it serious treatment as a potentially helpful technique.
I also asked my former computer professor about this. He is well-read and currently works full-time in the software industry, where he has advanced rapidly. He said that this technique definitely has a good application, and that there are several dozen classes in the codebase at his company that are under test in this way. He said that, like any technique, it can be overused.
I originally wrote the question when I was new to unit testing and knew next to nothing about dependency injection. Now, after some experience with both, I would add that the need to use this testing technique could be a smell. It may be a sign that need to rework your approach to dependencies. If the method that needs to be faked is one that is inherited from a base class, it may mean that you need to take the adage "favor composition over inheritance" more seriously. You should inject your dependencies rather than inheriting them.
There are some really nice packages for facilitating this kind of stuff. For instance, from the Mockito docs:
//You can mock concrete classes, not only interfaces
LinkedList mockedList = mock(LinkedList.class);
//stubbing
when(mockedList.get(0)).thenReturn("first");
does some real magic that's hard to believe at first. When you call
String firstMember = mockedList.get(0);
you'll get back "first", because of what you said in the "when" statement.

Is that normal Unit testing takes all the behavior out of my classes?

I'm starting a new project and I want to use unit testing.
So I wrote my services classes which are implementing interface and waiting for interface in their parameters so I can easily mock these classes.
My question: there is absolutely no code in my business class! (like Customer)
Is it normal? is it normal even without unit test ? what kind of code would you put in a class like "Customer"?
No, it doesn't sound normal to me - unless you are at the very beginning of your project and Customer is as yet just a skeleton, and you know it will get more functionality over time.
Otherwise it may be a sign of a design issue, such as an anemic domain model.
It is not the unit tests' fault. Unit tests don't in any way enforce one to create dumb classes without real functionality.
I don't know if normal is the right word here, I'd rather say that the situation you have found yourself in is very common.
I see this happen most often with people starting in on Domain Driven Design and also when people use design patterns such as MVVM - all the logic falls into services and controllers and managers (which are themself a smell IMO), and the core domain model becomes a very anaemic set of DTOs.
What I would suggest is returning to your object modelling and looking at your services and seeing where you have removed logic from your Customer object which is actually a core concern of the customer. That is - what does the customer object do? Some of this will belong in external services, but there will also be key processes which are the domain of the customer.
When you design clearly, there might be the case, where some classes are just aggregates of Data. This is part of the MVC Pattern, where the models should not contain much logic. However if you do have absolutely no code in your classes there is something seriously wrong.
To me it sounds, like you are trying some kind of dependency injection, but you are not only injecting the dependencies, but rather everything. This is taking the pattern to far, so it might be becoming it's own anti-pattern.

Types of methods which are hard to unit test?

What unit tests generally tend to be hard to write and why? I am particularly interested in methods which don't need mocking.
Thanks
Two cases where unit testing is made difficult:
Methods that invoke static methods that belong to other classes, particularly when those other classes have static state, or do significant work. Being stuck trying to "unit" test a method that, through transitive closure, does database queries can suck.
Methods that create instances of other classes directly (i.e., via new), particularly when the constructor of the other class does itself requires static state, or when it does significant work in the constructor.
A great A to Z guide of testability concerns with side by side code examples of easy/hard to test code can be found in Misko's extensive testability guide.
Click on the "flaw #x" links (they look like plain text but they're separate links).
Big, complex methods that do lots of things at the same time that really should've been separated. (example: get something from a configuration object, create a URL based on some variables, encode the URL, send a request, do something with the response... you get the drill).
Everything static. Things created with New, although I haven't found a proper way to avoid it without spamming the entire application with factories.
It's almost always about dependencies.
Most code depends on external systems such as databases, file systems, email clients, networks, etc. It's also common to have dependencies on major internal systems (e.g, the spell checking module, or the recalc engine...).
If these dependences are not easily substitutable, then the system becomes hard to test.
Classes that call statics and singletons are the worst offenders, but any class that doesn't accept it's dependencies via constructor or properties will be hard to test.
There are some legitimate situations that are hard to test:
Concurrency
User Interface - this is why the trend is towards MVC architectures that create ViewModels which can be easily tested. The actual rendering is minimized - this is called the humble dialog or humble object pattern in the test literature.

how to avoid returning mocks from a mocked object list

I'm trying out mock/responsibility driven design. I seem to have problems to avoid returning mocks from mocks in the case of objects that need a service to retrieve other objects.
An example could be an object that checks whether the bills from last month are paid. It needs a service that retrieves a list of bills. So I need to mock that billRetrievalService in my tests. At the same time I need that BillRetrievalMock to return mocked Bills (since I don't want my test to rely on the correctness of the Bill implementation).
Is my design flawed? Is there a better way to test this? Or is this the way it will need to be when using finder objects (the finding of the bills in this case)?
side note: althout Bill might be a value object candidate, the wider problem still remains when the collections aren't containing value objects (eg Users).
Most of the time, if I need a mock to return another mock, I find a dependency that makes more sense in the other direction. Stated differently, mock-returning-mock usually points to a violation of the Dependency Inversion Principle.
One common exception: a factory that creates objects (as opposed to a "holder" that simply returns the same object each time). If I need to create multiple objects of the same type during my lifetime, then I might need to depend on an ObjectFactory and invoke #createObject(), then perhaps set expectations on the Objects. Even so, I would question this. It might be possible for something else one level up the call stack to create Objects for me and give them to me as needed.
In the ObjectHolder case, rather than depending on the ObjectHolder to get the Object, I prefer to depend on the Object directly and force my caller to give it to me however it wants. This respects the desirable design property of context independence.
One specific version of this issue is the "Virtual Clock" pattern. Sometimes you need to depend on virtual clock, but often it's better simply to demand a timestamp ("Instantaneous Request" pattern) or, at worst, a stream of timestamps, wherever that comes from. Tests could provide a controled stream of convenient, hardcoded timestamps, but it's also easy to turn the system clock into a stream of timestamps.
Mock returning mocks is a strong code smell - a possible problem with the design. It could be that the Bills should be immutable values objects which should not be mocked. Or there is some confusion with the design and the responsibilities of the classes.
The book Growing Object-Oriented Software, Guided by Tests and paper Mock Roles, not Objects from the inventors of mock objects are worth reading.
As the Way of the Testuvius advices, no principle, however good, should be taken absolutely and so it is also with the rule that you shouldn't need mocks returning mocks, there are cases when this is quite suitable.
As Gutzofter suggests, you could break your object into two, one for the actual validation and another one for retrieval of the bills to validate. The advantage of this "single responsibility only" principle application is that the validator would be more generic and reusable. On the other hand, if you only have this simple use case and no special need for the higher reusability, it's a very pragmatic to keep the retrieval and validation in a single class. Layering, explosion of the number of objects etc. unjustified by a real need and a real benefit, done only for the sake of satisfying an abstract principle, isn't good. You always have to weight the pros and cons and the reality rarely is simple and as beautiful as we would like :-) Great examples of this pragmatic approach are in Adam Bien's Real World Java EE Patterns - Rethinking Best Practices.
Usually when I mock I end up having a triad of objects. The first object would be a coordinator BillsPaidLastMonthCoordinator this object has two dependencies BillRetrievalService and BillPaidValidator.
You would mock the two dependencies and your test would be for the interaction of retrieval and passing bills to the validation. So for this test you will not care what the data is. This helps separate responsibilities. Your original object was responsible for retrieving Bills and then seeing if it was a isPaid Bill.
With the way you described the problem you can end up is a noisy and brittle test. The brittleness comes from it being able to be broken in two ways.
With the corrdinator, it doesn't have to change if Bill implementation changes, Just the objects that actually use a Bill. My 2centavos.
[EDIT]
This is more aligned with using event handlers (the coordinator)