omsharp
omsharp

Reputation: 353

Is this bad code? If it is then how to work around it?

Is this considered circular dependency? I don't like that part where I have to pass the object itself to IRule... Is there a way to work around this?

  public interface IRule
  {
    void Apply(World world);
  }

  public class World
  {
    public List<IRule> Rules { get; set; }

    public void ApplyAllRules()
    {
        foreach (var rule in Rules)
        {
            //This is the part that I don't feel good about.
            rule.Apply(this);
        }
    }
  }

Upvotes: 0

Views: 79

Answers (1)

T.S.
T.S.

Reputation: 19340

May be I am wrong but term "circular dependency" usually applied to references. What you have here is called "tight coupling". As Gjeltema mentioned, there is not much wrong here besides that preferably, you decouple your concrete objects.

public interface IRule
{
    void Apply(ILocation loc);
}

public class World : ILocation
{
    public List<IRule> Rules { get; set; }

    public void ApplyAllRules()
    {
        foreach (var rule in Rules)
        {

           rule.Apply(this);
        }
     }
 }

Now you have IRule communicating not to concrete object but to abstract interface. So, no 2 or more implementations are tightly coupled.

Upvotes: 1

Related Questions