Inherit or wrap a class that deals with concurrency - c#

In trying to provide a unit-testable (using Moq) abstraction of ConcurrentQueue<T> I am debating whether I lose the benefits of using the framework's ConcurrentQueue<T> implementation depending on how I author the abstraction.
What are the implications of doing one or the other in the following code listing:
public abstract class MyMessageQueue1<T> : ConcurrentQueue<T>
{
public new virtual void Enqueue(T item)
{
base.Enqueue(item);
}
}
public class MyMessageQueue2<T>
{
private readonly ConcurrentQueue<T> _concurrentQueue =
new ConcurrentQueue<T>();
public virtual void Enqueue(T item)
{
_concurrentQueue.Enqueue(item);
}
}
In the first implementation (MyMessageQueue1), I hide any of the base class methods as to provide my implementation before passing the call to the base class.
In the second implementation, I wrap the ConcurrentQueue<T>inside and pass calls to it when I need to.
Does MyMessageQueue2 have to manually handle concurrency or does it not matter as all calls are passed to the wrapped ConcurrentQueue<T>.

You don't have to handle concurrency in either case because all you do is just delegating calls to the ConcurrentQueue as has been stated by #nanda. However, it would help us to know your reason to wrap this class. It is fairly unit-testing friendly in the sense that it doesn't use any external resources like files or a database. When being used in your classes you can just leave it doing its job and rather testing your own functionality that uses the ConcurrentQueue.
If you are trying to wrap it because you would like to verify whether your methods use it in desired way, you are probably focusing on testing of implementation of your method rather than the method's behaviour. Which might be useful in certain scenarios but you have to be aware of that fact and it is not a common practise.
There is one thing that you are losing when writing wrappers like these. Because wrappers have virtual methods so that they can be mocked, methods can't be inlined and a bit of performance is lost. ConcurrentQueue is slim and fast class and this might actually be an issue.

If all the wrapper does is delegation to ConcurrentQueue, and the wrapper does not have it's own members to protect for concurrent access then there is nothing to be done for concurrency for your wrapper.
But what would you be unit testing on this thin wrapper?

Related

dependecy injection and unit testing - static helper methods or private instance methods

