Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it accepted to use a private method instead to avoid virtual members in constructor?

AFAIK, It's agreed that accessing virtual members from constructor is a dangerous practice. Can we overcome this through using an additional step, a method, to make required initialization? like the following:

public class EntityAlpha {
    public virtual string Value { get; protected set; }

    public EntityAlpha(string value) {
        Value = value;
    }
}

to be replaced with

public class EntityAlpha {
    public virtual string Value { get; protected set; }

    public EntityAlpha(string value) {
         AssignValue(value);
    }

    private void AssignValue(string value) {
        Value = value;
    }
}

What are consequences of using this additional method? Does it still dangerous like using virtual member in constructor or worst?! How to test if this assumption is not harmful?

like image 277
Wahid Shalaly Avatar asked Dec 01 '22 10:12

Wahid Shalaly


1 Answers

You effectively have the same problem, only now the code is more difficult to read.

The key is designing your class so that the constructor won't reach any virtual members, even indirectly through other methods.

like image 55
Greg Avatar answered Dec 15 '22 02:12

Greg