O'Reilly logo

Programming C# 4.0 by Jesse Liberty, Matthew Adams, Ian Griffiths

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Defining Methods

When deciding what methods a class might need, we generally scan our specifications or scenarios for verbs that relate to the object of that class. If we look back at the ATC system description at the beginning of this chapter, we can see several plane-related actions, to do with granting permissions to land and permissions to take off. But do we need functions on the Plane class to deal with that? Possibly not. It might be better to deal with that in another part of the model, to do with our ground control, runways, and runway management (that, you’ll be pleased to hear, we won’t be building).

But we will periodically need to update the position of all the planes. This involves changing the state of the plane—we will need to modify its Position. And it’s a change of state whose details depend on the existing state—we need to take the direction and speed into account. This sounds like a good candidate for a method that the Plane class should offer. Example 3-39 shows the code to add inside the class.

Example 3-39. A method

public void UpdatePosition(double minutesToAdvance) { double hours = minutesToAdvance / 60.0; double milesMoved = SpeedInMilesPerHour * hours; double milesToTower = Position.Distance; if (Direction == DirectionOfApproach.Approaching) { milesToTower -= milesMoved; if (milesToTower < 0) { // We've arrived! milesToTower = 0; } } else { milesToTower += milesMoved; } PolarPoint3D newPosition = new PolarPoint3D( milesToTower, Position.Angle, Position.Altitude); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required