Search code examples
c#.netcode-contracts

C# Usage of Redundant Code Contract-Preconditions


I did not find the info by reading the usage guidelines, so I ask my question here: Assuming the following situation:

    /// <summary>
    /// Initalisiert eine neue Instanz des SettingsManager
    /// </summary>
    /// <param name="settingsRepo">Das SettingsRepository welches die Einstellungen enthält</param>
    public SettingsManager(ISettingsRepository settingsRepo)
    {
        Contract.Requires<ArgumentNullException>(settingsRepo != null, "The parameter settingsRepo cant be null");

        _settingsRepo = settingsRepo;
    }

    /// <summary>
    /// Lädt alle Einstellungen
    /// </summary>
    public void Load()
    {
        Contract.Requires<NullReferenceException>(_settingsRepo != null, "The repository cant be null");
        .
        .
        .
    }

where _settingsRepo is a global private field of the class SettingsManager. In the constructor, I define the precondition, that the parameter settingsRepo is not null. So when settingsRepo equals null an Exception is thrown. But the method Load() uses the field _settingsRepo which definetly wasn't null during instantiation. However, I do not know if _settingsRepo equals null at the moment, when Load() is being used, so is the precondition I defined in the method Load() considered as redundant, or should I rest this.


Solution

  • As I mention in the question's comment. You can remove the validation from Load method. The pattern you are using called Constructor Injection. The idea behind C'tor injection is the object you are trying to create needs a dependency and don't have any default/alternative behaviour if you don't supply the dependency. In your case it seem exactly the situation.

    Summery: You verified the _settingsRepo is not null in the C'tor, therefore you don't need to verify it again in the Load' method.

    This is a very good book about DI, I recommends you to read it.