Pages

Wednesday, November 2, 2016

To be, or not to be

To be, or not to be" is the opening phrase of a soliloquy spoken by Prince Hamlet in the so-called "nunnery scene" of William Shakespeare's play Hamlet.

Although called a soliloquy, Hamlet is far from alone since Ophelia is pretending to read while she waits for Hamlet to notice her, and Claudius and Polonius, who have set Ophelia there in order to overhear their conversation and find out if Hamlet is really mad or only pretending, are hiding behind an arras. Even so, Hamlet seems to consider himself alone. In the speech, Hamlet contemplates death and suicide, bemoaning the pain and unfairness of life but acknowledging that the alternative might be worse. The meaning of the speech is heavily debated but seems concerned with Hamlet's hesitation to directly and immediately avenge his father's murder (discovered in Act I) on his uncle, stepfather, and new king Claudius.
—Wikipedia, To be, or not to be, retrieved on 2 Nov 2016

Java's version of the question:

To be defined static, or not to be defined static

JavaScript's version of the question:

To be defined in the constructor's prototype, or in the body of the constructor

How to decide:

If the value of some property FOO (or the value of some property used to compute the value returned by some method called FOO) may vary from instance to instance of some object of type BAR, then:
  • Java: FOO cannot be static
  • JavaScript: FOO must be defined in the body of the constructor
If the value of some property FOO (or the value of any property used to compute the value returned by some method called FOO) may not vary from instance to instance of some object of type BAR, then:
  • Java: FOO may be static
  • JavaScript: FOO may be defined in the constructor's prototype

Example: Circles and Pi


The value of Pi never varies, but the radius of a Circle does!
So a method called getPi of a Java class called Circle could be defined static but a method called getRadius cannot:
class Circle {
  private double radius;
  Circle(double r) { this.radius = r; }
  static double getPi() { return Math.PI; }
  double getRadius() { return this.radius; }
}
Similarly, a method called getPi of a JavaScript constructor called Circle could be defined in the constructor's prototype, but a method called getRadius must be defined in the body of the constructor itself:
function Circle(radius) {
  this.getRadius = function() { return radius; }
}
Circle.prototype = {
  getPi: function() { return Math.PI; }
}

Trick, or Treat

  • May a Java method called getCircumference of the Circle class above be defined static? If so, what parameter must the method be defined in terms of?
  • May a JavaScript method called getCircumference be defined in the Circle's prototype? If so, how?

To use Java, or to use JavaScript

Can you repeat the question?