Thursday, April 24, 2008

Pure functions

To its detriment and yours, the Java language makes no distinction between a pure function, and any plain old subroutine. Even in the core libraries, the two are freely intermingled, with no obvious distinguishing characteristic. Yet we can all benefit from striving to make this distinction clear in our own code.

By "pure function" I mean a function in the mathematical sense: it performs a calculation with no observable side-effects, and its result depends only on its arguments. Invoke it again on the same instance (or Class if static), and with the same arguments in the same states, and you must always get the same answer.

What are some advantages of pure functions?

  • They're testable
  • They're thread-safe (though not necessarily "thread-correct", more on this later)
  • They're deterministic
  • They never need to be mocked out*
  • They're easier to understand and reason about
  • They're "referentially transparent," so they can be "memoized" (more on this later)

They're the easy kind of functions to work with, just like immutables are the easy variety of data objects.

(*About this particular claim. Have you ever felt compelled to test how your class behaves if the implementation of integer addition were to change? I doubt it, unless you're just plain batshit crazy, or a mathematician (but I repeat myself). In rare cases, if a pure function is very expensive, you may want to mock it anyway just to make your test runs faster. But you didn't "need" to do it.)

When is a function pure?

All its dependencies must be pure functions themselves (or constants, which are basically just pure functions that have no arguments). Impurity, just like it sounds, is a contaminant. If your method calls eight other methods, and just one of those calls a method which sometimes calls a method which uses System.currentTimeMillis(), kaboom: your function is not pure.