From unit testing and dependency injection point of view, what's the usual adopted norm when it comes to helper methods?
Here is my example situation:
public class GoodiesController : Controller
{
private IMyContext _context;
public GoodiesController(IMyContext context)
{
_context = context
}
public async Task<IAction> GetThoseGoodies()
{
if(YouLikeThemThisWay(Request.Path))
{
var result = await _context.GoGetThemThisWay()
} else { }
}
My question is am I better off with YouLikeThemThisWay(string path) as a static helper in some class or as a private instance method? Assuming I might have a couple of the likes of YouLikeThemThisWay?
It really depends on what your YouLikeThemThisWay(string path) method does. My rules for using a static method or as follows:
Does it require a non-primitive dependency? If so, don't use static.
Does it affect the state of the application? If so, don't use static.
Does it extend the functionality of a class or type you do not have access to internally (IE BCL classes or primatives)? If so use a static extension!
Will it impact unit tests--as in make them more difficult--if I cannot mock the routine? If no, then make it static!
Will it be used by more than one type or class? If so that it makes it a better candidate for static!
Does the routine perform some sort of IO, like calling a database or the filesystem? If so, I would not make it static.
Basically, small helper functions that are easily tested and don't affect state or usually OK to make static. If there is state involved, the routine requires a dependency that you would normally inject, or the routine is making IO or IPC calls then do not make it static.
One caveat to the dependency issue is technically you could use method injection to handle the dependencies, but I like to keep it simple. Your method is probably OK to be static.
Reuse is a big factor in statics too. If the routine will only be used in one class, it may be pointless to make static. Most of my static methods live in helper classes that are easily accessed anywhere.
EDIT: Note that I usually require most or all of those five rules to favor statics in order for me to even consider making something static.

Is it possible to restrict set/reset of EventWaitHandle?

I would like to have EventWaitHandle object (eg. ManualResetEvent) that can be set/reset from only one place but that can be waited for (with WaitOne()) from multiple places. Put it differently, I want to have just one class that can set/reset it while all other classes to be able to call WaitOne() on it. It's kind of like regular "read-only" property:
private string MyReadOnlyText {get; private set;}
only for specific methods in ManualResetEvent. But not the:
private ManualResetEvent MyEvent {get; private set;}
Of course, this won't work because, while only owner class can instantiate this property, any other external object is able to change it with MyEvent.Set/MyEvent.Reset().
Is something like this even possible? The purpose of this is to prevent arbitrary objects in the application to manipulate the wait handle state and to be sure that this can be done just from the single place.
To some extent, this seems like something that can be addressed by convention, i.e. just stipulate that the handle should be considered "read-only" by consumers. A simple grep through the source code should help ensure against miscreants.
There is limited support for the concept of a "real-only" event, if you expose the object only as a WaitHandle. WaitHandle instances don't have a Set() method, so that helps remind callers to not mess with it.
Of course, callers can still cast it to its actual type, and there are static methods in the WaitHandle that still allow manipulation. So it's not like this is 100% assurance. But it would help (and provide for more distinctive patterns to grep for when you do your code audit).
Finally, the "wrapper" approach mentioned in the comments can work as well. This is the most robust, and is a relatively common pattern for any kind of this sort of "restrict access to members except the owner object".
If the callers are in a different assembly as the privileged code, then the easiest way to do this is to make the hidden stuff "internal" and the public stuff "public. If they are in the same assembly, then if you can put the hidden members in the same class with the privileged code, then of course they can just be private to that class.
Often though, you want to encapsulate the special-accessibility object as a separate class while still granting privileged access to one specific class and limiting access by everyone else. In this case, you can use nested classes to achieve this separation, with the outer class containing the privileged code, and the nested class(es) containing the hidden code.
One version of this approach uses a base/sub-class design, where the base class has the public members and the sub-class has the hidden code:
class A
{
public class B
{
protected ManualResetEvent _event = new ManualResetEvent(false);
public void Wait() { _event.Wait(); }
}
private class C : B
{
public void Set() { _event.Set(); }
}
public B GetAnInstanceofB() { return new C(); }
private void DoSomethingWithB(B b) { ((C)b).Set(); }
}
Now callers can call the B.Wait() on the instance returned, but they can't cast to the type C to access the Set() method. But note that the code in class A is permitted to (because it can cast the type to C).
Note that the class B does not itself need to be nested. Just C.
Another variation on this theme is to declare an interface containing only the public methods, and then have the single implementer of the interface. Again, the implementing class will be nested private to the privileged code, while the interface can be nested or not.
Finally note that all of this is a matter of code reliability and maintenance. It is always of course possible for code to use reflection to inspect and access any part of any type it wants.
At the end of the day, you have to think about the audience of the code. If it's a small team and the code is all completely self-contained to a single project, it's probably sufficient to just tell everyone "you can wait on this, but don't muck with this event". In a larger environment, maybe several teams all working on several related projects together but still basically a self-contained unit, using WaitHandle might be sufficient. If you're writing a library for which you intend broad usage, encapsulation and private members and classes is an excellent tool. :)

Static Classes & Class design

While designing my data access layer, I wanted to make all my classes Static so that no object instantiation is required and all members of the class can be access using the class name.
Is this a good approach. If yes then why do we need to have a instance class type at all. Would it have an impact on the performance of the application where n clients want to access my DAL and then might cause a problem with managing the request(s) because no object is created at all?
I understand that static classes cannot be instantiated, and should be used for something like Logging, Utility methods etc, because all objects need to behave in a similar way, Is it valid/safe to assume that all DAL classes does behave the same way (have the same functionality) and hence make them static rather than instantiating it.
Please advice.
Either the type conceptually represents operations that are tied to instances, or it doesn't. Performance is not a consideration here.
If your methods have no state, or their state is designed to be shared between all invocations of the method throughout the application, then the method should be static. If there needs to be separate state shared between members but not shared with the entirety of the application then they need to be non-static. The type will generally require one or the other based on what it conceptually represents. It's not an actual choice.
Static classes are generally best avoided as they introduce tight coupling into your code. They make unit testing much harder because the calls are "hard wired" and can't be easily stubbed out.
Much better would be to make them instances, but only instantiate a single instance. If you couple this with dependency injection (i.e. passing the DAL object into the classes that need it) then you get looser coupling and can pass in a stub version for unit tests - look up Unity or Castle Windsor or other IoC frameworks to see how this works.
There is an impact on performace - static method calls are faster than instance method calls, especially if you address late binding. But that's also the big advantage of object-oriented programming.
If you just use static classes and therefore static method calls, you do not have the ability to 'exchange objects' - and that is, in my opinion, the most important part of object-oriented programming. Have a look at the SOLID principles of Object-Oriented Design and you'll learn about the real benefits of this programming style. Of course this might come with a performance penalty, but usually you won't have to think about it, except if you want to program e.g. real-time applications. Correct usage of OOP and OOD makes your code extremely flexible and (somewhat) easy to understand.
A useful design pattern for this is a variation of a singleton. Set up your static implementatation, leaving the static methods private, exposing them via an object instance, like this:
class MySingletonClass
{
//-----------------------------------------
// here, we hide the static implementations
//-----------------------------------------
private static int privateFoo()
{
/* do something useful here */
}
private static string privateBar()
{
/* do something useful here */
}
//---------------------------------------
// and expose them via an object instance
//---------------------------------------
public int Foo()
{
return privateFoo() ;
}
public string Bar()
{
return privateBar() ;
}
}
Your static class now has the same semantics as an ordinary object instance. Static methods are invoked thus:
SomeStaticClass.SomeStaticMethod() ;
while non-static classes are references thus:
SomeNonStaticClass instance = new SomeNonStaticClass() ;
instance.SomeNonStaticMethod() ;
By exposing the [private] static methods via instance methods, you have hidden the
implementation from the object's users. Down the line, then, when you realize that
your static methods won't work any more (for whatever reason) and the class has to
become non-static, all you have to do is modify the internal implementation of the class.
If your class's users were directly referencing the static methods, you would have to change
every reference in your code base.

when should i create a private method in c#

Since following DI and TDD, I'm bit confused as to when should I create a private method. Could you please tell me what should be the rules of thumb to be considered while making a method private keeping testability and Dependency injection in mind?
I believe an example might help here:
Assume I have an interface with 3 methods like the following:
public interface IWordFrequencyAnalyzer
{
int CalculateHighestFrequency(string forText);
int CalculateFrequencyForWord(string text, string word);
IList<IWordFrequency> CalculateMostFrequentNWords(
string text, int n);
}
Now, I can write a class which can implement a private method which takes a string and can compute the frequency of words in it, and later in each public method I can do a manipulation according to it's requirement.In this case I'll be able to test the contract.
OR
I can extract that private method into a seperate class say something like WordProcessor which implements IWordProcessor, with a single public method which splits the sentence into words and pass it as dependency to the implementation of IWordFrequencyAnalyzer. This way the implementation of splitting the words is testable as well.
Which approach will you suggest?
Thanks,
-Mike
Since getting more into DI and TDD I ended up using private methods less and less, but the reason was not because I needed them to be public for tests. It's more because, as a by-product of using DI, I'm learning more about applying the SOLID principles to my code and this (in turn) is leading me to write classes with less methods overall and almost none private.
So, let's say you have a piece of your code you're using throughout various methods of your class. You know about DRY and you refactor it out to a private method and all's good. Except that often you realize you can generalize what that private method does and inject that functionality as an external dependency of the class: this way, you can test it and mock it, sure, but above all you can reuse what that method does even in other classes or other projects if needs be. Moving it out of the original class is an application of the single responsibility principle.
As I said this change in the way I code is not directly depending on the fact I use TDD or DI, but it's a by-product of the principles TDD encourages me to enforce and of the convenience that DI containers provide in composing the many small classes that result from this approach.
EDIT: The second approach in the example you added to your question is a good example of what I was talking about. The fact your new WordProcessor class is now testable is a plus, but the fact it's now composable and reusable is the real benefit.
Your methods should be private unless they need to be public for your application, not your test.
Generally you shouldn't make things public just to support unit testing (internal might help there). And in that case, you should generally still be testing public interfaces, not private details of the class, which are much more likely to change and break your test.
If you have access to a copy, Roy Osherove's "The Art Of Unit Testing" addresses this issue pretty well
You specific methods as private when they are only used internally by the object, normally called from other methods, some of which will be public or protected. You are more likely to create private methods as a result of following the DRY (Don't Repeat Yourself) principles. In that scenario you'd extract some common code used by several methods into a private method called by those methods.
Making every method of a class public and write a unit test for every method on such class will create a maintenance nightmare quickly, because you will have to change your tests for every little refactoring in your production code. You want to test the behavior of the class itself and for this you don't need every method to be public.
You should keep your methods private always when it is possible. Don't change them to public only for unit tests. When you see that it is hard to test it then consider to change a little bit architecture of your class. From my experience usually when I needed to test private method the class had wrong responsibilities so I changed it.
The Single Responsibility Policy will help you in this matter. Consider this example:
internal class Boss
{
private bool _notEnoughStaff;
private IList<Employee> _staff;
public Boss(bool notEnoughStaff)
{
_notEnoughStaff = notEnoughStaff;
}
public void GiveOrders()
{
if (_notEnoughStaff)
HireStaff();
foreach (Employee employee in _staff)
{
employee.DoWork();
}
}
private void HireStaff()
{
_staff.Add(new Employee());
}
}
public class Employee
{
public void DoWork()
{
}
}
In this case I see not one but two responsibilities: The Boss delegates work AND hire new staff. In this example, I would always extract the private method HireStaff to a new class (let's call it HR), and inject this into the Boss class.
This is a very simplified example, but as you get more and more experienced in the TDD way of thinking, you will find that not many private methods have legitimacy.
Regards,
Morten

Good Case For Interfaces

I work at a company where some require justification for the use of an Interface in our code (Visual Studio C# 3.5).
I would like to ask for an Iron Clad reasoning that interfaces are required for. (My goal is to PROVE that interfaces are a normal part of programming.)
I don't need convincing, I just need a good argument to use in the convincing of others.
The kind of argument I am looking for is fact based, not comparison based (ie "because the .NET library uses them" is comparison based.)
The argument against them is thus: If a class is properly setup (with its public and private members) then an interface is just extra overhead because those that use the class are restricted to public members. If you need to have an interface that is implemented by more than 1 class then just setup inheritance/polymorphism.
Code decoupling. By programming to interfaces you decouple the code using the interface from the code implementing the interface. This allows you to change the implementation without having to refactor all of the code using it. This works in conjunction with inheritance/polymorphism, allowing you to use any of a number of possible implementations interchangeably.
Mocking and unit testing. Mocking frameworks are most easily used when the methods are virtual, which you get by default with interfaces. This is actually the biggest reason why I create interfaces.
Defining behavior that may apply to many different classes that allows them to be used interchangeably, even when there isn't a relationship (other than the defined behavior) between the classes. For example, a Horse and a Bicycle class may both have a Ride method. You can define an interface IRideable that defines the Ride behavior and any class that uses this behavior can use either a Horse or Bicycle object without forcing an unnatural inheritance between them.
The argument against them is thus: If
a class is properly setup (with its
public and private members) then an
interface is just extra overhead
because those that use the class are
restricted to public members. If you
need to have an interface that is
implemented by more than 1 class then
just setup inheritance/polymorphism.
Consider the following code:
interface ICrushable
{
void Crush();
}
public class Vehicle
{
}
public class Animal
{
}
public class Car : Vehicle, ICrushable
{
public void Crush()
{
Console.WriteLine( "Crrrrrassssh" );
}
}
public class Gorilla : Animal, ICrushable
{
public void Crush()
{
Console.WriteLine( "Sqqqquuuuish" );
}
}
Does it make any sense at all to establish a class hierarchy that relates Animals to Vehicles even though both can be crushed by my giant crushing machine? No.
In addition to things explained in other answers, interfaces allow you simulate multiple inheritance in .NET which otherwise is not allowed.
Alas as someone said
Technology is dominated by two types of people: those who understand what they do not manage, and those who manage what they do not understand.
To enable unit testing of the class.
To track dependencies efficiently (if the interface isn't checked out and touched, only the semantics of the class can possibly have changed).
Because there is no runtime overhead.
To enable dependency injection.
...and perhaps because it's friggin' 2009, not the 70's, and modern language designers actually have a clue about what they are doing?
Not that interfaces should be thrown at every class interface: just those which are central to the system, and which are likely to experience significant change and/or extension.
Interfaces and abstract classes model different things. You derive from a class when you have an isA relationship so the base class models something concrete. You implement an interface when your class can perform a specific set of tasks.
Think of something that's Serializable, it doesn't really make sense (from a design/modelling point of view) to have a base class called Serializable as it doesn't make sense to say something isA Serializable. Having something implement a Serializable interface makes more sense as saying 'this is something the class can do, not what the class is'
Interfaces are not 'required for' at all, it's a design decision. I think you need to convince yourself, why, on a case-by-case basis, it is beneficial to use an interface, because there IS an overhead in adding an interface. On the other hand, to counter the argument against interfaces because you can 'simply' use inheritance: inheritance has its draw backs, one of them is that - at least in C# and Java - you can only use inheritance once(single inheritance); but the second - and maybe more important - is that, inheritance requires you to understand the workings of not only the parent class, but all of the ancestor classes, which makes extension harder but also more brittle, because a change in the parent class' implementation could easily break the subclasses. This is the crux of the "composition over inheritance" argument that the GOF book taught us.
You've been given a set of guidelines that your bosses have thought appropriate for your workplace and problem domain. So to be persuasive about changing those guidelines, it's not about proving that interfaces are a good thing in general, it's about proving that you need them in your workplace.
How do you prove that you need interfaces in the code you write in your workplace? By finding a place in your actual codebase (not in some code from somebody else's product, and certainly not in some toy example about Duck implementing the makeNoise method in IAnimal) where an interface-based solution is better than an inheritance-based solution. Show your bosses the problem you're facing, and ask whether it makes sense to modify the guidelines to accommodate situations like that. It's a teachable moment where everyone is looking at the same facts instead of hitting each other over the head with generalities and speculations.
The guideline seems to be driven by a concern about avoiding overengineering and premature generalisation. So if you make an argument along the lines of we should have an interface here just in case in future we have to..., it's well-intentioned, but for your bosses it sets off the same over-engineering alarm bells that motivated the guideline in the first place.
Wait until there's a good objective case for it, that goes both for the programming techniques you use in production code and for the things you start arguments with your managers about.
Test Driven Development
Unit Testing
Without interfaces producing decoupled code would be a pain. Best practice is to code against an interface rather than a concrete implementation. Interfaces seem rubbish at first but once you discover the benefits you'll always use them.
You can implement multiple interfaces. You cannot inherit from multiple classes.
..that's it. The points others are making about code decoupling and test-driven development don't get to the crux of the matter because you can do those things with abstract classes too.
Interfaces allow you to declare a concept that can be shared amongst many types (IEnumerable) while allowing each of those types to have its own inheritance hierarchy.
In this case, what we're saying is "this thing can be enumerated, but that is not its single defining characteristic".
Interfaces allow you to make the minimum amount of decisions necessary when defining the capabilities of the implementer. When you create a class instead of an interface, you have already declared that your concept is class-only and not usable for structs. You also make other decisions when declaring members in a class, such as visibility and virtuality.
For example, you can make an abstract class with all public abstract members, and that is pretty close to an interface, but you have declared that concept as overridable in all child classes, whereas you wouldn't have to have made that decision if you used an interface.
They also make unit testing easier, but I don't believe that is a strong argument, since you can build a system without unit tests (not recommended).
If your shop is performing automated testing, interfaces are a great boon to dependency injection and being able to test a unit of software in isolation.
The problem with the inheritance argument is that you'll either have a gigantic god class or a hierarchy so deep, it'll make your head spin. On top of that, you'll end up with methods on a class you don't need or don't make any sense.
I see a lot of "no multiple inheritance" and while that's true, it probably won't phase your team because you can have multiple levels of inheritance to get what they'd want.
An IDisposable implementation comes to mind. Your team would put a Dispose method on the Object class and let it propagate through the system whether or not it made sense for an object or not.
An interface declares a contract that any object implementing it will adhere to. This makes ensuring quality in code so much easier than trying to enforce written (not code) or verbal structure, the moment a class is decorated with the interface reference the requirements/contract is clear and the code won't compile till you've implemented that interface completely and type-safe.
There are many other great reasons for using Interfaces (listed here) but probably don't resonate with management quite as well as a good, old-fashioned 'quality' statement ;)
Well, my 1st reaction is that if you've to explain why you need interfaces, it's a uphill battle anyways :)
that being said, other than all the reasons mentioned above, interfaces are the only way for loosely coupled programming, n-tier architectures where you need to update/replace components on the fly etc. - in personal experience however that was too esoteric a concept for the head of architecture team with the result that we lived in dll hell - in the .net world no-less !
Please forgive me for the pseudo code in advance!
Read up on SOLID principles. There are a few reasons in the SOLID principles for using Interfaces. Interfaces allow you to decouple your dependancies on implementation. You can take this a step further by using a tool like StructureMap to really make the coupling melt away.
Where you might be used to
Widget widget1 = new Widget;
This specifically says that you want to create a new instance of Widget. However if you do this inside of a method of another object you are now saying that the other object is directly dependent on the use of Widget. So we could then say something like
public class AnotherObject
{
public void SomeMethod(Widget widget1)
{
//..do something with widget1
}
}
We are still tied to the use of Widget here. But at least this is more testable in that we can inject the implementation of Widget into SomeMethod. Now if we were to use an Interface instead we could further decouple things.
public class AnotherObject
{
public void SomeMethod(IWidget widget1)
{
//..do something with widget1
}
}
Notice that we are now not requiring a specific implementation of Widget but instead we are asking for anything that conforms to IWidget interface. This means that anything could be injected which means that in the day to day use of the code we could inject an actual implementation of Widget. But this also means that when we want to test this code we could inject a fake/mock/stub (depending on your understanding of these terms) and test our code.
But how can we take this further. With the use of StructureMap we can decouple this code even more. With the last code example our calling code my look something like this
public class AnotherObject
{
public void SomeMethod(IWidget widget1)
{
//..do something with widget1
}
}
public class CallingObject
{
public void AnotherMethod()
{
IWidget widget1 = new Widget();
new AnotherObject().SomeMethod(widget1);
}
}
As you can see in the above code we removed the dependency in the SomeMethod by passing in an object that conforms to IWidget. But in the CallingObject().AnotherMethod we still have the dependency. We can use StructureMap to remove this dependency too!
[PluginFamily("Default")]
public interface IAnotherObject
{
...
}
[PluginFamily("Default")]
public interface ICallingObject
{
...
}
[Pluggable("Default")]
public class AnotherObject : IAnotherObject
{
private IWidget _widget;
public AnotherObject(IWidget widget)
{
_widget = widget;
}
public void SomeMethod()
{
//..do something with _widget
}
}
[Pluggable("Default")]
public class CallingObject : ICallingObject
{
public void AnotherMethod()
{
ObjectFactory.GetInstance<IAnotherObject>().SomeMethod();
}
}
Notice that no where in the above code are we instantiating an actual implementation of AnotherObject. Because everything is wired for StructurMap we can allow StructureMap to pass in the appropriate implementations depending on when and where the code is ran. Now the code is truely flexible in that we can specify via configuration or programatically in a test which implementation we want to use. This configuration can be done on the fly or as part of a build process, etc. But it doesn't have to be hard wired anywhere.
Appologies as this doesn't answer your question regarding a case for Interfaces.
However I suggest getting the person in question to read..
Head First Design Patterns
-- Lee
I don't understand how its extra overhead.
Interfaces provide flexibility, manageable code, and reusability. Coding to an interface you don't need to worry about the concreted implementation code or logic of the certain class you are using. You just expect a result. Many class have different implementation for the same feature thing (StreamWriter,StringWriter,XmlWriter)..you do not need to worry about how they implement the writing, you just need to call it.

Categories