jeudi 11 mai 2017

Object Orient Design Why we need composition for Bird class?

Recently I was asked a question in an interview to design a bird flight simulator. I went ahead and thought of strategy pattern for the simulator class and attributes like air pressure, wind velocity etc. A method would take a bird object and time and would return x,y,z coordinates. e.g.

class Simulator
 attr_accesor :bird, :air_pressure, :wind_velocity

 def map_coordinates(bird, time)
  ...
 end
 ...
end

and then thought about bird class:

For the bird can fly/Not fly attribute I thought about a boolean variable which would be set at initialization time. For e.g:

class Bird
 attr_accessor :weight, :wing_dimension, :canfly, :height....

 def initialize(weight, wing_dimension, canfly, height)
  @weight = weight
  @wing_dimension = wing_dimension
  @canfly = canfly
  @height = height
 end 
end

My question is from OOD point of view, it says a Bird class should use composition and use a class to encapsulate the properties required in a class. http://ift.tt/2q6W5Wk

So, Do I really need a class to map the canfly behavior? Can't I just have a boolean field to be initialized in this case while creating the Bird object.

Why would not that be a good design? If not, what's the best approach and why?

Aucun commentaire:

Enregistrer un commentaire