Let's say that we have the following interface -
interface IDatabase {
string ConnectionString{get;set;}
void ExecuteNoQuery(string sql);
void ExecuteNoQuery(string[] sql);
//Various other methods all requiring ConnectionString to be set
}
The precondition is that ConnectionString must be set/intialized before any of the methods can be run.
This precondition can be somewhat achieved by passing a connectionString via a constructor if IDatabase were an abstract or concrete class -
abstract class Database {
public string ConnectionString{get;set;}
public Database(string connectionString){ ConnectionString = connectionString;}
public void ExecuteNoQuery(string sql);
public void ExecuteNoQuery(string[] sql);
//Various other methods all requiring ConnectionString to be set
}
Alternatively, we can create connectionString a parameter for each method, but it looks worse than just creating an abstract class -
interface IDatabase {
void ExecuteNoQuery(string connectionString, string sql);
void ExecuteNoQuery(string connectionString, string[] sql);
//Various other methods all with the connectionString parameter
}
Questions -
- Is there a way to specify this precondition within the interface itself? It is a valid "contract" so I'm wondering if there is a language feature or pattern for this (the abstract class solution is more of a hack imo besides the need of creating two types - an interface and an abstract class - every time this is needed)
- This is more of a theoretical curiosity - Does this precondition actually fall into the definition of a precondition as in the context of LSP?