This is question is a bit broad and conceptual.
I have a class with various methods. Let's call them A
and B
. How can I make sure that other developers working with this class in the future will not call method B before first calling method A at least once ?
I am doing this in C++ but in general what's the best way to enforce this ? I have naive some ideas such as using a boolean variable but I would like to hear some other thoughts as well.
One way to guarantee this? Make it the responsibility of method B to call method A once.
Anything else is a fragile API.
One way is to redesign your class a little differently. Consider a simple database class that needs to be initialized before being used. I'm a Java guy, so...
public class Database {
public void init(String username, String password) // must call this first!
public List<Object> runQuery(String sql) // ...
}
So I need to call init first. I can make a DatabaseFactory that does the initialization and returns the actual database object. We can hide the constructor so that only a DatabaseFactory can create a Database (in Java a nested class, in C++ a friend class maybe?).
public class DatabaseFactory {
public Database init(String username, String password) // ...
public class Database {
private Database() {}
public List<Object> runQuery(String sql) // ...
}
}
So now I must go through the Factory to get to the underlying object.
DatabaseFactory factory = new DatabaseFactory();
Database database = factory.init("username", "password"); // first init (call method A)
// now I can use database (or B in your case)
database.runQuery("select * from table");
Have a boolean variable that determines if A
has been called. Then, when someone tries to invoke B
without this boolean variable being set, throw an IllegalStateException.
Or you could have B
simply call A
since it seems that it cannot execute without A
being called first anyways.
Otherwise, and since both methods are public, there's really no other way to enforce this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With