Home Segments Index Top Previous Next

401: Mainline

Suppose that you develop a big program around trade structures only to discover that you are more often interested in total trade costs than in prices per share. For efficiency, you might want to switch from a price structure variable to a total_cost structure variable, so that multiplication is not needed when you want a total_cost delivered.

If you work with the information in trade objects using constructors, readers, and writers exclusively, you need only to change the definitions of those constructors, readers, and writers to work with a total_cost structure variable instead of a price structure variable. Instead of computing total_cost from price and number values, you compute price from total_cost and number values:

struct trade {double total_cost; int number;}; 
struct trade* construct_trade (double price, int number) { 
  struct trade *tptr; 
  tptr = (struct trade*) malloc (sizeof (struct trade)); 
  tptr -> total_cost = price * number; 
  tptr -> number = number; 
  return tptr; 
double read_trade_price (struct trade *tptr) { 
  return (tptr -> total_cost) / (tptr -> number); 
int read_trade_number (struct trade *tptr) { 
  return tptr -> number; 
double read_total_cost (struct trade *tptr) { 
  return tptr -> total_cost; 
void write_trade_price (double price, struct trade *tptr) { 
  tptr -> total_cost = price * tptr -> number; 
void write_trade_number (int number, struct trade *tptr) { 
  tptr -> number = number; 
void write_total_cost (double total_cost, struct trade *tptr) { 
  tptr -> total_cost = total_cost;