Refactoring code using state pattern