Readonly vs abstract getter-only field

What are the advantages and disadvantages of having a readonly field compared to the fact that inheritors implement the abstract getter-only property (using C # as an example here, but in my opinion, it does not really matter).

Here are two ways to do this:

  • read-only field heirs need to insert a value into the constructor

    interface IFace {
      public int Field { get; }
    }
    
    abstract class Base : IFace {
      private readonly int field;
    
      protected Base(int field) {
        this.field = field;
      }
    
      public int Field { get { return this.field; } }
    }
    
    class Impl {
      public Impl() : base(1) {
      }
    }
    
  • abstract property getter-only; Inheritors must implement a property

    interface IFace {
      public int Field { get; }
    }
    
    abstract class Base : IFace {
      // default constructor can be used
    
      public abstract int Field { get; }
    }
    
    class Impl {
      public override int Field { get { return 1; } }
    }
    

Both implementations expose the public property int Fieldgetter-only, which does not change.

However, I see the following differences:

  • The value is fieldattached to each instance and nothing prevents the heirs from allowing the value to be received in the constructors themselves ( public Impl(int field) : base(field)).

    , . , .

    : ( ).

  • () field , / , . public overried int Field { get { return DateTime.UtcNow.Second; } }

    " IL", () , ( ).

    : ( , , ?). , , : , , .

- , ? , ?

, //, readonly (constant) , . , , ( ). , . ? .

+4
3

1 2, .

1 , , .

2 . - , .

- , , .

, - , (- getReadOnlyField() ), . - - - .

. . .

+1

, readonly- - . readonly - , , .

-getter - . , .

, public int Field; ? ( ) , Field. , , getter.

+1

, . .. , .. .

, - , - , LSP. , , , , . , LSP . , .

To say it, I would say that in the cases that you have stated, there is no real difference. Yes, the implementations are syntactically and semantically different, but other classes will in any case depend only on IFace, right? Seriously, there is no reason to rely on specific implementations if there is already an abstraction. Therefore, nothing prevents anyone from creating a new implementation for IFaceand passing it on.

+1
source

Source: https://habr.com/ru/post/1584168/


All Articles