5

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!

Jeff
  • 13,079
  • 23
  • 71
  • 102
  • Are you sure that “is something equal to something” is grammatically incorrect?? – Darko Aug 20 '09 at 07:30
  • Maybe not but you get the idea right? – Jeff Aug 20 '09 at 07:31
  • Yeah I get the idea, i think its about context. Are you *asking* if its equal or *stating* that its equal? Would answer your question if I knew but to tell you the truth I'm not sure, so I'm being a grammar nazi :) – Darko Aug 20 '09 at 07:34

2 Answers2

9

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
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

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
  • 167,066
  • 35
  • 309
  • 487
  • i prefer Gravell's solution as I can split the single class into partial class for readbility. – Jeff Aug 20 '09 at 07:45