Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instancing an object and calling a method in one line?

Tags:

c#

I have a lot of code like this

var o = new SomeClass().DoSomething(someParam);

Is this a design flaw ?

This class is some kind of a builder class.It should contruct other object.

like image 972
user256034 Avatar asked Sep 01 '11 08:09

user256034


3 Answers

Nope, that's fine - and in particular you might see it frequently with types which are used as builders. For example:

string x = new StringBuilder().Append("Foo")
                              .AppendFormat("{0}:{1}", x, y)
                              .ToString();

Or in my Protocol Buffers port:

Person p = new Person.Builder { Name = "Jon", Age = 35 }.Build();

Here the Person type is immutable, but the builder type isn't - so you create a builder, set some properties, and then call Build.

like image 132
Jon Skeet Avatar answered Oct 29 '22 02:10

Jon Skeet


If you don't need the instance after calling the method, you probably better with a static method on SomeClass and ends up with

var o = SomeClass.DoSomething(someParam);

and if for any reason, you absolutely need a new instance to execute DoSomething then you could create a static factory method to make the code more readable like :

var o = SomeClass.GetInstance().DoSomething(someParam)
like image 35
VdesmedT Avatar answered Oct 29 '22 02:10

VdesmedT


Not a problem in terms of style. This will be a problem if you need the constructed SomeClass after invoking the DoSomething method.

like image 42
SergioC Avatar answered Oct 29 '22 00:10

SergioC