Prevent method invocation before another

This question is a little broad and conceptual.

I have a class with various methods. Name them Aand B. How can I make sure that other developers working with this class in the future do not call method B before the first call to method A at least once?

I do this in C ++, but in general, what is the best way to provide this? I have some naive ideas, such as using a boolean variable, but I would like to hear other thoughts.

+5
source share
6 answers

One way to guarantee this? Run method B to call method A once.

Everything else is a fragile API.

+10
source

, .

. - .

A , -, B.

class MyClass {
  public:

    struct BProxy {
      public:
        MyClass * root;
        void B() { root->B(); }
      protected:
        BProxy( MyClass * self ) : root(self) {}; // Disable construction
        friend class MyClass; //So that MyClass can construct it
    };

    BProxy A() { ... return BProxy(this); }
    friend class BProxy; // So that BProxy can call B()
  protected
   void B() { ... }
};

int main() {
   MyClass m;
   BProxy bp = m.A(); 
   // m.B(); can't do this as it private - will fail at compile time.
   bp.B(); // Can do this as we've got the proxy from our previous call to A.
}

- , ( ) B().

+5

- . , . Java, ...

public class Database {
  public void init(String username, String password) // must call this first!
  public List<Object> runQuery(String sql) // ...
}

init. DatabaseFactory, . , DatabaseFactory ( Java - , ++ - , ?).

public class DatabaseFactory {
   public Database init(String username, String password) // ...

   public class Database {
     private Database() {}
     public List<Object> runQuery(String sql) // ...
   }
}

, Factory, .

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");
+5

, , A. , - B , IllegalStateException.

B A, , A, .

, , .

+4

, A . (), , B . , A , B - .

+2

"" . , , . "B", , .

+2

All Articles