简体   繁体   中英

Instancing an object and calling a method in one line?

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.

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 .

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)

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

It's not flawed design. I'd say that the only problem is readability, if the rest of your team is not using this style then don't use it especially with var cause it makes it harder to understand what is returned. For me, I personally like it since I am used to chaining from jquery.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM