9.5 Methods with Arguments and Result

One last possibility is the combination of arguments with a result. One common pitfall: although a method can have many arguments, it can only have one result.

The next example implements a move method. This method will move a circle by passing a value as an argument. This value will be added to the currrent position, but only as long as the result would not be outside of the screen. By returning a bool as a result, we can let the application know if movement succeeded.

 
class movingCircle { 
  Circle c    ; 
  Vec2   speed; 
 
5  void init(float r, Vec2 pos, Vec2 speed) { 
    c.r         = r    ; 
    c.pos       = pos  ; 
    this->speed = speed; 
  } 
10 
  float getRadius() { 
    return c.r; 
  } 
 
15  bool move(Vec2 pos) { 
    if(Cuts(c.pos + pos, D.viewRect())) { 
      c.pos += pos; 
      return true
    } else { 
20      return false
    } 
  } 
} 
 
25// somewhere in your application 
movingCircle mc; 
Vec2 p(0, 0); 
mc.init(0.1, p, Vec2(0.3, -0.5)); 
if( !mc.move(mc.speed * Time.d()) ) { 
30  // do something when failed 
}  

Exercise
Add the move method to your class. The application must use this method to move the circle. This method indicates wether or not the movement was a success, so you can remove the application code to keep the circle within the screen boundaries. If the method returns false, simple call the reset method to put the circle back in the middle.

It is still possible to simplify move even further. We already know movement will always be the same. So we don’t actually need an argument at all! The movement can be done with the information available in the class itself. (speed and the time delta)