duplicate codes in state machine design pattern

Hi all.
When I implement my state design pattern,I have sometimes duplicate methods. How can we prevent that?

public class State1:IState{
private StateController sc;
public State1(StateController _sc){
sc=_sc;
}
public void func1(){

}
public void func2(){

}
public void func3(){

}
}
------------------------------------------
public class State2:IState{
private StateController sc;
public State2(StateController _sc){
sc=_sc;
}
public void func1(){

}
public void func2(){

}
public void func3(){

}
}

Suppose some of the functions of the classes have same codes. Totally we can have duplicate codes in a state design pattern

Use the delegate pattern to pull the shared methods into their own types, then your states become composites of the shared delegate types.

Having all states inherit from a base class is another option, but that introduces a rigid hierarchy which may not be desired at this stage.

However, having some duplicated methods is not necessarily an automatic bad thing. It is a smell, but it doesn’t have to indicate a real problem. If those func1/func2/func3 methods hve unique responsibilities, then it might make sense to keep them separate. For example, right now each state may have an OnEnter() method, which, at the moment only does a simple Debug.Log. But, if you can reasonably foresee that the OnEnter methods of your states will eventually be fleshed out to include lots of individual behavior, then a little bit of code duplication may be palatable.

If the functions are truly duplicate, and a full on delegate pattern is too complex (which it probably is). then at the very least you could keep your func1/func2/func3 calls in each state, but have them delegate their internals to utility methods.

Thank you. Can I implement duplicate codes into StateController methods only once? methods that are common in all states like FindClosestEnemy position
I have states like chase,moverandom,escape, etc

which is better: having duplicate code but separate classes or having coupling classes but not duplicate?!

In general I would favor coupling classes to break out functionality into responsibilities. Coupling can always be reduced with interfaces and dtos, but duplicated code is a maintenance issue that can easily fester and grow out of control.

1 Like

My rule of thumb is that I’ll allow a method to be duplicated once without issue, twice with some explanation of why breaking it into its own class is too much effort. But that third time is absolutely forbidden. Once you’ve got 4 of the same method, refactor.

1 Like

Thanks. So I can define several methods in statecontroller and use it from states

yes we can use action,func,delegates and events to reduce coupling classes