Flattening attribute access

I’ve always been uncomfortable with certain attribute access lines in my code. Now in some videos and in the literature I’ve come upon hints about what’s going wrong, but I don’t know how to fix them.

The problem is attribute access. Let’s start with the most extreme example:


All I want to do is get the distance from the a fighter ship model to the model of it’s host ship. I understand the problem is that the ship is requesting an attribute it couldn’t know about. The Environment class could, where the nodes are stored (that’s mcglobals.env).

So what’s the solution? Properties? Decorators? Set/get methods?

Thing is I don’t see how those could help. In the Environment and Ship class I still had to do stuff like:

# Environment

def get_distance(from_id, to_id):
	return self.ShipObjects[from_id].ShipModel.getDistance(self.ShipObjects[from_id].ShipModel)
# Ship

mcglobals.env.get_distance(self.ShipBase.ID, self.ShipBase.aiflags["hostedby"])

… which still looks wrong to me. I could get rid of the self.ShipBase stuff, but that’s not the point here.

I don’t see a problem here. What is it that seems wrong to you? Too many dots? I’ve certainly seen longer chains. :wink:


How about this

world.getDistance(world.player.NP, world.target.NP)

Less letters to type -> faster codding, less chances for errors.

I’d go for:

get_distance(from_id, to_id)

(but I’d call it MyGetDistance(from_id, to_id))

world.getDistance(world.player.NP, world.target.NP)

for the OO fetishists :wink:

What you’re experiencing are consequences of a too short pattern design phase.

Think about the following:
-How, where and why get a specific object (thinking of modules and classes)
-How does it interact with others
-Does it use or is it used?

If you answer these to yourself, then you’ll probably get your answer. Also keep in mind that there already are methods for calculating a distance between two PandaNodes.