Data Validation with Member Functions

So far, we haven't really gained anything by providing member functions to access the data. Having the member functions provided data validation is a start:
// the implementation for Employee

void Employee::setName(char first[], char last[])
{
  if (strlen(first) > 9)     // if too long, truncate
  {
    strncpy(firstName, first, 9);
    firstName[9] = '\0';
  }
  else
    strcpy(firstName, first);

  if (strlen(last) > 11)     // if too long, truncate
  {
    strncpy(lastName, last, 11);
    lastName[11] = '\0';
  }
  else
    strcpy(lastName, last);
}

void Employee::setSalary(float newSalary)
{
  if (newSalary < 0.0f)   // make sure salary >= 0.0
    salary = 0.0f;
  else
    salary = newSalary;
}

void Employee::setYears(int numYears)
{
  if (numYears < 0)      // make sure years >= 0
    years = 0;
  else
    years = numYears;
}
Previous page
Next page

Back to Index
Back to Outline