John
John

Reputation: 3402

Is chaining c# to look like jQuery a good idea?

I'm thinking of using extension methods to chain a c# statement to look like jQuery in teh following:

foo foo2 = 
  new foo().Title(foo1.Title)
  .Name(foo1.Name)
  .DoSomeStuff()
  .DoSomeMoreStuff();

Is this a good/bad idea?

public class foo
{
  public string Title {get;set;}
  public string Name {get;set;}
  public int Age {get;set;}

  public foo(){} 
}

public static class fooExtension
{
  public static foo Title(this foo source, string title)
  {
    source.Title = title;
    return source;
  }

 //and other extensions
}

Upadate: More explanation as the the "why" I'm considering this. I have 2 things going on:

  1. I'm getting data from one object and using it to set the properties of another.
  2. I need to perform some action on these properties.

So my initial code looked more like

foo2.bars = foo1.bars;
foo2.RemoveUnderage();
foo2.NotifyPatronsBarsAreFull();

and instead, I thought that it might be more descriptive to write:

foo2.bars(foo1.bars).RemoveUnderage().NotifyPatrons();

Initializers are great, but they also bundle the properties all together and I wanted the property set to be close to the actions on which I would be taking on them.

Upvotes: 2

Views: 801

Answers (4)

TcKs
TcKs

Reputation: 26632

Do you mean Fluent interface? In some cases the same way is used in classes in .NET Framework (i.e. StringBuilder or LINQ extension methods). However the fluent interface must be explicitly created and it is a lot of work and usage from another language than C# can be not so pretty. I don't think that creating fluent interface for every class is good way how deliver good software in short time.

Upvotes: 0

jmccarthy
jmccarthy

Reputation: 480

I think it is a bad idea in terms of readability, but that's strictly a personal thing.

Upvotes: 0

n8wrl
n8wrl

Reputation: 19765

I personally like this 'fluent' style of programming. Properly-named methods can look like sentences. I would change yours just a bit:

foo foo2 = new foo()
{
    Title = foo1.Title,
    Name = foo1.Name
}
.DoSomeStuff()
.DoSomeMoreStuff(); 

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502406

Anything wrong with using object initializers instead?

new Foo { Title = foo1.Title, Name = foo1.Name }
   .DoSomeStuff()
   .DoSomeMoreStuff();

Chaining in general is fine (look at LINQ) but object initializers mean you don't need to add methods which look like properties.

Upvotes: 5

Related Questions