The Successor Value Pattern 71
Functional programming is in the air. It’s nearly unavoidable. Even if you haven’t heard people talk about it or haven’t read a blog about it, you’ve probably seen its influence in your project. People are taking ideas that they learned in functional programming and applying them in straight object-oriented code. In Java, where there are no closures, today you are much more likely to encounter someone’s hand-rolled fold or map abstraction, and even if they haven’t gone that far, you are likely to find attempts to replace mutable data with immutable data. It’s part of the learning process, and there are some interesting patterns which occur along the way.
OO programmers often think in terms of entities. They imagine objects with identity and changeable local state; messages sent to objects alter their local state and trigger further message sends. Classic OO is intrinsically time-oriented. How do we pull this into a functional world? One thing that we can do is choose to see an entity as a series of values over time. Here’s one way to do it. If we have an entity like this:
public class EventDay {
private LocalDate date;
...
public void advance() {
do {
date = RegionalEventCalendar.nextValidDate(date)
} while (!fitsLocalCalendar(date));
}
...
}
We can change it to this:
public class EventDay {
private final LocalDate date;
...
public EventDay next() {
return new EventDay(prospectiveDay(date));
}
...
}
This is the successor value pattern. The notion is that you model state change as a series of value transformations. Is this good? Well, successor value is extremely common in functional programming languages. In Haskell, for instance, you don’t have mutation so you are always constructing new values. When Scala and F# are used in a functional style, you do the same thing; but is this a good idea in Java, C#, and C++? One concern is that the runtimes and libraries of those languages might not be as well tuned for continual reconstruction of value representations of the larger domain objects that we often see in OO designs. On the surface, however, successor value is nice; it gives us a mapping to immutable values and a dose of referential transparency.
Successor Value has an interesting quality from a type perspective. You compute successor values using a function which takes a type to another value of that same type. In the example above, next
is a function like that. It maps from ‘this’, which has the type EventDay, to a new EventDay. In category theory, this is called an endomorphism. It’s a relationship with some cool characteristics. One of them is closure. You can chain any number of endomorphic operations and still end up with the type you started with:
LocalDate next = date.nextDay().nextWeek().fridayAfter();
This is really about as encapsulated as you can get. Endomorphic chains don’t betray their representations and they don’t force users to use new types. In a way, you can look at an endomorphic chain as a state machine over an entity, spread out over time.
If you are used to thinking in terms of entities, you can mechanically translate entities into values and mapping functions. However, the better thing is to rethink your data types a bit. Sometimes the mapping from entities to values is clean but often with a bit of thought you can end up with representations which are better tuned for functional work.
It’s becoming essential for us to refactor our designs this way, both for more robust concurrency and because these designs are generally more robust in single-threaded code, too.
Fortunately, I think the concerns about copy overhead will largely go away. VM’s construct new objects fairly efficiently already. We also need to build libraries of optimized, immutable data structures. Clojure probably has the best such libraries among the JVM languages, right now.
For example, suppose you have an immutable list and you want to create a new one with a different element in the middle. There’s no need to make a whole new copy of the list. Rather, the new and old lists can share the “sublists” that didn’t change. That is, we can exploit copy-on-write semantics.
Dean: True. I suspect it will take a while for that to spread, though. I wonder in particular about languages where objects are primary and not represented internally as collections amenable to that. The bad case for ‘Successor Value’ is to use it for large entities which don’t consist primarily of internal collections.
this looks like the “ValueObject” pattern in Eric Evans domain driven design, i.e. the majority of any system should be immutable so that it can be recombined in unanticipated ways better.
Wouldn’t this pattern be harder to do and more complex state is called for? (I.e. the entity pattern) Jeff
Jeff: Yes, Eric’s Value Object pattern is sort of “use immutable value objects.” ‘Successor Value’ is about using them to replace entities when that’s useful.
Languages with algebraic data types or case classes make it easier to create and reconstruct value objects: they’re tuned for it. But, in general, that seems to be true. There’s a dividend for keeping representations less complex. The bias is toward computing things on need and transforming one representation to another rather than carrying around things we may need in a deep nest.
Jeff – Matt Podwysocki actually worked a bit on trying to use this pattern with FitNesse. We wanted to move away from a mutable object requirement for fixtures, using this sort of a pattern. Ultimately we found that it was just not in the cards – the system didn’t want to let it happen without us having to put in special hooks.
But what we found is that we had the capability of expressing the state as a series of functions – we just couldn’t get early enough in the chain to inject that series.
I’ve been really impressed with the solutions in both the pure functional languages, and even the not-so-pure (F#) which do a good job of being able to handle complex cases, yet keeping rather clear.
Very interesting post, I like the successor pattern a lot, but I’m also one of those people who like functional programming and immutable objects.
I’m wondering if you think the successor pattern has similarities to what I have written on orienting code ‘East’ to get the same effects/results ?
http://jamesladdcode.com/?p=12
I’m not sure that the patterns are the same, but I think they lead to the same results.
Your opinion would be great to hear.
Rgs, James.
what is also nice that you can then use this series of value transformations as an (infinite lazy) sequence and use all the functional operators on that to select the values you’re interested in or to approximate the interesting result.
http://functionaljava.googlecode.com/svn/artifacts/2.17/javadoc/fj/data/Enumerator.html
Re: GC overhead: Cliff Click from Azul Systems ran Rich Hickey’s Clojure Ant Colony Simulation on one of their big-ass Java machines. The program generated 20 gigs of ephemeral garbage per second! The good news: the GC plowed just right through it, without even breaking a sweat.
Notice how endomorphic functions violate tell-dont-ask. Rather than telling an object to change it’s state, we ask that object for a new object in the new state.
This difference alone (commands that change state vs requests for new state) really reduces down to variable-assignment vs functions…
Compare this to REST in which the requests we can make are carried in the answer we recently received. We do not tell the system to change state, we ask for a new state from the options given us by the previous state.
Just want to make one comment about the “Value” pattern. (Eric wasn’t the first to come up w/that BTW. Ward Cunningham wrote about it in his Checks Pattern Language and others did too…)... This value over time function works if there is a logical “next”. Sometimes there is not a next, but a next given some condition expressed in a function arg. Is that a different pattern?
unclebob: Yes, to me that’s the most interesting thing about mixing OO and FP. OO, done well, is about telling. FP, done well, is about asking. There’s an inherent tension and a set of interesting choices. Steve Freeman and I are working on a paper about the architectural ramifications of this.
rebecca: I think so. In FP, transforming a value of one type to a value of another is extremely common and it happens for so many reasons. I was just trying to write up the pattern where a series of values ends up taking the place of an entity.
I’m always confused when designing a class with both mutable and immutable behavior. By this I mean that the class is mutable as in it’s state can change, has methods that modify the class members directly. On the other hand, there are methods that return a newly created object of that class.
I think the best way to refactor is to strengthen the mutable class within itself and separate out the immutable behaviors (methods) and wrap the mutable class with an immutable wrapper. Would you agree?
What I was unable to take back from this article was “Why do I need a Successor Value pattern” ? And “why does one even want to write function oriented programs”
I also wonder if Object Orientation is time-oriented as much as it is state oriented. In classic OO there is one intrinsic “current” state which is often encapsulated. Due to a variety of reasons including the necessity to not introduce side effects, FP introduces scenarios where these states are copied endlessly before eventually made consistent once again. Successor Value allows for each function to create a new value object rather than change the earlier one in place and service that no side effect requirement.
I am not sure if programmers are keen to model their typical Business Entity objects (eg. Product, Invoice etc.) using SuccessorValue pattern – these are probably to be found at a lower granularity (eg. InvoiceNumber) or within some computations in progress (eg. total Invoices processed today). So while OO programmers getting their feet wet in FP (me included) could perhaps find it difficult to figure out which states to model using functional constructs, they are imo less likely to choose the entities which do not make sense to be modeled using the FP constructs since the disconnect will very soon be obvious.
Finally in the context of Endomorphic chains, are endomorphic chains necessarily preferable ? In an EAI processing flow, the intermediate computing state objects often change type and they change type based on the underlying processing logic requirements. It is precisely to handle such type shifting that constructs such as Monads which help suppress its effects and handle the type polymorphism for the functions are to be found helpful. So again I am not sure if endomorphism is a desirable feature or simply an attribute of the business logic under consideration.
As I did state earlier, I am attempting to be able to work effectively with FP as well. So these are my observations along the way, and unlikely to be as good as that of someone much further down that path.
Monis: I’m not sure. Seems like we’d need a concrete example.
Dhananjay: I think the key thing is the reasoning advantage that referential transparency can give you.. that and the fact that computation can become a bit more explicit. I agree, though, that expense could be prohibitive – it depends on the language and the platform. Re domain objects, I notice that in many applications domain models become a bit bulky. You populate some entity and it’s clear that it has much more data and behavior than you need in a particular transaction. In FP, you are always translating, so you can condense down to the essence of what you need in a transaction. It’s not free, however. You can lose a bit of domainish-ness as you move in that direction.
I don’t think there are any clear answers yet, just tradeoffs. When I’ve seen people use successor value, it is for smaller things. I haven’t seen it in production code with something like an Order.
Re endomorphism, that was just an observation. In some functional programming I’ve done, I’ve noticed that when I push something through a series of states, I can often chain on that same time. I agree that type transformation is great and valuable, but I thought it was worth highlighting this concept just because I haven’t seen much widespread discussion of physical dependency in FP yet.
class TimeInterval {
}
Now this can be a complex data structure with self-manipulation logic defined through it’s methods. However we have another method expand2 that does not alter the state of the calling object i.e. a method without side-effects.
We see this kind of behavior in many places. My point is that we should try to extract out expand2 in another wrapper class that provides such immutable methods over TimeInterval. In this way we can have both mutable and immutable flavors of a single data structure.
I haven’t gone through Scala completely but I think that the Scala collections are built on similar theme.
I use them and find them helpful, but I feel that they are a bit of a cop-out as a language construct. If an exception could talk, it would say “get me the hell out of here.” And, you have to admit, that’s a bit rude.
Most problems happens before testing, nice post anyway!
would you mind updating your blog with more information?
would you mind updating your blog with more information?
would you mind updating your blog with more information?
would you mind updating your blog with more information?
would you mind updating your blog with more information?
I am happy to find this post very useful for me, as it contains lot of information. I always prefer to read the quality content and this thing I found in you post. Thanks for sharing
Thank you very much for this article.I like its.As to me it’s good job.
Nice site.
The info shared is a cool one on all the blogs. Very useful.
http://www.newerahatstore.com Recently established in 2006,http://www.newerahatstore.com is the website of a company that has been in business in the Chinese market for about 3 years.We are new era fitted hats wholesale manufacture in china, Our company specialize in supplying new era hats,monster energy hats,dc shoes hats,red bull hats,famous hats,jordan hats,etc. We pay attention to our products quality and service
Very interesting post. Good job.
We wholesale hats at competitive price,providing a huge range of hats with different brand name,such as coogi hats, polo hats,Jordan hats,famous hats, dc shoes hats,new era hats, etc.You can buy cheap hats.
Welcome to caps-hat.com website. New era caps, new era hats, red bull hats, monster energy hats, baseball hats wholesale. Free shipping to worldwide.
Thanks for sharing.It really helpful to me about those information.
Here is very different. Thank you
We wholesale hats at competitive price,providing a huge range of hats with different brand name,such as coogi hats, polo hats,Jordan hats,famous hats, monster energy hats, red bull hats, etc.You can buy cheap hats. Welcome to visist here
I suppose the students who take our TDD course could claim to be Object Mentor Certified TDDers; and they’d be right.
Enjoy the christmas time and enjoy the hottest white iphone 4. All you need to do is the white iphone 4 conversion kit home.
Mold making is the core business of Intertech (Taiwan). With world level technology, Intertech enjoys a very good reputation for making Injection Mold and Plastic Moldsfor their worldwide customers.
I suppose the students who take our TDD course could claim to be Object Mentor Certified TDDers; and they’d be right.
Very interesting post, I like the successor pattern a lot, but I’m also one of those people who like functional programming and immutable objects.accounting services
I really like this essay. Thank you for writing it so seriously. I want to recommend it for my friends strongly. iPad to Mac Transfer can help you transfer music, movie, photo, ePub, PDF, Audiobook, Podcast and TV Show from ipad to mac freely.
Video cameras have to be frequented primarily in two modes. The first, characteristic on a lot early television, is what could be known as a. Images directly To a screen for Immediate observation. A couple cameras still accommodate live television production, but lots of live connections in most cases are being security, military/tactical, as well as industrial operations where surreptitious or remote viewing is required. The 2nd is To have on the images recorded To a container device being archiving or farther processing; as Many years,. was the primary format frequented as this purpose, rather. Recorded video is used into TV and film production, and more commonly. and monitoring tasks where unattended recording as for a situation is required as at a later time analysis.
Thanks for taking the time to discuss and share this with us, I for one feel strongly about it and really enjoyed learning more about this topic. I can see that you possess a degree of expertise on this subject, I would very a lot like to hear much more from you on this subject matter – I have bookmarked this page and will return soon to hear additional about it.
love the discussion in here. lots of great ideas.
We are the professional jacket manufacturer, jacket supplier, jacket factory, welcome you to custom jacket.
You do not need any oily residue there, since this is the spot where you will be applying your lace.. You can also use skin prep and let dry before applying glue.
I was recommended this website by my cousin. I’m not sure whether this post is written by him as no one else know such detailed about my problem. You are wonderful! Thanks!
good articles,come on ,you can do better….
This is great stuff. I have to say i am impressed by your ideas. roofing contractor venice
useful!
internette görüntülü olarak okey oyunu oyna, gerçek kisilerle tanis, turnuva heyecanini yasa.
I attempted these Beats by dr dre studio out in several genres thinking about which i listen to an eclectic mix Beats by dr dre solo. A all natural suit With Solos, you really feel the music, not the Monster Beats By Dr. Dre Pro Headphones Black.
Blog posts about wedding and bridal are always rare to find , at least with great quality,you qualify for a great blog post writer title,kep the great job happening
Corporations are challenging existing business models as they seek ways to speed innovation, focus on their core competencies, and scale to capitalize on opportunities and outpace competitors.
. This is really very happy for the great services in this blog. Thanks a lot for using the great info is visible in this blog and the nice services in this blog. Program Coordinator Job Description|Hospital Administrator Job Description|Cook Job Description|Registered Nurse Job Description
Slewing bearing called slewing ring bearings, is a comprehensive load to bear a large bearing, can bear large axial, radial load and overturning moment.
Until the last great war, a general expectation of material improvement was an idea peculiar to Western man. Now war and its aftermath have made economic and social progress a political imperative in every quarter of the globe.
Nice tuto Cesped Artificial Precios
Welcome you online shopping for discount and highest quality replacement batteries. We specializing in laptop battery, digital camera battery, camcorder battery, pda battery, cell phone battery, portable DVD battery, two way radio battery, MD Walkman battery, laptop AC adapter, laptop DC adapter, portable DVD player adapter and iPod Accessories. Fujifilm NP-45A Digital Camera Battery Charger
All-in-one solution to backup iPhone contacts and SMS, transfer iPhone video, songs, ebooks, photo, call list and more to computer or iTunes
This article is GREAT it can be EXCELLENT JOB and what a great tool!
The Successor Value Pattern 62 good post68
The Successor Value Pattern 63 hoo,good article!!I like the post!119
Hi, I totally agree about functional programing and you have a really good insight on the subject. Have a nice week. Ziad
Intertech Machinery Inc. provides the most precise Plastic Injection Mold and Rubber Molds from Taiwan. With applying excellent unscrewing device in molds,
Intertech is also very professional for making flip top Cap Molds in the world. Mold making is the core business of Intertech (Taiwan). With world level technology, Intertech enjoys a very good reputation for making Injection Mold and Plastic Molds for their worldwide customers.
If you are like most people you probably rock crystal beads purchase a watch, put it on your swarovski crystal wrist, and wear it until it dies. silver bracelet bangle You may not be aware that if you spider brooch care for your watch you may just prolong its life.
I can’t believe how many quality posts you’ve published. I’ll never get any work done!
A designer replica handbag is definitely the best choice for a fashionable woman who doesn’t want to splurge her hard earned cash on a single branded purse?
With more than 20 years of experience, Intertech provides an extensive integrated operational ability from design to production of molds 100% made in Taiwan. Additional to our own mold making factory, we also cooperate with our team vendors to form a very strong working force in Taiwan.
For the overseas market, we work very closely with local representatives in order to take care of the technical communication and after-sales service to our customers. We also participate in the EUROMOLD & FAKUMA exhibitions and meet our customers every year in Europe. By concentrating on mold “niche markets”, we play a very useful mold maker role from the Far East whenever customers want to develop their new projects. We provide services from A to Z to our customers on a very economic cost and effect basis.
Intertech Machinery Inc.
With more than 25 years of experience, Intertech provides an extensive integrated operational ability from design to production of molds 100% made in Taiwan. Additional to our own mold making factory, we also cooperate with our team vendors to form a very strong working force in Taiwan.
Main Products:
Injection Mold, Silicone Molding, Rubber Mold, Silicone molding, PC High-Gloss Plastic Mold, Die Casting Mold, Silicone Mold, Silicone Rubber Mold, Liquid Silicone Rubber , Cosmetic Packaging Mold, Medical Products Mold, Engineering Plastic Molds, Home Appliances Mold, etc…