Skip to main content

Immutable object example

After reading some chapters of  the book "Design patterns" (Navrhove vzory) from czech author Rudolf Pecinovsky, I decided to test my own examples of usage of the design patterns mentioned in this book. In this first post I will publish here a code that is an example of usage of the immutable objects.

As you maybe already know - the immutable objects cannot be changed after their creation. That can be very useful in some situation. In this particular example (which is kind of a english copy of the czech example mentioned in the book "Navrhove vzory") the object, which represents fraction and its operations is created. The main thing here is, that during every operation (method) new instance of class Fraction is created instead of modifying the existing Fraction instance.

Immutable objects can be very useful in concurrent applications - their state cannot be changed, so there is no way they could be corrupted by other threads.

Code example:

 
package com.shimon.immutable;

import com.shimon.immutable.common.Functions;

/**
 * This class defines fractions and needed operations with fractions - addition, subtraction, multiplication and division.
 * @author shimon
 *
 */
public class Fraction extends Number{
 /**
  * 
  */
 private static final long serialVersionUID = 2522259263216154175L;
 private final int numerator;
 private final int denominator;
 
 /**
  * Creates new instance of class Fraction with numerator and denominator passed as parameters.
  * @param n - numerator of new fraction
  * @param d - denominator of new fraction
  */
 public Fraction (int n, int d){
  if (d == 0){
   throw new IllegalArgumentException("Denominator cannot be zero.");
  }
  int divisor = Functions.gcd(n, d);
  if (d < 0){
   n = -n;
   d = -d;
  }
  
  numerator = n / divisor;
  denominator = d / divisor;
 }
 
 public Fraction(Fraction f){
  numerator = f.numerator;
  denominator = f.denominator;
 }
 
 public Fraction(int number){
  numerator = number;
  denominator = 1;
 }
 
 /**
  * Adds a fraction passed as parameter to the Fraction instance.
  * @param f- fraction to add
  * @return
  */
 public Fraction plus(Fraction f){
  return new Fraction(numerator * f.denominator + f.numerator * denominator, denominator * f.denominator);
 }
 
 public Fraction plus (int number){
  return new Fraction(numerator + number * denominator, denominator);
 }
 
 /**
  * Substracts fraction passed as parameter from the Fraction instance
  * @param f - fraction to substract
  * @return
  */
 public Fraction minus(Fraction f){
  return new Fraction(numerator * f.denominator - f.numerator * denominator, denominator * f.denominator);
 }
 
 public Fraction minus(int number){
  return new Fraction(numerator - number * denominator, denominator);
 }
 
 /**
  * Subtracts the fraction from the number, which is passed to the method as a parameter.
  * @param number - number to subtract from
  * @return
  */
 public Fraction subtractFrom(int number){
  return new Fraction(number * denominator - numerator, denominator);
 }
 
 /**
  * Multiplies the fraction with fraction passed as parameter
  * @param f - fraction to multiply with
  * @return
  */
 public Fraction multiply(Fraction f){
  return new Fraction(numerator * f.numerator,denominator * f.denominator);
 }
 
 public Fraction multiply(int number){
  return new Fraction(number * numerator, denominator);
 }
 
 /**
  * Divides the fraction with the fraction passed as a parameter
  * @param f - fraction to divide by
  * @return
  */
 public Fraction devide(Fraction f){
  return new Fraction(numerator * f.denominator, denominator * f.numerator);
 }
 
 public Fraction devide(int number){
  return new Fraction (numerator, denominator * number);
 }
 
 /**
  * Divides the number with a fraction
  * @param number - number to be divided
  * @return
  */
 public Fraction devideNumber(int number){
  return new Fraction(denominator * number, numerator);
 }
 
 @Override
 public int intValue() {
  return numerator / denominator;
 }

 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + denominator;
  result = prime * result + numerator;
  return result;
 }

 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  Fraction other = (Fraction) obj;
  if (denominator != other.denominator)
   return false;
  if (numerator != other.numerator)
   return false;
  return true;
 }

 @Override
 public long longValue() {
  return (long) numerator / denominator;
 }

 @Override
 public float floatValue() {
  return (float) numerator / denominator;
 }

 @Override
 public double doubleValue() {
  return (double) numerator / denominator;
 }
 
 public int getNumerator() {
  return numerator;
 }

 public int getDenominator() {
  return denominator;
 }

}

}
}
Functions class:
 
package com.shimon.immutable.common;

/**
 * This class is a library class, its methods solve the calculation of greatest common divisor and least common multiple.
 * @author shimon
 *
 */
public final class Functions {
 
