Object Oriented Thinking — Part I

Prerequisites :

Terminology :

A bit of background about client!

Client is a fan of mathematics and they want to build an application that can compare two probabilities.

Implementation :

import java.util.Scanner;public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double p1 = scanner.nextDouble();
double p2 = scanner.nextDouble();
if (p1 == p2) {
System.out.println("P1 and P2 are equal");
} else {
System.out.println("P1 and P2 are not equal");
}
}
}
java Main.java
0
1
P1 and P2 are not equal

Retrospect :

Make it better ?

//1. creating a class probability
public class Probability {

//2. creating data member to hold probability value
private final double value;

//3. constructor to create probability object
public Probability(double value)
throws InvalidProbabilityException {
validate(value);
this.value = value;
}
//4. Equality check by accepting another probability
public boolean equals(Probability that) {
if (this == that) return true;
return this.value == that.value;
}
//5. validate probability range [0,...,1]
private void validate(double value)
throws InvalidProbabilityException {
if (value > 1 || value < 0) {
throw new InvalidProbabilityException();
}
}
}

Playing with above code

//Create some objects using above class
Probability probabilityOne = new Probability(1);
Probability probabilityZero = new Probability(0);
//Equate objects
probabilityOne.equals(probabilityZero) => this will return false
//Create some objects using above class
Probability probabilityOne = new Probability(1);
Probability anotherProbabilityOne = new Probability(1);
//Equate objects
probabilityOne.equals(anotherProbabilityOne)
=> this will return true

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store