How to solve circular reference? - c#

How do you solve circular reference problems like Class A has class B as one of its properties, while Class B has Class A as one of its properties?
How to do architect for those kind of problems?
If you take an example of NHibernate, there will be a parent-child relationship between objects.
How is it able to handle those parent child scenarios?

In most cases when I've had to have two things reference each other, I've created an interface to remove the circular reference. For example:
BEFORE
public class Foo
{
Bar myBar;
}
public class Bar
{
Foo myFoo;
}
Dependency graph:
Foo Bar
^ ^
| |
Bar Foo
Foo depends on Bar, but Bar also depends on Foo. If they are in separate assemblies, you will have problems building, particularly if you do a clean rebuild.
AFTER
public interface IBar
{
}
public class Foo
{
IBar myBar;
}
public class Bar : IBar
{
Foo myFoo;
}
Dependency graph:
Foo, IBar IBar
^ ^
| |
Bar Foo
Both Foo and Bar depend on IBar. There is no circular dependency, and if IBar is placed in its own assembly, Foo and Bar being in separate assemblies will no longer be an issue.

I would tell your friend he needs to rethink his design. Circular references like you describe are often a code smell of a design flaw.

Unlike C++ (for instance), C# does not need forward declarations to resolve circular references. Hence:
public class A
{
public B B { get;set; }
}
public class B
{
public A A { get;set; }
}
However, this is often an indicator of questionable design decisions.

In most every case the best solution is to change your design and avoid a circular dependency. For instance you may do one of the following:
Move the common referenced code to a utility project in your solution and have the other projects reference the Utility project
Use an interface as explained by "Ed Bayiates" in his answer.
If its a small amount of simple/common code then rewrite it for one of the classes so you don't need to reference it in a circular dependency. (my least favorite)
However, if you are working in a solution with many projects and you don't have the ability to make one of the changes above because you don't own the code, its to difficult to implement, or not worth the time to fix, then You can use this method:
Right-click on the project references and select "Add Reference...". Then in the dialog window that appears switch to the "Browse" tab and the "Browse" button. From there you can go find the DLL and select it. This is a work around at best and can cause build problems especially if both DLLs are being updated frequently, and/or have many dependencies. I do not recommend this method but it works in a pinch.
Fissh

interfaces are a good idea however if your looking for a quicker solution than redoing the architecture of so many things try building one dll class library that holds all your data structures your main project holds your UI that needs that data and then any other dlls you want to add can access that data structures dll as well so they have all the info they need to run but still can be separate- this is called the tri force design pattern -

Circular reference occurs when two or more interdependent resources cause lock condition. This makes the resource unusable.
To handle the problem of circular references in C#, you should use garbage collection. It detects and collects circular references. The garbage collector begins with local and static and it marks each object that can be reached through their children.
Through this, you can handle the issues with circular references.
Let’s say the following classes is in circular reference. Here both of them depends on each other −
public class A
{
B Two;
}
public class B
{
A one;
}
To solve the issue, create an interface −
public interface myInterface {
}
public class A {
myInterface Two;
}
public class B: myInterface {
A one;
}

Related

Automatic (and not refactor-related) extraction of interface from class

I'm relatively new to C# so this may be a somewhat naive question.
Does there exist a way, or can one even be constructed, to construct an interface containing all the public methods/properties of a class?
I find myself in a project using the mocking framework Moq. Moq has an apparently rather common limitation in that it can only handle interfaces and virtual methods. The project's architect has decided to go the interface route, which means every class in the project has an accompanying interface. This means there are loads of interfaces implemented by a single class. Furthermore, the style mandates that interfaces go into their own files. This means there are loads of files in the project.
In my opinion it would be a real improvement if these interface-and-files-just-for-Moq could be a bit less intrusive. Is there no way to have the system (Visual Studio/.Net/C#) create them.
For instance, if writing this
[ExtractAndImplement("IFoo")]
public class Foo
{
public int Bar(int baz)
{
...
}
}
would be equivalent to
public interface IFoo
{
int Bar(int baz);
}
public class Foo : IFoo
{
public int Bar(int baz)
{
...
}
}
NB No, Refactor -> Extract Interface does not do what I want. First off, it creates an interface in source code somewhere, so it doesn't reduce the clutter of singly-implemented interfaces. Second, it's an interface I need to maintain explicitly; when I add a public method in the class I need to extract that new method to the correct interface. No, I'd like to have something that's implicit, i.e. interfaces are created on the fly without cluttering the source or the project.
I'm guessing that in Lisp/Scheme it'd be done using macros, and in Haskell using templates.
You can do this in Visual Studio (not in the express version).
Use Refactor -> Extract Interface. The cursor needs to be placed on the classname.
For more information:
http://msdn.microsoft.com/en-us/library/fb3dyx26.aspx
You could also look at ReSharper for this option or SharpDevelop.
You are probably asking for
The interface language is in Italian (It says "Extract Interface"), sorry, but you got a hint I hope.

Where do I put all these interfaces?

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.

Class implementations in interface dll?

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.

Circular dependencies

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 .

How to derive from an internal interface in another assembly

I'm a C# newbie, so please bear with me.
OK, so I have two classes in different assemblies that need to reference each other:
namespace AssemblyA
{
class A
{
private B MyB { get; set; }
}
}
namespace AssemblyB
{
class B
{
private A MyA { get; set; }
}
}
I understand that circular references aren't allowed, so I'm using an interface:
namespace AssemblyA
{
public interface IB
{
// whatever 'A' needs of 'B'
}
class A
{
private IB MyB { get; set; }
}
}
namespace AssemblyB
{
class B : AssemblyA.IB
{
private A MyA { get; set; }
}
}
This works, but it has the disadvantage that it exposes IB to the rest of the world. What I would like to do instead is to make IB internal. But then B cannot derive from it.
In C++, I'd make B a friend and be done. I understand that C# doesn't have friends (pun not intended, but noted), so I have to make do without. I've read that there is an attribute for that, but this will make the whole of assembly A accessible to the whole of assembly B, which I don't like. Is there a way to avoid that?
You've in fact been misinformed - C#/.NET does indeed have support for friend assemblies. You want to mark your two assemblies as Friend Assemblies, which MSDN defines as the following:
An internal type or internal member in an assembly can be accessed from another assembly.
So, simply place the following attribute anywhere in one of your code files in your project (I would choose AssemblyInfo.cs).
[assembly:InternalsVisibleTo("name_of_friend_assembly")]
It seems that the big issue here is letting assembly B see one specific member of assembly A.
This negates, according to the comments reiterating part of the original question, the feasibility of using the well-documented InternalsVisibleTo attribute.
Or does it?
Have you considered making a new assembly, C, with the IB interface marked internal and its own InternalsVisibleTo attributes out to A and B?
This at least exposes IB in a controlled fashion, without exposing all of A to B. I'm not a huge fan of the solution (I would personally just go ahead and use InternalsVisibleTo on A as has been suggested, then document the rest of my internals to keep others in line), but I understand where you're coming from -- and this at least solves the problem.
You could use InternalsVisibleToAttribute
http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx

Categories

Resources