 /**
  * Private constructor.
  */
 private Functions(){}
 
 /**
  * Returns greatest common divisor of two numbers.
  * @param i1 - First number
  * @param i2 - Second number
  * @return - gcd
  */
 public static int gcd(int i1, int i2){
  i1 = Math.abs(i1);
  i2 = Math.abs(i2);
  
  while (i2 > 0){
   int pom = i1 % i2;
   i1 = i2;
   i2 = pom;
  }
  return i1;
 }
 
 /**
  * Least common multiple of two numbers.
  * @param i1 - First number
  * @param i2 - Second number
  * @return lcm
  */
 public static int lcm(int i1, int i2){
  if ((i1 == 0) || (i2 == 0))
   return 0;
  return i2 * Math.abs(i1) / gcd(i1,i2);
 }
}
Test class:
 
package com.shimon.immutable;

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;

public class FractionTest {
 
 private Fraction f;

 @Before
 public void setUp() throws Exception {
  f = new Fraction(3, 5);
 }
 
 @Test
 public void testPlus(){
  Fraction result = f.plus(new Fraction(1,2));
  assertEquals(new Fraction(11,10), result);
 }
 
 @Test
 public void testMinus(){
  Fraction result = f.minus(new Fraction(2,10));
  assertEquals(new Fraction(2,5), result);
 }
 
 @Test
 public void testDivision(){
  Fraction result = f.devide(new Fraction(6,4));
  assertEquals(new Fraction(6,15), result);
 }
 
 @Test
 public void testMutliplication(){
  Fraction result = f.multiply(new Fraction(5,6));
  assertEquals(new Fraction(1,2), result);
 }

}

Comments

Popular posts from this blog

Servant (Design Pattern) in Java - example

The servant design pattern - or better idiom is used to provide the functionality (methods) to some group of objects. This functionality is common for all these object and therefor should not be repeated in every of these classes.
The object, which should be served is passed to the method of servant as a parameter. All the served objects should implement common interface - in this particular example IMovable interface. Also the type of argument passed to the servand method is of type IMovable.
The servant in this example is used to move objects from one position to another. In real life application these methods should change the position of object in small steps so that the final change would look like smooth movement (animation). In my servant method, only some message are printed instead for demonstration.
IMovable interface:
package com.shimon.servant; import java.awt.Point; /** * Movable interface * @author shimon * */ public interface IMovable { public void setPosition(P…

Livigno 2017

Po niekoľkých rokoch, kedy sme skončili v lete na dovolenke niekde pri Jadrane, sme si minulý rok so Zuzkou povedali, že ďalšia dovolenka musí byť iná. K tomu sa pridal obmedzený počet dní dovolenky, ktoré sme mohli cez leto využiť. Takže sme zvažovali, či vôbec ísť k moru, a aké sú ďalšie možné varianty. Po zavrhnutí niekoľkých iných alternatív sme sa nakoniec rozhodli pre "cyklo" dovolenku v horách, a ako je zrejmé už z nadpisu, v talianskom alpskom mestečku Livigno. Zastávka v Innsbrucku Na dovolenku sme chceli využiť 2 české štátne sviatky v priebehu prvého júlového týždňa, preto sme dovolenku plánovalí od soboty do nedele. Až týždeň pred odjazdom sme si uvedomili, že by sme takto zabili celú sobotu cestovaním a tak sme si povedali, že vyrazíme už v piatok po práci a zastavíme sa v niektorom z rakúskych miest po ceste. Do úvahy pripadali asi len Salzburg a Innsbruck. Keďže Innsbruch je k Švajčiarsku (cez ktoré vedie najkratšia cesta do Livigna) najbližšie, zabookovali sm…

Optimise your PDF for e-book reader

Some of you e-book enthusiasts maybe also ran into a problem when trying to read some PDF that was not optimised for reading on e-book reader (e.g. Kindle). The margins are too wide, pictures are too small, etc.

Luckily there is one very useful (command line) tool that helps you prepare your PDF document for reading on your e-book. It's name is k2pdfopt (not very lucky name I think). This utility scans the content of the provided PDF document, reorganises the columns (if there are multiple) and improves overall document readability.

Here is a saple of document before and after the optimisation:



To optimise the document use following command:

If you use unix based system (Linux, MacOS) change the downloaded k2pdfopt file to exacutable by running `chmod +x k2pdfopt`Run the k2pdfopt commang with PDF you want to optimise as parameter: `k2pdfopt /path/to/your/file.pdf`Use `d` option to choose desired target deviceYou can check other options - they may be useful for youHit `Enter` to opt…