Shared Interface vs Shared Behavior

Two objects share an interface when they need to respond to the same methods, and they share behavior if they need to take the same (or overlapping) actions in response to the same methods.

Since Python is a dynamically typed language, shared interfaces are implicit. This is called duck typing (because as long as it quacks on command, the calling object doesn’t need to know or care what’s doing the quacking).

My last post went over a shared behavior example, and I’m going to adapt this to a shared-interface-only example.

Here’s the code from the last example, for reference:

class CrewMember
attr_reader :seat_buckled, :name, :blood_type

def initialize(args={})
@name = args[:name] || "Jane Doe"
@blood_type = args[:blood_type]
@seat_buckled = false
end
def liftoff_checklist   
local_checklist << "Buckle Seat Belt" if !seat_buckled
local_checklist
end
def local_checklist
[]
end
end
class Engineer < CrewMember
def local_checklist
["Check space engines"]
end
end
class Pilot < CrewMember
def local_checklist
["Engage warp drive"]
end
end
class ShipCounselor < CrewMember
def local_checklist
["Issue vague, pointless warning"]
end
end

Say Star Fleet gets assimilated by the Borg. We no longer care about crew member names or blood type, because such distinctions are now meaningless. And forget seat belts, since the Borg just sort of plug into the wall.

It was shockingly hard to find a picture of this online.

So what do we get with these shared behaviors stripped away?

class CrewMember

def liftoff_checklist
[]
end
end

Not much of a point inheriting from this anymore, but our subclasses still need to respond to a ‘liftoff_checklist’ interface.

class Engineer
def liftoff_checklist
["Check space engines"]
end
end
class Pilot
def liftoff_checklist
["Engage warp drive"]
end
end
# There's no ships counselor anymore for obvious reasons

Duck typing!

Though if we’re being real it would probably all just be:

class Borg
def the_only_method
['contribute to hive mind']
end
end
Like what you read? Give Nicole McCabe a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.