So a method which invokes new Random(5) may still be pure (as guaranteed by that class's specification), while one that invokes new Random() certainly is not. Collections.shuffle(), the two-argument form, is pure, while Collections.shuffle() the one-argument form is not. (wait, duh, neither is pure, because they mutate the passed-in list! but maybe you see the point anyway?) Now you see the "intermingling" I was bemoaning before!

What are the most common sources of impurity in my code?

Some I can think of:
  • mutable state
  • the system clock
  • I/O

I'm sure there are more. Help me out here: what others can you think of?

Are impure functions evil?

No, of course not. If they were, I would never be able to write any, as it would be against company policy. They're simply very different from their pure cousins, and more challenging to work with and to test. Keeping your functions pure, like keeping your value objects immutable, just gives you less to worry about. (Remember that hit song "Mo' Mutatin', Mo' Problems?" Toootally analogous to that. Listen to Biggie, he knew.)

How to deal with impurity?

I've told you that the system clock is a contaminant, that makes everything it touches impure. But, of course, some of your business logic probably needs to know the current time. Are you just hopelessly contaminated as well?

No! You have at your disposal a chlorine tablet called dependency injection! (You just knew it would come to that, didn't you?)


  public class SignUtils {
public static String getCurrentMessage() {
Instant now = new Instant(); // automatically set to now
return someCalculation(now) ? "OPEN" : "CLOSED";

After (simplified):

  public class SignController {
@Inject Clock clock;
public static String getCurrentMessage() {
Instant now =;
return someCalculation(now) ? "OPEN" : "CLOSED";

The result is a function which can be either pure or impure depending on what dependencies are provided for it. In "real life", you need it to be impure, and return a different result at 9:01 than it did at 8:59. But this nondeterminism has now been walled off behind an interface. Because the result of getCurrentMessage() itself now depends only on the states of its arguments (none) and the state of its instance, it will always be just as pure as its provided clock instance is. Now the code is testable, because we properly isolated the impurity.

In summary:
  • Pay attention to the difference between your pure and impure functions.
  • Use dependency injection to limit the damage radius of impure functions.
  • If you're designing the Next Great Language, ferchrissakes handle these two things differently. Don't make the system time available via a simple static method call.

Thanks for reading. Let me know if this kind of post is helpful to you!


Foodberg said...

Funny, I thought you were going to get to language features that help separate pure functions from impure ones, possibly by introducing another annotation for such pure functions, or waxing about static analysis (which would be difficult with your injection example)

Annotations wouldn't really work of course, and would also burden _everyone_ with Yet Another Annotation.

Finally, while the Clock abstraction is probably useful, I've personally never had that much of a need for it. Then again, you're working on the Date & Time JSR.

Srikanth said...

Hi Kevin, this post was definitely very interesting. I didn't get the answer before looking at your example (my Java is becoming rusty). But when I saw it, it was a "aha" moment for me.

Please keep writing similar stuffs, surely this kind of post is what I look for.

Talk is cheap, show me the code :)

harryh said...

If you try hard enough, you can turn any language into ML. :-)

Bharath said...


Such posts sure are interesting. Please do keep them coming.


Stevi Deter said...

This is an excellent post. I think the specific example is well chosen - I, too, had an "a-ha" moment. It really helps show how DI can be used to improve separation of concerns.

Kevin Bourrillion said...

Thank you all very much for the feedback! It definitely motivates me to write more.

Unknown said...


Very interesting post. I started thinking about pure functions after getting contact with some functional languages and really appreciate the value.

The next step (in the Next Great Language) could be to have this information at compile and run time (Method#isPure?), maybe by the combination of some keyword or annotation (pure or impure, depending on the default) and some analysis. We could imagine the possibilities of this for users of your own Predicate. On the other hand, if not done right, could this become the next const?

Anonymous said...

In English class, one girl Cheap WoW Gold said never give up when discussing. It just reminded me wow goldsomething about myself.WoW Gold Maybe it is wow power leveling something about love.WoW Gold My love, which began on July 3rd of WoW Gold 2005 and finished on August wow leveling 23rd of 2008, taught me many things. wow leveling It is not a pleasant world of warcraft power leveling thing to look back on world of warcraft power leveling that. But I know I world of warcraft power leveling must learn something from it,world of warcraft leveling no matter what it is, world of warcraft leveling happiness or sorrow.Our wow gold love did not go on so smoothly and we went through many things.

Anonymous said...

China Highlights
China Highlights
China Tours
China Hotels
China Attractions
Beijing China Travel
Shanghai China Travel
Xi'an China Travel
Guilin China Travel
Yangshuo China Travel

Affordable Luxurious Wedding Dress Blog said...

cheap wedding gowns,
discount bridal gowns,
China wedding dresses,
discount designer wedding dresses,
China wedding online store,
plus size wedding dresses,
cheap informal wedding dresses,
junior bridesmaid dresses,
cheap bridesmaid dresses,
maternity bridesmaid dresses,
discount flower girl gowns,
cheap prom dresses,
party dresses,
evening dresses,
mother of the bride dresses,
special occasion dresses,
cheap quinceanera dresses,
hot red wedding dresses

Anonymous said...

nike shoes, jordan shoes, nike dunks, nike air force 1, nike shox, nike shoes, nike shox, nike dunks, nike air force 1, nike shox, nike shoes, nike shox oz, nike shox nz, nike shox r3, nike shox r4, nike shox r5, nike shox tl
nike air force 1

nike Air Force 1, nike shoes, Jordan shoes, nike sb dunks, cheap nike Air Force 1, cheap nike shoes, cheap Jordan shoes, cheap nike sb dunks, discount nike Air Force 1, discount nike shoes, discount Jordan shoes, discount nike sb dunks, nike shoes, nike shox, nike dunks, nike air force 1, jordan shoes, nike shoes, nike shox, nike dunks, nike air force 1, jordan shoes

nike shoes, nike shox, jordan shoes, puma shoes, nike dunks, nike air max, nike air force one, timberland boots, ugg boots, nike shoes, nike shox, nike air force 1, nike sb dunks, puma shoes, nike air max, jordan shoes, ugg boot, jordan sneakers, timberland shoes, bape shoes, nike shoes, nike shox, nike dunks, nike air force 1, jordan shoes

Anonymous said...

Bon marche de Dofus Kamas.achat de dofus.le prix moins cher.nous vendons dofus,or de Wakfu. 24/7 appui-en-ligne et livraison rapide.Wakfu Kamas
china: chinaserving

Anonymous said...

I am grateful to you for this great content.aöf thanks radyo dinle cool hikaye very nice ssk only cinsellik very nice ehliyet only home free kadın last go korku jomax med olsaoy hikaye lesto go müzik dinle free only film izle love aşk only mp3 indir only radyolar lest go açıköğretim free net only filmler

Anonymous said...

cheap wow gold buy wow power leveling cheap cheap wow gold

Anonymous said...

cheap wow gold buy wow power leveling cheap cheap wow gold

Anonymous said...

China Wholesalers has been described as the world’s factory. buy products wholesaleThis phenomenom is typified by the rise ofbusiness. Incredible range of products available with China Wholesale “Low Price and High Quality” not only reaches directly to their target clients worldwide but also ensures that wholesale from china from China means margins you cannot find elsewhere and China Wholesale will skyroket your profits.china wholesale productsbuy china wholesalewholesale chinawholesale productsbuy products

Anonymous said...

There was this guy who believed very much in true love and decided to take his time to wait for his right girl to appear. He believed that there would definitely be someone special out there for him, but none came.
Every year at Christmas, his ex-girlfriend would return from Vancouver to look him up. He was aware that she still held some hope of re-kindling the past romance with him. He did not wish to mislead her in any way. nike shoxsSo he would always get one of his girl friends to pose as his steady whenever she came back. That went on for several years and each year, the guy would get a different girl to pose as his romantic interest. So whenever the ex-girlfriend came to visit him, she would be led into believing that it was all over between her and the guy. nike womens shoes The girl took all those rather well, often trying to casually tease him about his different girlfriends, or so, as it seemed! In fact, the girl often wept in secret whenever she saw him with another girl, but she was too proud to admit it. Still, every Christmas, she returned, hoping to re-kindle some form of romance. But each time, she returned to Vancouver feeling disappointed.
Finally she decided that she could not play that game any longer. puma mens shoes Therefore, she confronted him and professed that after all those years, he was still the only man that she had ever loved. mens puma shoesAlthough the guy knew of her feelings for him, he was still taken back and have never expected her to react that way. He always thought that she would slowly forget about him over time and come to terms that it was all over between them. nike shox Although he was touched by her undying love for him and wanted so much to accept her again, he remembered why he rejected her in the first place-she was not the one he wanted. nike 360 air maxSo he hardened his heart and turned her down cruelly. nike running shoesSince then, three years have passed and the girl never return anymore. They never even wrote to each other. NIKE air shoes The guy went on with his life..... still searching for the one but somehow deep inside him, he missed the girl.
On the Christmas of 1995, he went to his friend's party alone. "Hey, how come all alone this year? Where are all your girlfriends? What happened to that Vancouver babe who joins you every Christmas?", asked one of his air max He felt warm and comforted by his friend's queries about her, still he just surged on.
Then, he came upon one of his many girlfriends whom he once requested to pose as his steady. He wanted so much to ignore her ..... not that he was impolite,wholesale nike shoes but because at that moment, he just didn't feel comfortable with those girlfriends anymore. nike shox torchIt was almost like he was being judged by them. The girl saw him and shouted across the floor for him. Unable to avoid her, he went up to acknowledge her.
" are you? Enjoying the party?" the girl asked.
"Sure.....yeah!", he replied.
She was slightly tipsy..... must be from the whiskey on her hand.

Adi said...

Oes Tsetnoc one of the ways in which we can learn seo besides Mengembalikan Jati Diri Bangsa. By participating in the Oes Tsetnoc or Mengembalikan Jati Diri Bangsa we can improve our seo skills. To find more information about Oest Tsetnoc please visit my Oes Tsetnoc pages. And to find more information about Mengembalikan Jati Diri Bangsa please visit my Mengembalikan Jati Diri Bangsa page and other update like as Beratnya Mengembalikan Jati Diri Bangsa, Mengembalikan Jati Diri Bangsa di perpanjang and Jangan Berhenti Mengembalikan Jati Diri Bangsa. Thank you So much.

Oes Tsetnoc | Lanjutkan Mengembalikan Jati Diri Bangsa

Anonymous said...

Your blog is wonderful, I like it very much, thank you!
By the way, do you like polo shirts, which are very chic, especially the polo t shirts, I love them very much. I also like playing tennis rackets, it can keep healthy, what do you like to do?
We are the outlet of polo t shirts women, polo t shirts on sale, polo t shirts for women, polo shirts on sale, these products are best-seller in our store online.besides we also sell polo shirts men, men's polo shirt, men polo shirt, mens polo shirts, mens polo shirt and cheap polo shirts, discount polo shirts, men's polo shirts, women's polo shirts We are also the outlet of cheap tennis racket, discount tennis racket and the main product is prince tennis racquet, head tennis rackets, wilson tennis racket, babolat tennis racquet. So if you love sports, you should not miss our store, we can meet what you want, and you can find many surprise in our store

Anonymous said...

Rolex Watches Rolex Watches
Tag Heuer Watches Tag Heuer Watches
rolex replica rolex replica
replica rolex replica rolex
rolex replica watches rolex replica watches
replica rolex watches replica rolex watches
Tag Heuer Tag Heuer
replica Tag Heuer replica Tag Heuer
Tag Heuer replica Tag Heuer replica
rolex rolex
rolex air king rolex air king
rolex datejust rolex datejust
rolex day date rolex day date
rolex daytona rolex daytona
rolex gmt rolex gmt
rolex submariner rolex submariner
rolex yachtmaster rolex yachtmaster
rolex air king watches rolex air king watches
rolex datejust watches rolex datejust watches
rolex day date watches rolex day date watches
rolex daytona watches rolex daytona watches
rolex gmt watches rolex gmt watches
rolex submariner watches rolex submariner watches
rolex yachtmaster watches rolex yachtmaster watches

Anonymous said...

I am grateful to you for this great content

araç sorgulama
bağkur sorgulama
ssk sorgulama
emekli sandığı
radyo dinle

Anonymous said...

After read your blog, I think you are a wonderful person, for your blog is the best one I have ever seen. If you do not mind, I would like to know do you like fashion? Have you ever heard of polo shirts, which are very chic, especially the polo t shirts, I love them very much. I also like playing tennis rackets, it can keep healthy, what do you like to do? I consider it as my great pleasure to introduce myself as the outlet of polo t shirts women
polo t shirts on sale
and the warmly welcomed
polo t shirts for women
Now. I'd like to introduce our masterpieces, such as
polo shirts on sale
polo shirts men
men's polo shirt
men polo shirt
mens polo shirts
mens polo shirt
besides we also sell
cheap polo shirts
discount polo shirts
men's polo shirts
women's polo shirts
Which are popular with fashinable people. We are also the outlet of
cheap tennis racket
discount tennis racket
in this sporty season, we recommend
prince tennis racquet
head tennis rackets
wilson tennis racket
babolat tennis racquet
There more new products in our store online, we are expecting you to come. We can say that you must find your satisfied things in our store.

Unknown said...

Dofus Kamas|Prix Moins Cher Dofus Kamas|Kamas par allopass|Dofus kamas audiotel|Dofus kamas par telephone sur

Meilleur prix dofus kamas stock de dofus kamas

Prix moins cher dofus kamas vente dofus kamas sur dofus kamas vente

Nicole C said...

buy viagra
viagra online
generic viagra

King Bayern Munich said...

I think you write very good article I agree with the views and ideas! Second, the article gave me the feeling is very large, so I learned a lot of knowledge. Very grateful to the author's share. I also like led moving sign and LED tunnel light very much , very much !

AdFunds said...

Hi webmaster, commenters and everybody else !!! The blog was absolutely fantastic! Lots of great information and inspiration, both of which we all need!b Keep 'em coming... you all do such a great job at such Concepts... can't tell you how much I, for one appreciate all you do! Acuvue Advance Astigmatism

Newsinfo said...

workout at home with dumbbells
at home workouts
lose weight at home
abs workout at home
exercise machines at a gym
chest workout at home
get fit with exercise
how to exercise at home
run a marathon to shed pounds and improve cardio
how to lose weight at home
a healthy heart comes with exercise
medicine ball abs
fatigue your muscles by using weights or your body
upper body workout at home
be sure to hydrate your muscles as often as possible
dandruff home remedy
Good share you have here hope you keep it up, and don't forget to use dumbbells while exercising, even better though you can do these lose weight at home
where to buy venapro
buy venapro
venapro reviews
venapro review
best tooth whitening system
bleaching your teeth
teeth bleaching products
teeth bleaching trays
tooth whitening bleach

tpjewelry said...

Other ways to unlock trapped cash thomas sabo is in the form of selling thomas sabo shop silverware, silver flatware, sterling silver thomas sabo jewellery and scrap silver. Each of these thomas sabo schmuck will fetch different values depending on charm club thomas sabo the product and purity factors. sabo charm club With the current economic condition, selling thomas sabo 2010 precious metals, either pure or scrap, has gained thomas sabo sales a lot of importance since it thomas sabo reduziert has great intrinsic value attached to it and selling the scrap is one of the smartest ways of making money.


I would like to thank you for sharing your thoughts and time into the stuff you post!! Thumbs up
Eeveryone love fashion clothing, Polo Ralph Lauren is very popular all over world, that is my dream to get Ralph Lauren Polo Shirts, now there are lots of online shop which are Ralph Lauren Polo Outlet, it will be convenient for us, you can buy Discount Polo Ralph Lauren there.

Unknown said...

Ankara'nın en güzel escortlarıyla görüşmek için çankaya escort sayfamızı ziyaret edebilirsiniz.

Anonymous said...

Anonymous said...

super hero said...

Misbah Digital Marketing is an excellent online marketing agency in Bangalore.Misbah Digital Marketing!
Misbah Digital Marketing! having certified professionals in Google Ads, Google Analytics and Bing Ads.

Misbah Digital Marketing!

The Marketer said...

I enjoyed your blog Thanks for sharing such an informative post. We are also providing the best services click on below links to visit our website.

web design company in nagercoil
web development company in nagercoil
website design company in nagercoil
website development company in nagercoil
web designing company in nagercoil
website designing company in nagercoil
best web design company in nagercoil
web design company in velachery
web development company in velachery
website design company in velachery
website development company in velachery
web designing company in velachery
website designing company in velachery
best web design company in velachery

Thanks for Sharing - ( Groarz branding solutions )