Introducing JSR 354 The Money & Currency API

Nov. 11, 2016
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
Introducing JSR 354 The Money & Currency API
1 of 50

More Related Content

Similar to Introducing JSR 354 The Money & Currency API

html5html5
html5NebberCracker01
Introduccion a HTML5Introduccion a HTML5
Introduccion a HTML5Pablo Garaizar
Event Sourcing - You are doing it wrong @ DevoxxEvent Sourcing - You are doing it wrong @ Devoxx
Event Sourcing - You are doing it wrong @ DevoxxDavid Schmitz
What Web Developers Need to Know to Develop Windows 8 AppsWhat Web Developers Need to Know to Develop Windows 8 Apps
What Web Developers Need to Know to Develop Windows 8 AppsDoris Chen
WCRI 2015 I18N L10NWCRI 2015 I18N L10N
WCRI 2015 I18N L10NDave McHale
Project: Call Center ManagementProject: Call Center Management
Project: Call Center Managementpritamkumar

Recently uploaded

Recommendation Modeling with Impression Data at NetflixRecommendation Modeling with Impression Data at Netflix
Recommendation Modeling with Impression Data at NetflixJiangwei Pan
Product Research PresentationProduct Research Presentation
Product Research PresentationDeahJadeArellano
Cloud Study Jam ppt.pptxCloud Study Jam ppt.pptx
Cloud Study Jam ppt.pptxPoorabpatel
Omada Pitch DeckOmada Pitch Deck
Omada Pitch Decksjcobrien
How resolve Gem dependencies in your code?How resolve Gem dependencies in your code?
How resolve Gem dependencies in your code?Hiroshi SHIBATA
Brisbane MuleSoft Meetup 13 MuleSoft Maven and Managing Dependencies Part 1.pptxBrisbane MuleSoft Meetup 13 MuleSoft Maven and Managing Dependencies Part 1.pptx
Brisbane MuleSoft Meetup 13 MuleSoft Maven and Managing Dependencies Part 1.pptxBrianFraser29

Recently uploaded(20)

Introducing JSR 354 The Money & Currency API

