views:

143

answers:

2

I have the following class:

public class Fluently
{
  public Fluently Is(string lhs)
  {
    return this;
  }
  public Fluently Does(string lhs)
  {
    return this;
  }
  public Fluently EqualTo(string rhs)
  {
    return this;
  }
  public Fluently LessThan(string rhs)
  {
    return this;
  }
  public Fluently GreaterThan(string rhs)
  {
    return this;
  }
}

In English grammar you can’t have “is something equal to something” or “does something greater than something” so I don’t want Is.EqualTo and Does.GreaterThan to be possible. Is there any way to restrict it?

var f = new Fluently();
f.Is("a").GreaterThan("b");
f.Is("a").EqualTo("b");        //grammatically incorrect in English
f.Does("a").GreaterThan("b");
f.Does("a").EqualTo("b");      //grammatically incorrect in English

Thank you!

+9  A: 

To enforce that type of thing, you'll need multiple types (to restrict what is available from which context) - or at the least a few interfaces:

public class Fluently : IFluentlyDoes, IFluentlyIs
{
    public IFluentlyIs Is(string lhs)
    {
        return this;
    }
    public IFluentlyDoes Does(string lhs)
    {
        return this;
    }
    Fluently IFluentlyDoes.EqualTo(string rhs)
    {
        return this;
    }
    Fluently IFluentlyIs.LessThan(string rhs)
    {
        return this;
    }
    Fluently IFluentlyIs.GreaterThan(string rhs)
    {
        return this;
    }
}
public interface IFluentlyIs
{
    Fluently LessThan(string rhs);
    Fluently GreaterThan(string rhs);
}
public interface IFluentlyDoes
{    // grammar not included - this is just for illustration!
    Fluently EqualTo(string rhs);
}
Marc Gravell
oh yes... thanks.
Jeffrey C
we need a grammar guru now!
Jeffrey C
A: 

My solution would be

public class Fluently
{
    public FluentlyIs Is(string lhs)
    {
        return this;
    }
    public FluentlyDoes Does(string lhs)
    {
        return this;
    }
}

public class FluentlyIs
{
    FluentlyIs LessThan(string rhs)
    {
        return this;
    }
    FluentlyIs GreaterThan(string rhs)
    {
        return this;
    }
}

public class FluentlyDoes
{
    FluentlyDoes EqualTo(string rhs)
    {
        return this;
    }
}

Quite similar to Gravell's, but slightly simpler to understand, in my opinion.

Alexey Romanov
i prefer Gravell's solution as I can split the single class into partial class for readbility.
Jeffrey C