Should inheritance (of non-interface types) be removed from programming languages?

前端 未结 20 2278
旧时难觅i
旧时难觅i 2020-12-30 05:20

This is quite a controversial topic, and before you say \"no\", is it really, really needed?

I have been programming for about 10 years, and I can\'t honestly sa

20条回答
  •  情话喂你
    2020-12-30 05:46

    Inheritance can be rather useful in situations where your base class has a number of methods with the same implementation for each derived class, to save every single derived class from having to implement boiler-plate code. Take the .NET Stream class for example which defines the following methods:

    public virtual int Read(byte[] buffer, int index, int count)
    {
    }
    
    public int ReadByte()
    {
        // note: this is only an approximation to the real implementation
        var buffer = new byte[1];
        if (this.Read(buffer, 0, 1) == 1)
        {
            return buffer[0];
        }
    
        return -1;
    }
    

    Because inheritance is available the base class can implement the ReadByte method for all implementations without them having to worry about it. There are a number of other methods like this on the class which have default or fixed implementations. So in this type of situation it's a very valuable thing to have, compared with an interface where your options are either to make everyone re-implement everything, or to create a StreamUtil type class which they can call (yuk!).

    To clarify, with inheritance all I need to write to create a DerivedStream class is something like:

    public class DerivedStream : Stream
    {
        public override int Read(byte[] buffer, int index, int count)
        {
            // my read implementation
        }
    }
    

    Whereas if we're using interfaces and a default implementation of the methods in StreamUtil I have to write a bunch more code:

    public class DerivedStream : IStream
    {
        public int Read(byte[] buffer, int index, int count)
        {
            // my read implementation
        }
    
        public int ReadByte()
        {
            return StreamUtil.ReadByte(this);
        }
    }
    

    }

    So it's not a huge amount more code, but multiply this by a few more methods on the class and it's just unnecessary boiler plate stuff which the compiler could handle instead. Why make things more painful to implement than necessary? I don't think inheritance is the be-all and end-all, but it can be very useful when used correctly.

提交回复
热议问题