2
\$\begingroup\$

Program that cleans up user-entered phone numbers so that they can be sent SMS messages. The rules are as follows:

  • If the phone number is less than 10 digits assume that it is bad
    number
  • If the phone number is 10 digits assume that it is good
  • If the phone number is 11 digits and the first number is 1, trim the 1 and use the last 10 digits
  • If the phone number is 11 digits and the first number is not 1, then it is a bad number
  • If the phone number is more than 11 digits assume that it is a bad number

Here is the gist with correspondent specs.

The solution that I've came up with:

class PhoneNumber(phone: String) {

  def number = if(valid_phone) clean_phone else "0000000000"

  def areaCode = clean_phone.take(3)

  override def toString = s"($areaCode) ${clean_phone.substring(3,6)}-${clean_phone.takeRight(4)}"

  private def valid_phone = clean_phone.length == 10

  private val clean_phone = {
    val clean_number = phone.filter(_.isDigit)
    if (clean_number.length == 11 && clean_number(0) == '1') clean_number.tail else clean_number
  }

}

Here is a couple of questions that I have:

  • Should I always use val instead of def when the return value is not going to change and I can avoid multiple calculation of the same thing?
  • Why am I getting an exception when I try to change def valid_phone to a val? Its about Java Null Pointer Exception.
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

This is a fairly small piece of code and we don't see how it's used, so there are some points where it's hard to know whether or not other approaches might be useful. For example, in a U.S. phone number, the second set of three digits are called the prefix (or sometimes exchange) and the final set of four digits is called the line number. Sometimes this is relevant, and sometimes it isn't.

The decision to precompute a value that is constant is a factor of the cost to compute it times the frequency that it is used. However, worrying about the cost for something as small as a phone number is probably premature optimization. Write whatever seems the cleanest and most straightforward, and worry about it later if, and only if, it causes performance problems in your application.

The reason why changing valid_phone to a val gives a NullPointerException is a little, but important detail that new Scala developers sometimes forget. In Scala, a class definition is also the primary constructor for instances of that class. In the code above, if you change valid_phone to a val, then at the time the line is evaluated, the value of clean_phone has not been initialized and is null. If you want to make valid_phone a val, then you have to put it after clean_phone.

Otherwise, the code seems fine.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.