How can I use multiple constructors to remove duplicated code while maintaining readability?
- 阅读更多 关于 How can I use multiple constructors to remove duplicated code while maintaining readability?
int a, b, c; Constructor() { a = 5; b = 10; c = 15; //do stuff } Constructor(int x, int y) { a = x; b = y; c = 15; //do stuff } Constructor(int x, int y, int z) { a = x; b = y; c = z; //do stuff } To prevent duplication of "stuff" and a few assignments, I tried out something like: int a, b, c; Constructor(): this(5, 10, 15) { } Constructor(int x, int y): this(x, y, 15) { } Constructor(int x, int y, int z) { a = x; b = y; c = z; //do stuff } This works for what I want to do, but sometimes I need to use some lengthy code to create new objects or do some calculations: int a, b, c; Constructor():