my problem: Inside an application, all interfaces are declared inside an own dll(project "interfaces", for example).
Inside project interfaces, there are many class implementations, too.
Now I need one of this implemented classes inside another project and get a ring dependency because this project is also a reference in project interfaces.
So, what is the best way to get around this ring dependency? Could it be possible that this is a big mistake in the design of the application?
Schematic representation:
IBigInterface.cs (everything in one file):
interface ISomeInterfaceA
{
void SomeFunctionA(ClassB x); // ClassB from newProject.cs
void SomeFunctionB();
}
//
// etc.
//
class ClassA
{
//
// Code
//
}
newProject.cs (everything in one file):
class ClassB
{
//
// used in interfaces.dll
//
}
class ClassC
{
void SomeFunction(ClassA a) // ClassA from IBigInterface.cs
{
//
// do something
//
}
}
First thing that comes into my mind would be sth. like:
IBigInterface.cs:
interface ISomeInterfaceA
{
void SomeFunctionA(IInterfaceB x); // use interface instead of a class
void SomeFunctionB();
}
interface IInterfaceB
{
//
// declarations
//
}
class ClassA
{
//
// implementation
//
}
newProject.cs:
class ClassB : IInterfaceB // implementation of IInterfaceB
{
}
class ClassC
{
void SomeFunction(ClassA a)
{
//
// implementation
//
}
}
so that project newProject wouldn't be a reference in project interfaces anymore (although this means changes in the whole application).
P.S.: I inherited this application so the idea of implementing classes in an interface-project was not my idea :).
In General, I would create one file per class (so don't point to this :).
First, there's nothing wrong with combining concrete classes and the interfaces they implement into a single assembly (though it would be a bit strange to call the project "interfaces").
Having said that, circular references are usually a sign that you've over-modularized your code: the parts causing the circular reference belong together and they should be merged into a single assembly.
Other times, a circular reference is just a sign that a class is in the wrong layer; the class needs to be moved into another assembly altogether (usually out of a lower-level infrastructure assembly and into a higher-level assembly). For example, ClassC might really belong in another project that references the "interfaces" assembly.
That's exactly the reason why Java requires public definitions to be in their own files (but I think you get the concept here :)).
It's usually not good to mix pure interface and implementation (though there are cases where it could be useful), and it's definitely a troublemaker if you export those into DLLs.
A cyclic dependency means your projects are too coupled to be distinct. This is usually a symptom of bad design (big ball of mud-like). You should either work on removing that coupling or merge both projects together.
If you have a specific project that, as you say, contains all your interfaces, why not introduce another project that contains "helper classes" such as ClassA? Then your interface DLL and the projects depending on the interface DLL could use the classes.
I would try to factor out the classes and interfaces that are common to several projects into a "Common" assembly (or similar), which has no dependencies to the assemblies that reference it.
For example, a business entity such as Product does not have to know anything about how it is persisted to a database or fetched via a web service, but the service components that do things with Product, for example IProductsRepository, needs to know what a Product is. Thus the assembly (or namespace) where IProductsRepository is defined holds a reference to the assembly (or namespace) where Product lives, but not the other way around.
Related
I'm trying to get my feet wet with unit testing. I'm currently not in the habit of writing interfaces for classes unless I foresee some reason I would need to swap in a different implementation. Well, now I foresee a reason: mocking.
Given that I'm going to be going from just a handful of interfaces to perhaps hundreds, the first thing that popped into my head was, Where should I put all these interfaces? Do I just mix them in with all the concrete implementations or should I put them in a sub-folder. E.g., should controller interfaces go in root/Controllers/Interfaces, root/Controllers, or something else entirely? What do you advise?
Before I discuss organization:
Well, now I foresee a reason: mocking.
You can mock with classes, as well. Subclassing works well for mocking as an option instead of always making interfaces.
Interfaces are incredibly useful - but I would recommend only making an interface if there is a reason to make an interface. I often see interfaces created when a class would work fine and be more appropriate in terms of logic. You shouldn't need to make "hundreds of interfaces" just to allow yourself to mock out implementations - encapsulation and subclassing works quite well for that.
That being said - I typically will organize my interfaces along with my classes, as grouping related types into the same namespaces tends to make the most sense. The main exception is with internal implementations of interfaces - these can be anywhere, but I will sometimes make an "Internal" folder + an Internal namespace that I use specifically for "private" interface implementations (as well as other classes that are purely internal implementation). This helps me keep the main namespace uncluttered, so the only types are the main types relating to the API itself.
Here's a suggestion, if almost all of your interfaces are to support only one class, just add the interface to the same file as the class itself under the same namespace. That way you don't have a separate file for the interface which could really clutter the project or need a sub folder just for interfaces.
If you find yourself creating different classes using the same interface, I would break the interface out into the same folder as the class unless it becomes completely unruly. But I don't think that would happen because I doubt you have hundreds of class files in the same folder. If so, that should be cleaned up and subfoldered according to functionality and the rest will take care of itself.
Coding to interfaces goes far beyond being able to test code. It creates flexibility in the code allowing a different implementation to be swapped in or out depending on product requirements.
Dependency Injection is another good reason to code to interfaces.
If we have an object called Foo that is used by ten customers and now customer x wants to have Foo work in a different way. If we have coded to an interface (IFoo) we just need to implement IFoo to the new requirements in CustomFoo. As long as we don't change IFoo there is not much needed. Customer x can use the new CustomFoo and other customers can continue to use old Foo and there need be few other code changes to accommodate.
However the point I really wanted to make is that interfaces can help eliminate circular references. If we have an object X that has a dependency on object Y and object Y has a dependency on object X. We have two options 1. with object x and y have to be in the same assembly or 2. we have to find some way of breaking the circular reference. We can do this by sharing interfaces rather than sharing implementations.
/* Monolithic assembly */
public class Foo
{
IEnumerable <Bar> _bars;
public void Qux()
{
foreach (var bar in _bars)
{
bar.Baz();
}
}
/* rest of the implmentation of Foo */
}
public class Bar
{
Foo _parent;
public void Baz()
{
/* do something here */
}
/* rest of the implementation of Bar */
}
If foo and bar have completely different uses and dependencies we probably do not want them in the same assembly especially if that assembly is already large.
To do this we can create an interface on one of the classes, say Foo, and refer to the interface in Bar. Now we can put the interface in a third assembly shared by both Foo and Bar.
/* Shared Foo Assembly */
public interface IFoo
{
void Qux();
}
/* Shared Bar Assembly (could be the same as the Shared Foo assembly in some cases) */
public interface IBar
{
void Baz();
}
/* Foo Assembly */
public class Foo:IFoo
{
IEnumerable <IBar> _bars;
public void Qux()
{
foreach (var bar in _bars)
{
bar.Baz();
}
}
/* rest of the implementation of Foo */
}
/* Bar assembly */
public class Bar:IBar
{
IFoo _parent;
/* rest of the implementation of Bar */
public void Baz()
{
/* do something here */
}
I think there is also an argument for maintaining the interfaces separate from their implementations and treating these sightly differently in the release cycle as this allows interoperability between components that were not all compiled against the same sources. If fully coding to interfaces and if interfaces can only be changed for major version increments and not on minor version increments then any component components of the same major version should work with any other component of the same major version regardless of the minor version.
This way you can have a library project with a slow release cycle containing just interfaces, enums and exceptions.
It depends. I do this: If you have to add a dependent 3rd party assembly, move the concrete versions out to a different class library. If not, they can stay side byside in the same directory and namespace.
I find that when I need hundreds of interfaces in my project to isolate dependencies, I find that there may be an issue in my design. This is especially the case when a lot of these interfaces end up having only one method. An alternative to doing this is to have your objects raise events and then bind your dependencies to those events. For an example, let's say you want to mock out persisting your data. One perfectly reasonable way to do this would be to do this:
public interface IDataPersistor
{
void PersistData(Data data);
}
public class Foo
{
private IDataPersistor Persistor { get; set; }
public Foo(IDataPersistor persistor)
{
Persistor = persistor;
}
// somewhere in the implementation we call Persistor.PersistData(data);
}
Another way you could do this without using interfaces or mocks would be do do this:
public class Foo
{
public event EventHandler<PersistDataEventArgs> OnPersistData;
// somewhere in the implementation we call OnPersistData(this, new PersistDataEventArgs(data))
}
Then, in our test, you can instead of creating a mock do this:
Foo foo = new Foo();
foo.OnPersistData += (sender, e) => { // do what your mock would do here };
// finish your test
I find this to be cleaner than using mocks excessively.
I disagree quite a bit with the Accepted answer.
1: While technically correct, you do not NEED an interface because you have the option to mock a concrete implementation, you should make an interface for 2 reasons.
You can extend your code with an interface, concrete implementations require modification, if you do not have an extension, once you get a change request.
1.1:
You can make TDD(Test driven development) without any actual implemented code, as long as you only create interfaces to test. This will also force you to consider code design before you make an implementation. Which is an excellent approach to coding.
1.2:
but I would recommend only making an interface if there is a reason to make an interface. I often see interfaces created when a class would work fine and be more appropriate in terms of logic.
There is always a reason to make an interface. Because SOLID's open/close principle says you should aim for extending your code rather than modifying it.
And this is true for multiple reasons.
1.2.1:
It's easier to write new unit tests this way. You will only need the dependency to the concrete implementation you are testing in your code as a subject. (And before you have a concrete implementation you can use a mock)
1.2.2:
When you have a concrete implementation, the reference to that concrete implementation will be propagated throughout the system. With an interface, all references will be done by interface, not concrete implementation. This makes extension possible.
1.2.3
If you follow up with all "leaf" piece of code, to follow the principle, if the method has a return, the method can't have a side effect, if the method doesn't have a return, it can only have 1 side effect, you will also automatically split your code up into the "S" part of SOLID, this makes your unit tests small, and very easy to maintain.
2:
Interfaces are technically needed, if you want to write clean code. If you want to follow SOLID, I don't see how you can do it, without interfaces.
You will also need to organize your code efficiently when you break about responsibilities, as the more decoupled your code is, the more interfaces and implementations of interfaces, you will have. Thus you need to have a good project management system in place, so you don't have "hundres of interfaces" lying around randomly.
There are so very good guides in books and youtube, udemy, etc. That will teach you this. (and also some poor ones, basically, they increase in usefulness when you have to pay for them in general). You will have to know enough about the subject matter to identify if a free one is good enough, if you plan to make business decision on it, before you do so, at least.
I am having the following problem. I have a main project, and some extra projects that have similar functionality.
For example: I have an MVC website, then a class library project "A" with a "SettingsHelper". This just defines static wrappers for configuration settings so they can be used as propertys.
Then I have another class library project "B", which also contains a "SettingsHelper class".
How can I merge these SettingsHelpers in my main project, so I can use: SettingsHelper.Property from both modular extra projects.
I would like to be able to plug extra class libraries into one project.
Sounds pretty much like Dependency Injection. Normally you would expose SettingsHelper as an interface (your contract), and program against that. Then a DI container, such as Ninject, StructureMap, or Windsor would plug an implementation of that interface into the relevant parts of your code based on configuration.
This would allow you to code against a known contract and provide different libraries depending on the circumstances, the DI framework could then use that library to get the concrete implementation of the interface.
Would you need both instances at the same time?
Note that you cannot utilise the partial keyword across different assemblies, only within an assembly.
Update: based on your comment it sounds like you want to do something like Composition. Have a class that takes both classes from either library and combines them into one class that can be used by your application. Whether you then configure it to do something special or load the types when the libraries are present, it can all be encapsulated in this new class.
Update 2: alternatively, look into MEF:
http://msdn.microsoft.com/en-us/library/dd460648.aspx
That won't work. Partial classes cannot be divided over assemblies -- they don't exist in the CLR, only in the editor and the compiler. So they are compiled together into a single CLR class.
What you can do, is inherit one from the other. However, helpers tend to be static classes, so that won't work either.
The other alternative is not to write helper classes, but extension methods. You can extend classes in one assembly with methods defined in another assembly (or multiple other assemblies). See also http://msdn.microsoft.com/en-us/library/bb383977.aspx.
I would say that move both Helper classes in 3rd project and add reference of that project to both of your projects. So this new library will become shared datastructures and functionalities library.
Regards.
The specific pattern you are after is called a Facade Pattern. Unfortunately you are not going to get any help from the compiler getting this right. Essentially:
Create a new CombinedSettingsHelper class in your local assembly.
If the two SettingsHelper types are in the same namespace you will need to set up aliases for them (check the reference properties in the solution explorer, and MSDN documentation for this).
Implement the object so that it can access both SettingsHelper objects.
To clean up your facade you might try having a abstract method along the lines of abstract object GetSettingValue(string name);. Your facade could then inherit from the same base class and call these on its contained children. For example:
public abstract class SettingsHelperBase { public object GetSettingValue(string settingName); }
// Assembly1
public class SettingsHelper : SettingsHelperBase { }
// Assembly2
public class SettingsHelper : SettingsHelperBase { }
public class SettingsHelper : SettingsHelperBase
{
private List<SettingsHelperBase> _backends = new List<SettingsHelperBase>();
public readonly PropertiesImpl Properties;
public class PropertiesImpl
{
private SettingsHelper _settingsHelper;
public string Name
{
get
{
return (string)_settingsHelper.GetSettingValue("Name");
}
}
internal PropertiesImpl(SettingsHelper helper)
{
_settingsHelper = helper;
}
}
public SettingsHelper()
{
_backends.Add(asm1::MyNs.SettingsHelper);
_backends.Add(asm2::MyNs.SettingsHelper);
Properties = new PropertiesImpl(this);
}
protected override object GetSettingValue(string settingName)
{
foreach (var item in _backends)
{
var val = item.GetSettingValue(settingName);
if (val != null)
return val;
}
return null;
}
}
There is a way; Visual Studio allows the same code file to be included in more than one project.
When you do “Add”/”Existing Item” to can select a file that is in the different folder.
This is what some of the silver light support does so as to allow a “common class” that has some method that are only on the server and one methods that are only on the client.
(As to the question of “good design” you will have to decide that yourself, a lot of people don’t like having the same class compiled in different ways in different projects. Think if the mess you could get in with #if XXX, when XXX is only defined in one of the projects)
There's a same question I keep asking myself each time a new Dependency Injection based solution is being started. I usually have a dedicated assembly for interfaces - this one is referenced by each and every other solution modules. Should I need to use some small user data types, I use to store those in interfaces assembly also. This seems to be the most logical thing, however it always makes the inerface assembly project look like a trashbox.
And the question is - what's the best place for SearchParams, SimpleTask and ComplexTask to be kept in? Please refer to the example below.
That's how I use to do:
Common.Interfaces
interface IScheduler
{
Boolean ScheduleTask(ITask task);
ITask FindTask(SearchParameters search);
}
interface ITask { ... }
class SearchParameters { ... }
Common.Scheduler
class Scheduler : IScheduler { ... }
class SimpleTask : ITask { ... }
class ComplexTask : ITask { ... }
The problem with SimpleTask and ComplexTask here is it requires me to reference Common.Scheduler wherever I'm calling IScheduler.ScheduleTask(...). And the problem with SearchParameters is it wastes interface assmebly. Imagine there are hundreds of small types stored under the same assembly.
Why do you need to reference Common.Scheduler when you call IScheduler.ScheduleTask? This method correctly uses the interface, so calling this method doesn't require you to reference Common.Scheduler.
You only need to reference that assembly if you are working with one of the concrete types SimpleTask or ComplexTask. In that case, it is correct that you need to reference that assembly.
I'm doing some internal domain-specific library development at the moment, and incidentally the stuff i'm trying to model mimicks "class" and "object" relations fairly well. So objects of my C# class MyClass should sort of act like a domain specific class for objects of my C# class MyObject who play the part of object or instance. Now I would like the code in MyObject to access methods of MyClass, which should not be accessible to other classes/code in the project. Any ideas how to enforce this, asside from documenting it at hoping my fellow developers will respect this.
I hope I made my question clear enough, otherwise let me know.
Best regards!
You could always split MyClass and MyObject up into another project, and define MyClass and/or MyObject as an internal class. That way it can only be accessed by other objects in that assembly.
See: http://msdn.microsoft.com/en-us/library/7c5ka91b(VS.80).aspx
The standard approach here is to declare the members internal and make sure MyClass and MyObject are part of the same assembly. That assembly should contain little else.
Additional: This is the tool that was designed for this purpose. Other languages have other means to fine-tune accessibility (C++: friend) but in .NET a simpler model was chosen.
And you don't have to take the 'nothing else' so strictly, the 2 classes could share an assembly with other related classes. you would then have to verify the no-access rule(s) manually inside that library.
I'd suggest a private nested class. That way, even if your fellow devs are writing code in the same namespace, they'll never be able to access the class.
Once the class declaration is fully enclosed within another class declaration, the class is considered nested and can only be accessed through the containing class.
Pehaps your MyObject should descend from MyClass and declare the methods in MyClas as protected.
If you don't want your consumers to invoke certain implementation specific methods you could try abstracting to interfaces or abstract base classes. That way the consumer will only 'see' the properties and methods you want them to see.
You do not have to use inheritance to provide shared functionality and you do not have to rely on member accesibility to prevent others from using methods you'd rather not expose.
For example:
public interface IDomainSpecific
{
void DoStuff();
}
public interface IDomainService
{
void HelpMeDoStuff();
}
public class DomainObject1 : IDomainSpecific
{
private readonly IDomainService _service;
public DomainObject1( IDomainService service )
{
_service = service;
}
public DoStuff()
{
// Do domain specific stuff here
// and use the service to help
_service.HelpMeDoStuff();
}
}
This uses classic constructor injection and works best when you already use dependency injection in your application, though it works perfectly well with factories as well.
The point is to keep responsibilities crystal clear. There's no chance of anybody invoking anything they shouldn't because the 'DomainObject' never knows what concrete type implements the shared service. The shared service is not exposed on the domain object either. The added bonus is testability and the possibility of swapping the service with another implementation without ever needing to touch the DomainObject.
I have 2 projects.
Project#2 has a reference to Project#1
Now I need to reference Project#2 in Project#1, but vs.net is complaining about a circular dependency.
Is there a way out of this?
Absolutely not. Circular dependencies are a indication of bad design. I don't mean to be harsh. There are some ways out of this.
1) You can refactor common code to another project, say Project#0
2) You can fix your design, which is probably the way to go.
Uncle Bob has a good article on Packaging Principles which includes the Acyclic Dependencies Principle. http://www.objectmentor.com/resources/articles/granularity.pdf. Read this to know why cyclic dependencies are a bad thing.
Refactor your projects to take the common elements out into a "Project #0" which both Project #1 and Project #2 reference.
Merge the two into one or redesign.
This points to a problem in your design. If there is a genuine need for two or more of your types to be mutually aware then they should exist in the same assembly.
A circular dependency means that these are no longer two independent projects (because there it is impossible to build only one of them).
You need to either refactor so that you have only a one way dependency or you should merge them into a single project.
No. Structure your projects properly. Try using some sort of ordering based on abstraction - low-level to high-level.
Circular reference can be done as seen in a previous question, but you should not do it for the reasons everybody already stated here.
I really don't mean to be a smart-aleck, but better program design is the answer.
Everyone will tell you this is a bad design do not do it etc. However sometimes it is easier said than done and moving the implementation into a separate common code is not desirable.
For such cases instead of calling the other package directly, emit an event from one package and handle it in the other. That way you do no need to make the other component a dependency in the first component.
Another way if you still want to keep the implementation in separate packages is to derive your logic classes form interfaces and define those in a separate package. This works if you have a way to instantiate the implementation, for example via dependency injection or other means.
Contrary to what's been said before, circular dependencies are sometimes unavoidable. For sure there are benefits to linear designs (maintainability, readability, debugging etc.) but it makes no sense to give up circularity/bidirectionality if it is going to make you give up on splitting projects based on their functionality (which wouldn't help you maintain or understand the code).
Solution:
You have to use a project with interfaces to which both of said projects reference to.
Classes from higher level projects contain implement interfaces from the interface project.
This way you can expose method implementations and classes in a circular manner.
Some pseudocode:
Project Interface
interface IApple { void dropOnHead(IPerson person);}
interface IPerson { void eatApple(IApple apple);}
Project#1
using ProjectInterfaces;
class Apple : IApple{
void dropOnHead(IPerson person) { log("bop");}
}
Project#2
using ProjectInterfaces;
class Person : IPerson{
void dropOnHead(IApple apple) { log("crunch");}
}
This seems to be a design flaw, nothing else. Re-design is the solution.
In C++ you can forward declare class B, if class A depends on it. Something like that.
// segment.hpp
class Polygon; // fwd declare
class Segment {
public:
bool Intersects(Polygon p);
};
and
// polygon.hpp
class Segment; // fwd declare
class Polygon {
public:
bool Intersects(Segment s);
};
While in C# you could create an extension module, far away from both. Something like that
// Segment.cs
namespace MyLib {
public class Segment {
// ...
}
}
and
// Polygon .cs
namespace MyLib {
public class Polygon {
// ...
}
}
and a third file
// Extensions.cs
namespace MyLib {
public static class Extensions {
public static bool Intersects(this Segment s, Polygon p) { //... }
public static bool Intersects(this Polygon p, Segments) => s.Intersects(p);
}
}
and then you will haver no circular dependencies and get this result.
// Program.cs
using MyLib; // that's all you need
namespace ConsoleApp {
internal class Program {
static void Main(string[] args) {
var s = new Segment(...);
var p = new Polygon(...);
bool intersects = p.Intersects(s);
}
}
}
I don't think it is a good solution but still we can do by following these steps
add the reference
browse and
go to Debug folder of dll project,
find the .dll and Add .