开发者

: this() As a constructor

开发者 https://www.devze.com 2023-01-12 02:15 出处:网络
I\'m trying to get a better understanding of general practice... specifically deriving this() in a constructor.I understand that its less code, but I consider it less readable.Is it common/g开发者_Sta

I'm trying to get a better understanding of general practice... specifically deriving this() in a constructor. I understand that its less code, but I consider it less readable. Is it common/g开发者_StackOverflow中文版ood practice to do it this way? Or is it better to write a second constructor that handles it specifically?

public SomeOtherStuff(string rabble) : this(rabble, "bloop") { }

or

Public SomeOtherStuff(string rabble)
{
    //set bloop
}

Any input would be greatly appreciated


It is good practice to use this() whenever possible. Otherwise you will be duplicating some code, which violates the DRY (Don’t Repeat Yourself) principle. The problem with repeating yourself is that every time you need to make a change — even if it’s a simple change to a single line of code — you have to remember to make the same change in multiple places, and keep the multiple copies synchronised.

You should only “duplicate” the code when you need to because it needs to be different, so it’s no longer a duplicate. This way, having a duplicate is a message to the reader that the code is actually different, and is so for a reason.


The problem with the two separate constructors is, that they often contain identical code, which may lead to problems with later refactorings, when one constructor is changed and the other not. So you could see constructor chaining with this() as an application of the DRY principle.


Initialization lists are very common practice in industry.

As for readability... that is a matter of opinion. But maintainability is usually a higher goal to strive for.

DRY is a good thing :)


That is how you chain constructors and it is a perfectly valid thing to do.


I really like the first way (constructor chaining) but if you feel the second way is more readable then go for that and you could put whatever duplicate code you have in the constructors into a private method to avoid breaking the DRY principle people have mentioned.

Also, I also always try to code in the style of the code I'm working on - so if the predominant style is one or the other, I'd go with that style for consistency.


I care less about readability and more for reliability.

Chaining constructors is much better than copypasting constructor method bodies.


another way to DRY is writing an initialization method, for example Init(rabble, bloop) and all constructors calls this method.

This tends to be less confusing and more flexible especially where there are many constructors.

0

精彩评论

暂无评论...
验证码 换一张
取 消