I have a spec translator, like below.
//all specifications implement this base class
public abstract class SpecBase
{
public abstract void Translate(IContext context);
}
//spec translator implementation
public interface ISpecTranslator
{
void Translate(IContext context);
}
I need to inject the dependency of the SpecTranslator constructor. I have two ways to express the depenency.
Solution 1
public class SpecTranslator:ISpecTranslator
{
IList<SpecBase> specs;
public SpecTranslator(IList<SpecBase> specs)
{
this.specs = specs;
}
}
Please note using IList<SpecBase> works for now, but seems solution 2 provides more protection.
Solution 2:
public class SpecTranslator:ISpecTranslator
{
ISpec spec;
public SpecTranslator(ISpec spec)
{
this.spec = spec;
}
}
public interface ISpec
{
IList<SpecBase> specs {get;}
}
However, the implementation of ISpec have the same problem when using constructor dependency injection.
Any idea on pros and cons on these two solutions, or other solutions?
It seems in order to "translate" (analyze) the list of specs, the contents of the ISpec instance given need to be destructured in all cases. A list has to be obtained and seen through. No matter how many layers of abstraction you weave in, the SpecTranslator will finally need a list.
In your case I'd think of ISpec as a factory. If the list is not lazily calculated there is no value in it.
Also, simplicity is an important design principle. As ISpec does not add any capability or architectural freedom it does not carry its own weight.
Related
I am new to TDD and I am using Moq as my mocking framework.
I am trying to check if a method has been called in my class.
The class is not implementing any Interface.
var mockFooSaverService = new Mock<FooSaverService>();
mockFooSaverService.Verify(service => service.Save(mockNewFoo.Object));
to make this work I found here that I have to make the Save() method as a Virtual method.
Question:
What are the consequences of using Virtual keyword for all methods in a class just for the sake of making it testable?
TL;DR
As per the comments, the need for the virtual keyword indicates that your class hierarchy is too tightly coupled, and you should apply SOLID principles to decouple them from eachother. This has the "happy" side effect of making your class hierarchy easier to Unit Test, as dependencies can be mocked via the interface abstraction.
In more Detail
The need make all public methods virtual to allow Moq to override them is frequently indicative of a separation of concerns or class coupling smell.
e.g. this scenario needed virtual methods because class under test has multiple concerns, and there was a need to mock one method and actually invoke another method in the same system under test.
As per #JonSkeet's comment, it is commonplace SOLID best practice to abstract dependencies as interfaces. As it stands, your class under test (May I call it "Controller"?) is dependent on the concrete FooSaverService to save Foos.
By applying the Dependency Inversion Principle, this coupling can be loosened, by abstracting just the externally useful methods, properties and events of FooSaverService to an interface (IFooSaverService), and then
FooSaverService implements IFooSaverService
Controller depends only on IFooSaverService
(Obviously, there are likely other optimizations, e.g. to make the IFooSaverService generic, e.g. ISaverService<Foo> but not in scope here)
Re : Mock<Foo> - it is fairly uncommon to need to Mock simple data storage classes (POCO's, Entities, DTO's etc) - since these will typically retain data stored in them and can be reasoned over directly in unit tests.
To answer your question re implications of Virtual (which is hopefully less relevant now):
You are breaking the (polymorphic) Open and Closed Principle - it is inviting others to override behaviour without deliberately designing for this - there may be unintended consequence.
As per Henk's comment, there will be a small performance impact in administering the virtual method table
A code example
If you put all this together, you'll wind up with a class hierarchy like so:
// Foo is assumed to be an entity / POCO
public class Foo
{
public string Name { get; set; }
public DateTime ExpiryDate { get; set; }
}
// Decouple the Saver Service dependency via an interface
public interface IFooSaverService
{
void Save(Foo aFoo);
}
// Implementation
public class FooSaverService : IFooSaverService
{
public void Save(Foo aFoo)
{
// Persist this via ORM, Web Service, or ADO etc etc.
}
// Other non public methods here are implementation detail and not relevant to consumers
}
// Class consuming the FooSaverService
public class FooController
{
private readonly IFooSaverService _fooSaverService;
// You'll typically use dependency injection here to provide the dependency
public FooController(IFooSaverService fooSaverService)
{
_fooSaverService = fooSaverService;
}
public void PersistTheFoo(Foo fooToBeSaved)
{
if (fooToBeSaved == null) throw new ArgumentNullException("fooToBeSaved");
if (fooToBeSaved.ExpiryDate.Year > 2015)
{
_fooSaverService.Save(fooToBeSaved);
}
}
}
And then you'll be able to test your class which has the IFooSaverService dependency as follows:
[TestFixture]
public class FooControllerTests
{
[Test]
public void PersistingNullFooMustThrow()
{
var systemUnderTest = new FooController(new Mock<IFooSaverService>().Object);
Assert.Throws<ArgumentNullException>(() => systemUnderTest.PersistTheFoo(null));
}
[Test]
public void EnsureOldFoosAreNotSaved()
{
var mockFooSaver = new Mock<IFooSaverService>();
var systemUnderTest = new FooController(mockFooSaver.Object);
systemUnderTest.PersistTheFoo(new Foo{Name = "Old Foo", ExpiryDate = new DateTime(1999,1,1)});
mockFooSaver.Verify(m => m.Save(It.IsAny<Foo>()), Times.Never);
}
[Test]
public void EnsureNewFoosAreSaved()
{
var mockFooSaver = new Mock<IFooSaverService>();
var systemUnderTest = new FooController(mockFooSaver.Object);
systemUnderTest.PersistTheFoo(new Foo { Name = "New Foo", ExpiryDate = new DateTime(2038, 1, 1) });
mockFooSaver.Verify(m => m.Save(It.IsAny<Foo>()), Times.Once);
}
}
TL;DR;
Another good answer is - making classes extendable, and providing virtual methods (i.e. the possibility to extend them) is "feature" of that class. And this feature needs to be supported and tested as any other feature.
Much better explanation can be read on Eric Lippert's blog.
Is this a valid example for decorator pattern?
I would like to know is this example a valid example for decorator pattern? if not what
is correction or change needed here, please suggest.
We have a Container class representing container and for it i want to add features at
run time. features like wheel and lid are used in the example.
Client code:
private void button2_Click(object sender, EventArgs e)
{
IContainer container = new MovableConatiner(new Container());
string features = container.getFeatures();
container = new LidConatiner(container);
features = container.getFeatures();
}
API code:
public interface IContainer
{
string getFeatures();
}
public class Container : IContainer
{
public string getFeatures()
{
return "Container";
}
}
// a decorator to add wheels
public class MovableConatiner : IContainer
{
protected IContainer container;
public MovableConatiner(IContainer container)
{
this.container = container;
}
public string getFeatures()
{
string features = container.getFeatures();
features = features != string.Empty ? string.Format("{0} , four wheels", features) :
features;
return features;
}
}
// a decorator to add lid to contaner
public class LidConatiner : IContainer
{
protected IContainer container;
public LidConatiner(IContainer container)
{
this.container = container;
}
public string getFeatures()
{
string features = container.getFeatures();
features = features != string.Empty ? string.Format("{0} , Lid", features) :
features;
return features;
}
}
its as per my understand so i would like to verify my understanding.
While your implementation doesn't ideally reflects the structure or the Decorator pattern, from my point of view it solves the same problem that Decorator is targeted to solve. Your solution is just not as strict and safe for future modifications as "ideal" Decorator implementation.
You simplified implementation removing "unnecessary" for you abstractions. But while you might think they are unnesessary at the moment, they will become very useful in the future when your application grows and get few dozens of components and decorators. it's easy to get lost who is who currently.
In the link I provided there is very simple description of main participants of the Decorator pattern, and there is a sample code, very similar to yourth, but complete. I won't copy-paste it here to show you corrent implementation.
I just want to stress that if you don't understand the need of some abstractions in Design patterns, you better leave them, or read once more how to use it instead of just removing them.
UPDATE: point in favour of abstractions:
All common logic must be implemented in one place and reused. Code duplication is very-very bad. I think everybody agrees that this is fundamental principle of well-organized code.
Now let's analyze your implementation of Decorator pattern without extracting abstract base class for decorators. Compare the implementation of your MovableContainer and LidContainer classes - do you see anything similar? I hardly see any difference at all actually. Ok, let's find what's common:
both have constructors, receiving component to decorate.
both store reference to IContainer which is decorated
both retrieve component's features in the getFeatures() method
both check component's features for empty and if not - append some string (the only difference is string itself)
All this logic should be extracted to base class. You already should udnerstand that base class for your two decorators is required.
Let's go further. Let's imagine every possible decorator for every possible container. As implies from the Decorator pattern definition, it's obvious that some logic is common for all decorators: they all store reference to the decorating object. Is that enough for extracting base class (single property - that's not hard to copy-paste it to both decorators you have)? Definitely enough!
If you like real-life examples, here it is. You've implemented few decorators, let's say 100 (2 is still enouth, 100 just exadurates the problem). And they you realize that some decelopers doesn't know how to use them properly - they just pass NULLs to your decorators. Their code works fine, then created decorators are passed somewhere else, or stored to DB etc. And then at some magical points, your code is failing in various places later. It's hard to every time find where that NULL came from, which part of application created such object. You decide to add NULL-check in the constructor to disallow passing NULLs and make initial code fail to immediately fix the problem. Ouch, we need to fix all 100 constructors! And merge your changes with changes of 10 more developers who are working everybody on his decorator. That's not a good perspective.
If this example didn't convince you and you are still ready to copy-paste code 100 times, imagine that you are developing a reusable library and other developers from other companies also implement decorators derived from your IContainer. You have no way to fix constructors of their decorators and ensure they won't provide you with invalid object containint NULL internally. On contrary if you had a base class for Decorator, you just needed to fix it - and all implementations both yourth and 3rd party get that functionality. If you think you don't implement a reusable library - consider other developers working in your team as 3rd party - it's always useful and not so different - don't require them to change their code because you need some fix.
Finally I provide the way I would refactor your code (I didn't want to do it at the beginning to let you come to this on your own):
public interface IContainer
{
string getFeatures();
}
public class Container : IContainer
{
public string getFeatures()
{
return "Container";
}
}
public abstract class ContainerDecorator : IContainer
{
protected IContainer container;
protected ContainerDecorator(IContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
this.container = container;
}
public abstract string getFeatures();
}
public class StringFormatDecorator : ContainerDecorator
{
private readonly string _format;
public StringFormatDecorator(IContainer container, string format) : base(container)
{
_format = format;
}
public override string getFeatures()
{
string features = container.getFeatures();
features = features != string.Empty ? string.Format(_format, features) : features;
return features;
}
}
// a decorator to add wheels
public class MovableConatiner : StringFormatDecorator
{
public MovableConatiner(IContainer container) : base(container, "{0} , four wheels")
{
}
}
// a decorator to add lid to contaner
public class LidConatiner : StringFormatDecorator
{
public LidConatiner(IContainer container) : base(container, "{0} , Lid")
{
}
}
Such code not only improves core reuse, but also prevents others from using your decorators in wrong way because of lost border between containers and decorators. It's much harder to declare parameterless decorator now and almost impossible to use it. You can't "decorate" one container with another container which is non-sense, but possible in your implementation when some new developer creates his own container without knowing your initial intentions.
Now doing things wrong becomes much more complex.
I have been looking for Strategy Pattern and I saw This link which the guy has explained this pattern very well.
But as far as I know (maybe right or wrong) you shouldn't make a new class in another class (for the sake of being loosely coupled).
this.motor = new Motor(this)
Is there a better kind of implementation for that to not violate the principles (like IoC)?
It would produce a more maintainable code to define both your strategy and context as interfaces:
interface IStrategy<T> where T : IContext
{
T Context { get; }
void Execute();
}
// this cab have other structures too depending on your common logic
// like being generic
interface IContext
{
}
I, myself prefer constructor injection. But in this case property injection is needed because one may need to change the strategy at run time.
Now you can implement/inject your concrete types.
You can use Constructor Injection.
public class MyClass{
public MyClass(Motor motor){
this.motor = motor;
}
}
Then, it's up to your IOC container to supply the needed dependency.
Sure, there are many possibilities. What about a strategy factory?
this.motor = MotorFactory.newMotor(MotorFactory.BOOST);
or simply a mutator method for injection (assuming IMotor is the abstract interface for motors:)
void setMotor(IMotor m) {
this.motor = m;
}
u can use "dynamic" in c# instead like this:
Method(dynamic input)
Method(DTO1 input) Method(DTO2 input) Method(DTO3 input)
All of our reports are created from object graphs that are translated from our domain objects. To enable this, we have a Translator class for each report, and have been using Dependency Injection for passing in dependencies.
This worked great, and would yield nice classes structured like this:
public class CheckTranslator : ICheckTranslator
{
public CheckTranslator (IEmployeeService empSvc
, IPaycheckService paySvc)
{
_empSvc = empSvc;
_paySvc = paySvc;
}
public Check CreateCheck()
{
//do the translation...
}
}
However, in some cases the mapping has many different grouping options. As a result, the c-tor would turn into a mix of class dependencies and parameters.
public class CheckTranslator : ICheckTranslator
{
public CheckTranslator (IEmployeeService empSvc
, IPaycheckService paySvc
, bool doTranslateStubData
, bool doAttachLogo)
{
_empSvc = empSvc;
_paySvc = paySvc;
_doTranslateStubData = doTranslateStubData;
_doAttachLogo = doAttachLogo;
}
public Check CreateCheck()
{
//do the translation...
}
}
Now, we can still test it, but it no longer really works with an IoC container, at least in a clean fashion. Plus, we can no longer call the CreateCheck twice if the settings are different for each check.
While I recognize it's a problem, I don't necessarily see the right solution. It seems kind of strange to create a Factory for each class ... or is this the best way?
Shot in the dark here, but could you move those parameters to the method instead?
In other words:
public Check CreateCheck(bool doTranslateStubData, bool doAttachLogo)
{
//do the translation...
}
Do those parameters have to be passed in via the constructor?
(Note - if your response to this is "there are too many methods for that to be practical", then part of the problem may be that the abstraction is too coarse).
Another option (it's really hard to say without understanding the domain model and injection patterns) would be to introduce a parameter object that is itself managed by the injector:
public interface ICheckConfiguration
{
bool AttachLogo { get; }
bool TranslateStubData { get; }
}
Then inject this with the constructor:
public CheckTranslator (IEmployeeService empSvc, IPaycheckService paySvc,
ICheckConfiguration config)
{
// etc.
}
This should be enough. You can then create a concrete CheckConfiguration class that takes those two bool properties in its constructor, and configure your container to create different instances of the parameter object (interface) based on a higher-level DI parameter.
The last thing I think I should mention is that just because you're using DI doesn't mean that everything has to be managed by the container. It's not such a bad thing to create CheckTranslator objects in an ad-hoc fashion if there's only one kind of "translator". As long as the translator still depends on abstractions, which it does here, then maybe you shouldn't be injecting it at all, just let higher-level DI-enabled classes create them ad-hoc.
This question is a result of a post by Jeffery Palermo on how to get around branched code and dependency injection http://jeffreypalermo.com/blog/constructor-over-injection-anti-pattern/
In his post, Jeffery has a class (public class OrderProcessor : IOrderProcessor) that takes 2 interfaces on the constructor. One is a validator IOrderValidator and an IOrderShipper interface. His method code branches after only using methods on the IOrderValidator interface and never uses anything on the IOrderShipper interface.
He suggests creating a factory that will call a static method to get the delegate of the interface. He is creating a new object in his refactored code which seems unnecessary.
I guess the crux of the issue is we are using IoC to build all our objects regardless if they're being used or not. If you instantiate an object with 2 interfaces and have code that could branch to not use one of them, how do you handle it?
In this example, we assume _validator.Validate(order) always returns false and the IOrderShipper.Ship() method is never called.
Original Code:
public class OrderProcessor : IOrderProcessor
{
private readonly IOrderValidator _validator;
private readonly IOrderShipper _shipper;
public OrderProcessor(IOrderValidator validator, IOrderShipper shipper)
{
_validator = validator;
_shipper = shipper;
}
public SuccessResult Process(Order order)
{
bool isValid = _validator.Validate(order);
if (isValid)
{
_shipper.Ship(order);
}
return CreateStatus(isValid);
}
private SuccessResult CreateStatus(bool isValid)
{
return isValid ? SuccessResult.Success : SuccessResult.Failed;
}
}
public class OrderShipper : IOrderShipper
{
public OrderShipper()
{
Thread.Sleep(TimeSpan.FromMilliseconds(777));
}
public void Ship(Order order)
{
//ship the order
}
}
Refactored Code
public class OrderProcessor : IOrderProcessor
{
private readonly IOrderValidator _validator;
public OrderProcessor(IOrderValidator validator)
{
_validator = validator;
}
public SuccessResult Process(Order order)
{
bool isValid = _validator.Validate(order);
if (isValid)
{
IOrderShipper shipper = new OrderShipperFactory().GetDefault();
shipper.Ship(order);
}
return CreateStatus(isValid);
}
private SuccessResult CreateStatus(bool isValid)
{
return isValid ? SuccessResult.Success : SuccessResult.Failed;
}
}
public class OrderShipperFactory
{
public static Func<IOrderShipper> CreationClosure;
public IOrderShipper GetDefault()
{
return CreationClosure(); //executes closure
}
}
And here is the method that configures this factory at start-up time (global.asax for ASP.NET):
private static void ConfigureFactories()
{
OrderShipperFactory.CreationClosure =
() => ObjectFactory.GetInstance<IOrderShipper>();
}
I just posted a rebuttal of Jeffrey Palermos post.
In short, we should not let concrete implementation details influence our design. That would be violating the Liskov Substitution Principle on the architectural scale.
A more elegant solution lets us keep the design by introducing a Lazy-loading OrderShipper.
I'm running late for a meeting, but a few quick points...
Sticking to the code branching of using only one dependency, there are two branches to propose:
Applying DDD practices, you would not have an OrderProcessor with a dependency on IOrderValidator. Instead, you'd make the Order() entity be responsible for its own validation. Or, stick to your IOrderValidator, but have its dependency within the OrderShipper() that is implemented - since it will return any error codes.
Ensure the dependencies being injected are constructed using a Singleton approach (and configured as Singleton in the IoC container being used). This resolves any memory concerns.
Like someone else that mentioned here, the point is to break the dependency on concrete classes and loosely couple the dependencies using Dependency Injection with some IoC container in use.
This makes future refactoring and swapping out legacy code far easier on a grand scale by limiting the technical debt incurred in the future. Once you have a project near 500,000 lines of code, with 3000 unit tests, you'll know first hand why IoC is so important.