id/email
password
forgot password | create account
about | help | code help+videos | done | prefs
CodingBat code practice

gaurav.gupta@mq.edu.au delegation

A function should have one specific responsibility, not too many. For example, the following function returns true if the passed String is purely alphabetic, but is bulky.

boolean isAlpha(String s) {
  for(int i=0; i < s.length(); i++) {
    if(!(s.charAt(i) >= 'a' && s.charAt(i) <= 'z')) {
      if(!(s.charAt(i) >= 'A' && s.charAt(i) <= 'Z')) {
        return false;
      }
    }
  }
  return true;
}

Instead, it would be better to delegate it to smaller functions, each having a very specific job, and then use them to solve the more complex problem.

boolean isLowerCase(char ch) {
  return ch >= 'a' && ch <= 'z';
}

boolean isUpperCase(char ch) {
  return ch >= 'A' && ch <= 'Z';
}

boolean isAlphabet(char ch) {
  return isLowerCase(ch) || isUpperCase(ch);
}

boolean isAlpha(String s) {
  for (int i=0; i < s.length(); i++) {
    if (!isAlphabet(s.charAt(i))) {
      return false;
    }
  }
  return true;
}

Benefits include,

1. Easier to code.

2. Easier to debug and isolate issues.

3. Easier to maintain.

4. Easier to reuse.

-------

Level 1

- isPalindrome H   - overlap H  

Level 2

- occursExactlyOnce H  

Level 3

- same H  
Authoring docs

Copyright Nick Parlante 2017 - privacy