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…

Hrebeňovka Nízkych Tatier za 4 dni

Nízke Tatry som ešte do nášho presunu do Žiliny a následneho sťahovania do Brna poznal z našich pohorí asi najlepšie. V dobe keď som ešte žil v Brezne ma myšlienka hrebeňovky príliš nenadchýnala, predsa len som to mal všetko za domom (takže tam môžem ísť kedykoľvek :). Ako to už ale väčšinou býva, človek si uvedomí čo mal, až keď to stratí - našťastie to nebola v tomto prípade žiadna tragická (či trvalá) strata, a tak sme sa spolu s Lukášom a Maťom rozhodli využiť tohoročné nádherné letné počasie na prechod z Telgártu na Donovaly po červenej značke a teda po hrebeni.

Kto nechce čítať ďalej a chce si pozrieť len fotky, nech pokračuje tu.


Vstávanie, cestovanie a ostrý štart Jednou z koplikovanejších otázok, bola práve otázka presunu zo Žiliny na Telgárt. Túru je potrebné začať čím skôr a preto do úvahy prichádzali len asi 2 spoje z Banskej Bystrici s prestupom v Brezne. Každopádne to pre nás znamenalo nastaviť si budík na 3:15, aby bolo reálne stihnúť autobus o pol šiestej ráno v Bystri…

Thajsko 2018 - Bangkok

Po minuloročnej dovolenkovej abstinencii sme si chceli so Zuzkou tento rok napraviť chuť nejakou exotickejšou destináciou. Podmienkami bolo, aby tam bolo teplo aj vtedy, keď je u nás ešte stále zima a aby sa tam dal robiť windsurfing. Druhá podmienka nejak začala s postupom času strácať na dôležitosti a výsledkom nakoniec bola 3 týždňová dovolenka v Thajsku.
Tentokrát som si povedal, že blog budem písať priebežne, aby boli dojmy čo najčerstvejšie. Ako asi každý kto bol v Thajsku sme začali našu cestu v Bangkoku. No, aby som bol presný, s 3 hodinovou prestávkou na najluxusnejšom letisku, aké som zatiaľ videl - v katarskej Dohe (nuž, nafta očividne stále vynáša). Aby sme využili hneď prvý večer, ubytovali sme sa v Bangkoku pomerne blízko k ulici Kao San, na ktorej sa koná slávny Kao San night market. Hneď po príchode sme sa tam vydali. Zážitok to bol teda intenzívny. 
Z každej strany na vás niekto máva nejakou ceduľou a pozýva vás na jedlo, drinky, jazdu tuktukom alebo čokoľvek iné. Za…