Thursday, July 16, 2020

Static Factory Constructors

I bought and am reading Uncle Bob's "Clean Code". It is my new bible. I will be posting some of the better ideas I read in it. Here is the first.

One of the problems we see from time to time is ambiguous class constructors.


        public cBox() { }
       
        public cBox(int length, int width, int height)
        {
            this.length = length;
            this.width = width;
            this.height = height;
        }

As you instantiate this class it can be difficult to know which constructor to use because they all have the same name (that's the nature of constructors). How about using static factories with unambiguous names like this?


        public static cBox FromLengthWidthHeight(int length, int width, int height)
        {
            return new cBox { length = length, width = width, height = height };
        }

When you instantiate, it looks like this.


        cBox BigBox = cBox.FromLengthWidthHeight(10, 10, 20);


No comments:

Post a Comment