Is this clean coding? (.Net, C#) [closed]
In one of our projects I found this code
class A
{
private B b = new B();
protected void AMethod()
{
var x = b.DomeSome();
}
}
My question, is this a "clean" way of coding? Would it be cleaner to instantiate b in AMethod? Does is depend?
If you create an instance of b in AMethod
, then the variable will lost after AMethod
ends. So each call of AMethod
will create a new object B.
On the other hand, having the variable declared at class level (like in your example) will allow you to reuse the instance of B for all the calls of AMethod
.
There is not precise answer on how is cleaner unless your provide us with more context
If DomeSome
changes the state of B
the logic would be different if B
was instantiated on every call of AMethod
.
With this amount of code given: The code is clean and it depends.
Would it be cleaner to instance b in AMethod?
It would be different. In the current code b is instantiated when A is instantiated.
Does ist depend?
Yes
Yes It totally depends upon you requirement.. That b
variable of type B
may be needed somewhere else too so it has been declared in the Class
.
And there is no hard defined specifications on clean coding
. Keep coding as long as its concise, understandable and does what it needs to do.
Also I assume you have changed variable names to A & B for posting here.. if these are present in actual code.. CHANGE IT NOW !!
精彩评论