Typically the first interview question I’ll ask someone is:
What are the three fundamentals of Object Oriented Programming?
This is amazingly good at weeding out those that aren’t qualified for programming positions. Most will at least start discussing what OO provides you. The three I usually look for are Encapsulation, Inheritance and Polymorphism (but there are others that work as well). Once they express these concepts, I’ll ask for a description of each. Many will simply respond by rote from college courses, but the stand outs really go the extra mile.
Encapsulation conceals implementation details about a class from the users of that class. The classic example is Accessor methods (getters/setters) that hides the underlying data. However, the point of Encapsulation really goes further than just hiding the details, it reduces code duplication. Following Pragmatic Programmers DRY (don’t repeat yourself) here is important. For example (from the book), you might implement a Point2D class that has an X, Y and length.
public class Point2D {
private int x, y, length;
public setX(int x) {
this.x = x;
length = Math.sqrt((x*x) + (y*y));
}
public int getX() {
return x;
}
public setY(int y) {
this.y = y;
length = Math.sqrt((x*x) + (y*y));
}
public int getY() {
return y;
}
public int getLength() {
return length;
}
}
This meets the rules of Encapsulation, by not allowing direct access to the data, but there is a lingering issue living here that goes deeper into the concept. Because “length” is encapsulated with an accessor, we can invoke the DRY principal and use the accessor to calculate length on demand.
public class Point2D {
private int x, y;
public setX(int x) {
this.x = x;
}
public int getX() {
return x;
}
public setY(int y) {
this.y = y;
}
public int getY() {
return y;
}
public int getLength() {
return Math.sqrt((x*x) + (y*y));
}
}
This reduction of duplication does two things, lowers the number of places you need to change code (i.e. setX, setY) and therefore, lowers the likelihood of bugs (less code, less bugs) and improves the Orthogonality of our code.
So, Encapsulation does more than just limit the visibility into a class, it empowers the developer to improve the design of the class.
Meyer’s Uniform Access principle: All services offered by a module should be available through a uniform notation, which does not betray whether they are implemented through storage or through computation.