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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With