c++ - Is there a design patter that can deal with method call dependencies? -


my problem this:

when design c++ class, in cases, methods can called after other methods have been called, or after data member has been prepared.

i found quite hard deal when there data member dependencies not obvious, , class needs extended support more features , functionalities. error-prone.

execution speed of code not important in case, code clarity/maintainability/sensibility more important.

if method2 called after method1 class has state. want keep state consistent , methods change/use state should not damage state.

so need incapsulation. incapsulation not how make field private , create setfield() method change state. right answer: object change state. if have setters every single field have unprotected object , control consistent state has leaked.

in practice, re-desing code data set during previous steps only. in case don't worry checking "is data prepared?" each time method2 called.

to avoid untimely calls there several approaches. each has pro , contras. suppose have chain of state0 -> method1 -> state1 -> method2 -> state2 -> method3 -> state3

  • throw exception if object has different state. f.e. inside method1 add if currentstate.differs(state0) throw exception easy implement, way won't in terms of understanding , maintaining project

  • use combination of state , chain-of-responsibility pattern. divide class in several ones , each accept previous 1 input param , return next class in chain. f.e. class0 have method wih signature class1 method1(state0), class1 have class2 method2(class1) , class 2 have state3 method3(class2). nobody call class2.method3 or method1(class3) - not compile. side effect lot of classes. rigid process flow more flexible next option.

  • use template pattern. create processor class process method , make sure class call desired methods. state3 process(state0) { preparestuff(); state1 = method1(state0) somepreparation(state1) state2 = method2(state1) anotherprepare(state2) return method3(state2) } alter process flow subclassing processor , overriding preparation methods. nobody override process(). disadvantage always whole process , can't stop after method2 (in fact can lead leak state , again uncontrolable process) note policy template

in sense both ways incapsulate state of process @ higher level.


there ways implement call dependency. no matter choose have strictly limit possibility call methods anywhere @ random moment.


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -