Is it a feature envy code smell if a state class within the state design pattern uses a field object of the context class to call a method?

48 views Asked by At

I am using the state design pattern where I have a context class and a bunch of state classes. The context class has as class fields the state itself and also a few objects that are instances of other classes that the context class has. These objects have methods that I need to call within the context class but their calling depends on the state thus the behavior of the context class will be different per state as the purpose of this design pattern is.

My context class looks something like this:

class Context:
    def __init__(self, obj1, obj2):  
        self.state = StateOne(self)
        self.obj1 = obj1 
        self.obj2 = obj2

Then in the states classes I need to access methods that belong to the obj1 and obj2. I don't know whether to do that in the context class itself or call them directly in the state classes:

# OPTION 1: calling them in the context class directly
def method_obj1(self):
   self.obj1.do_method()

and then call that inside the state class

class StateOne:  
    def __init__(self, context)
        self.context = context
                               
    def behaviour1(self)
        self.context.method_obj1()

Or I do this which I am not sure if this is feature envy code smell:

# OPTION 2: calling directly the object field in the state class 
class StateOne:
    def __init__(self, context)
        self.context = context

    def behaviour1(self):
        self.context.ob1.do_method()

Or maybe both of these options are wrong? I am simply finding it hard to grasp this clearly in order to decide how to implement this desired behaviour.

0

There are 0 answers