Editor's Notes

  1. Good afternoon everybody and welcome to our talk about JSR 354 – The Money and Currency API.
  2. First of all, who are we? Well, my name is Wim van Haaren… … and my name is Jeroen Burggraaf. We are the founders of Tritales, a company in the Netherlands. Together we have over 35 years of software development experience in both backend as well as frontend development. Lets start with our talk about the money and currency API.
  3. Let’s quickly get to the reason why we are standing here. Why do we want to talk about a JSR about Money and Currency?
  4. Well, a lot of applications have to deal with money. So why do the mainstream programming languages not provide data types for it? Especially since this has caused of lots of problems…
  5. Furthermore, we as programmers keep on reinventing the wheel over and over again… To show some of the problems we could run into, we are going to start by having a look at how in the past we would typically go about dealing with money.
  6. I guess you all know, that money is made up of two parts: it has a numerical value and it has a currency. But since the JDK doesn't provide a standard representation of money, how could we as developers represent it?
  7. As a beginning developer our first attempt would probably to use a double. <KLIK> But then the output would not be quite what we expected. <KLIK> So, are floating points broken in Java? No, it's not, but this is how IEEE-754 standard works.
  8. Let’s use integer types as our next attempt. If we are using a long, we will first have to convert the value of our money to cents. However, this solution does have some problems with readability and flexibility. Let’s say for example that we’ve got a Product class with a name and a value attribute.
  9. And suppose we have two products defined somewhere in our system. <KLIK> And somewhere our colleague is going to sum up the two values. <KLIK> As you can imagine, it is very easy to go wrong with this design where we could easily forget the fact that we have to convert euros into cents.
  10. Lets rewrite the last example using BigDecimal. BigDecimal makes our lives easier because it sounds more natural to say that a product is worth 9 euros rather than 900 cents. <KLIK> Now our co-worker won’t be confused about the value. So this is exactly what we want. However, there is a very important factor missing in our design. <KLIK> Because most of the time, the number 9 has no real meaning without a currency.
  11. If our program deals with a single currency then we are totally fine and we don’t need to model currencies. However, this is not the case most of the time. So let's add a field of type String to hold the currency. Well, this is clearly not a good design because it's not type-safe. The String is not validated and could be anything that is not a valid currency.
  12. We can make the currency type-safe by introducing an enum. Now we have a fixed set of currencies so we cannot use an incorrect currency. The enum, however, is still very limited and lacks various aspects like internationalization and standardization like ISO-4217. ISO 4217 is an international standard that represents currencies as 3-character codes.
  13. A more advanced approach is to use the java.util.Currency class which is available in the JDK. It is type-safe and support the ISO currency standard. So we improve our product design by using it.
  14. A Currency can be instantiated by providing an ISO currency code. So now we have a suitable amount and currency type.
  15. However, to make it useful we need operations like addition, subtraction etc. and we need to take into account that the currencies of our two products might be different so it is essential to do some validation before operating on the amount values. We will end up with a lot of utility classes and it is important not to forget to use them.
  16. Adding an abstraction for representing money becomes more and more obvious after we try all these tricks. Martin Fowler wrote an article describing an abstraction for representing money that solves the issues we have seen. This Money class should be the only type that is responsible for dealing with money and encapsulates the amount and currency and provides utility operations.
  17. So let’s use this Money class and add it to the product. <<click>> Next we instantiate our products by providing a Money instances… <<click>> and now we can apply operations on the money instances. This raises the question why such a Money class is still not available in the JDK yet.
  18. Let’s summarize the motivation to add a Money class. Monetary amounts are a key feature of many applications and there is no standard type yet. There are some quirks with ISO 4217. It contains some ambiguous currency codes like the central African franc which has two variants used in different areas. Furthermore, historical currencies are missing. Virtual currencies like Bitcoin are not supported. Conversion and arithmetic is missing. Formatting is not provided.
  19. So we have seen problems and missing functionality in the JDK. This lead to the development of JSR 354, the money and currency API which started in 2012 and was finished in 2015. The new JSR is targeted for JDK 9. A standalone API will be available which can be used in JDK 7 and 8 in combination with the ‘Moneta’ reference implementation. Wim will now talk about the details of this new API.
  20. So let’s have a closer look at the JSR 354 Specification. As we’ve seen Money is represented by a value and by its currency.
  21. Currencies are represented by the CurrencyUnit interface. And implementations of this interface are required to be immutable and thread-safe A CurrencyUnit can be constructed in a multitude of ways. The easiest two ways are using the Currency code, which is a three character string. Or by passing in the Locale.
  22. Amounts are represented by the MonetaryAmount interface. Again, implementations are required to be immutable and thread-safe   There are alotof methods defined by the interface. But bascially there are four groups. 1) boolean operators like isGreatherThan() or isPositive(). 2) arithmetic operator methods like add() and divide(). 3) a method to get the Currency for this amount. 4) finally there is the query() method about which Jeroen will tell you more in a minute.
  23. Amounts are generated using a MontaryAmountFactory. The simplest case, you would use the default factory. <klik> But using the RI Moneta, creating money is even simpler. Just call one of the static methods and provide it with a value and a currency
  24. To retrieve the numerical value of a money amount, all you have to do is call the method getNumber() which will return a NumberValue object. NumberValue extends java.lang.Number and as a result it can easily be converted to primitive numerical types (e.g. int , long , float , double , short , byte ).
  25. Let’s talk about monetary operators and queries.
  26. The JSR provides two functional interfaces: MonetaryOperator and MonetaryQuery. MonetaryOperator takes a monetary amount, operates on it and produces a new monetary amount. MonetaryQuery provides queries for example for retrieving the fractional parts (cents). Both MonetaryOperator and MonetaryQuery can be instantiated using a lamba expression.
  27. The Monetary operator accepts a monetary amount and returns a new monetary amount. In this example we create an amount of 10 euro’s which we want to multiply by 2. We create a monetary operator to do this. There are two ways to apply it, either use the ‘apply’ method of the operator with the amount as argument or use the ‘with’ method of the amount with the operator as argument.
  28. Similar to MonetaryOperator, MonetaryQuery is a functional interface. It accepts a monetary amount and returns a generic type. You can perform queries on a monetary amount such as getting the currency code or the number of fraction digits. Again there are two ways to apply it.
  29. One of the goals of the JSR was to make formatting simple and flexible, and to overcome problems with the current Java formatting options, especially the lack of thread safety.
  30. To do so, the MonetaryAmountFormat was introduced. There are several methods defined by the interface but for now we’ll take a quick look at format().
  31. Converting a MonetaryAmount to a textual representation is very easy. Just get your hands on a formatter from the MonetaryFormats singelton, and then call the format() method on it… For more control over the formatting you can also use QueryBuilders….
  32. If the standard formats don’t suit you, you can always use custom formats. Here we see one possible example using a DecimalFormatQueryBuilder.
  33. Conversion is the process of changing the currency of a monetary amount by applying an exchange rate. The exchange rate is the ratio between one currency and the other. The process of conversion is important when dealing with different international countries and currencies. As an example, let’s try to add two amounts with different currencies. What happens? <<click>> A MonetaryException is raised since the currencies don’t match. So before we can add these amounts, we have to make sure both amounts have the same currency by applying an exchange rate.
  34. In order to apply an exchange rate we use an exchange rate provider. In this example we create such a provider and then apply it to the euro amount to convert it to a US dollar amount. After this we can add the two amounts without an exception. The exchange rate in this example is retrieved from the European Central Bank. It is also possible to retrieve the exchange rates from the International Monetary Fund and to get the currency on historic dates.
  35. As an example we use the date of May 10th 2016 and try to get the exchange rate to convert to a US dollar amount. Fortunately this day is on a Tuesday and an exchange rate is available, otherwise an exception would have been thrown.
  36. JSR354 was developed under Java 8, and so it uses Java 8 functionality alot. The RI Moneta provides some higher order functions in the MonetaryFunctions class that help you when working with Streams. Let’s have a look at some examples…
  37. There are several functions available for sorting. Here, we see an example to sort alphabetically, and another to sort by the value. These sorting functions will not factor in exchange rates. In other words, ten Euros will be considered equal to ten US Dollars.
  38. To sort based on the exchange rate, an ExchangeRateProvider must be provided.
  39. TODO OUTPUT It is also possible to combine multiple sorters. The Comparator.thenComparing() method can be used to chain multiple sorting comparators. Essentially, the secondary comparator will be applied when two values are equal according to the first comparator.
  40. Reduce, also known as fold , is a higher order function that, when applied on a stream, results in a value or none. For example, sum, average, min, and max. As an example we’ll take a look at sum(). The average(), min() and max() methods work similarly.
  41. Sum is a reduction method. Given a stream of MonetaryAmount, it returns the sum of its elements.
  42. If we want to sum up amounts with different currencies, an exception will be thrown to signal that a currency mismatch has occured.
  43. To avoid that, an ExchangeRateProvider must be provided. And now we can sum up amounts with different currencies.
  44. Let’s talk about predicates. As you will remember, a predicate is a higher order function that takes a value and results in a Boolean. It can be used for filtering a collection. The moneta reference implementation provides several predicates on a monetary amount value or currency.
  45. Here we show some example of currency predicates. We create an array of two US dollar amounts and one euro amount. We use an isCurrency predicate to get all US dollar amounts. Next a predicate to determine if there is at least one US dollar amount in the collection and a predicate to determine if all amounts in the collection are US dollar amounts.
  46. Next we show a couple of predicates that act on the monetary amount value. Again we create an array of monetary amounts and filter on amounts greater than zero. We also use a matcher to verify that there is at least one amount greater than zero.
  47. We’ve reached the end of our presentation about the money and currency API. We will summarize what we have discussed. We saw that there is currently no proper support for monetary amounts in the JDK. JSR 354 fixes this in JDK 9. For JDK 8 and before a standalone API is provided that can be used in combination with the moneta reference implementation. The JSR provides a monetary amount class, monetary operators and queries, formatters, conversions, sorting, reduction, predicates, grouping and filtering.
  48. Of course these 15 minutes are too short to cover the complete JSR. The following references provide more information about the money and currency API. Soon after the conference we will make the presentation available on slideshare. Visit our website for the link.
  49. Thanks for attending our presentation. If you have any questions please come over to discuss them.