Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing a method being called before another one

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.

like image 510
Cemre Mengü Avatar asked Aug 26 '12 02:08

Cemre Mengü


3 Answers

One way to guarantee this? Make it the responsibility of method B to call method A once.

Anything else is a fragile API.

like image 167
Mitch Wheat Avatar answered Oct 08 '22 08:10

Mitch Wheat


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");
like image 6
jeff Avatar answered Oct 08 '22 09:10

jeff


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.

like image 5
João Silva Avatar answered Oct 08 '22 10:10

João Silva