Menu
CoddyTech

Validated Construction

Lesson 29 of 48 in Coddy's Ruby for Java Developers course.

Java static factory methods and Ruby class singleton methods can give construction meaningful names. Ruby initialize remains the instance setup hook, while the factory is called on the class. Factories can choose valid arguments and return suitable objects without exposing every setup detail to callers.

Java: complete program

import java.util.*;
public class Main {
  static class Mode {
    final boolean automatic;
    Mode(boolean automatic) { this.automatic = automatic; }
    static Mode manual() { return new Mode(false); }
  }

  public static void main(String[] args) {
    System.out.println(Mode.manual().automatic);
  }
}

Ruby: complete program

class Mode
  attr_reader :automatic
  def initialize(automatic)
    @automatic = automatic
  end
  def self.manual
    new(false)
  end
end
puts Mode.manual.automatic
challenge icon

Challenge

Easy

Define Interval.new(low,high), raising ArgumentError when low>high. Provide width (high-low) and include?(value), inclusive at both ends. solve reads low high query; return width and boolean separated by a space, or invalid.

Return text from solve(input) without printing. The locked driver prints the returned text with one final newline and checks required public APIs independently.

Your code goes in exercise.rb, interval.rb. main.rb holds the supplied input/output code and cannot be edited.

Try it yourself

require_relative 'exercise'
require_relative 'interval'
def check(value)
  raise 'Public API check failed' unless value
end
r = Interval.new(-4, 2)
check(r.width == 6 && r.include?(-4) && !r.include?(3))
begin
  Interval.new(2, 1)
  raise "Expected rejection"
rescue ArgumentError
end

puts solve(STDIN.read)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Ruby for Java Developers

Practice on your own: Online Ruby compiler