Reputation: 4369
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.
Upvotes: 7
Views: 6194
Reputation: 9113
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)
Upvotes: 3
Reputation: 5173
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.
Upvotes: 1
Reputation: 1500525
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
.
Upvotes: 10
Reputation: 71
Not a problem in terms of style. This will be a problem if you need the constructed SomeClass after invoking the DoSomething method.
Upvotes: 1