9/8/12

Phantom types in Java

Introduction
One of the things that I like about types in programming languages is that they're there to help you (although sometimes feels the opposite). The more things you can check at compile time, the less you need to do during tests (if you need to do it at all!).
One of those techniques are Phantom Types, and although well known in advanced languages (Haskell, Scala, OCaml, etc.) it seems to be relativelly unknown in Java despite the fact it can be perfectly used.

Since Java 1.5, we have parametric types (generics). Once you have that, you can add types parameters to other types...

public class MyTpye <TypeParameter> { .... 

you can have methods with generic parameters

public <T> Result doSomething( MyType<T> p){ 
.... do something with p ... 
}

or require specific type parameters on your methods (called a generic type invocation ).

public Result doSomethingStringy( MyType<String>  p){ 
.... do something with p ... 
}

A ghost in the (type) machine
So, what are phantom types?. Now, normally when you require a specific type in the parameter you use it in the method body (say, when you have sum(List<Integer> xs) you'll use the fact that you have a list of Integers to sum them) , but what happen if you don't? Now you have a parameter type that never appears in the body, although is there, requiring that specific parameter in the type and preventing compilation if doesn't match. That's a phantom type :)

A simple example
Here an example: let's model a plane that can be either flying or landed and a takeOff and land methods that can only be applied to landed and flying planes respectively.
First, let's define the different flight status as marker interfaces:




Now, our plane class parametrized by the flight status:

And finally, our flight controller class with the takeOff and land methods:

The interesting part is in the land and takeOff methods. For example, in the land method, we require a Plane<Flying> but we just return a landing plane, (without using the Flying interface in the body). That's how we enforce that a plane must be flying to be able to land.
What I wanted to show with this is pretty silly example is how you can use phantom types to enforce some rules.

What are they good for?
Ok, now you have a way to require at compile type certain parameter on a type, what can you use it for?
Turns out it you can use to enforce many constraints:
Enforce a particular state: in the previous example, we used phantom types to require a specific state in a method (flying/landing in this case). In the same way we can require a connection to be open when we do a query or close it:

public ResultSet execute( Connection<Open> c, Query q) ....

public void close( Connection<Open> c) ....

(but is not safe, will work a better example)

You can also use it for safer Ids:
Usually Ids are Int or Strings, and is very easy to mix them up, e.g. in buy(String productId, String customerId) you can swap the Ids by mistake and you can get subtle bugs (the productId might match a customerId). With phantom types you can define an Id class parametrized by the entity and you get buy(Id<Product> productId,  Id<Customer>  customerId) and you'll get a compiler error if you pass a product id where you expect a customer id.
The full example  (in Scala):






Go ahead and Type!
As you see, phantom types are pretty straightforward and gives you more expressive power (in particular, will allow you to get more mileage from Java's type system). I hope they get more use in Java...

59 comments:

Unknown said...

Another usage for Phantom types is for creating type safe instance builders. I've written about this some time ago already: https://michid.wordpress.com/2008/08/13/type-safe-builder-pattern-in-java/

Unknown said...

That post was among the original references I found... I've added it to the links.
Thanks a lot!

Edmund Horner said...

public void close( Connection c) ....

So how does `close` change the type of `c` to `Connection` ? ;-)

I guess you could have:

public Connection close(Connection c) ....

Connection c2 = close(c);

With the understanding that `c` no longer exists after the call to `close`. Makes me wonder if there are any imperative languages that support functions that render their arguments unusable. I think Whiley would support something like `c = close(c)` where the type of `c` has changed after that call, though I'm not sure where it's at in terms of generics.

Edmund Horner said...

Damn, all the generic < and > chars have been stripped as HTML. :<

Read it as:

public Connection<Closed> close(Connection<Open> c) ....

Connection<Closed> c2 = close(c);

Anonymous said...

Your approach requires new object to be created in order to "change" the phantom type.

Another interesting approach is typestate (http://dl.acm.org/citation.cfm?id=10693) which allows object to change it's type during its lifetie

javin paul said...

Learned new way to use Generics. worth including in my list of advantage of using Generics in Java

Will said...

"well known in advanced languages (Haskell, Scala, OCaml, etc.) "
Why do you call then "advanced" languages?

Unknown said...

I called advanced languages because they have an advanced type system more expressive than the Java one.

Unknown said...
This comment has been removed by the author.
Shawn Michaels said...

Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful for me. BY - software development

Nikos Maravitsas said...

Hi Gabriel ,

Great blog! Is there an email address I can contact you in private?

Fritz Morse said...

Makes wonder if there are any crucial 'languages' that support functions that provide their justifications useless.

Anonymous said...
This comment has been removed by the author.
priya said...

Live Cricket Streaming Sites

eonwebs said...

Really Very very happy to say, your blog is very intersting to read. Business need online platforms and mobile applications because they impact how customers reach you for your products and services. Software development is much more than just a website or an application. There are many benifits you can get by improving your software.
You are doing a great job. Keep it up!

Yashika Jadon said...

This blog for software development are very informative! We find these technology-related topics very daunting, but for our projects we can now use these references. We really enjoy the blog which gives real examples, so that anyone can know. Great job! Great job! Keep it up.

Codexina Technologies said...

We Have Found Your Blog Very Informative. We Got Vital Information Related To Mobile App Development From Your Blog.
You Define Each Point In Your Blog. Todays Mobile App Development Becomes A Vital Feature For A Business And Startup
Which Contains Smooth Relation With Low Efforts. To Obtain The Benefits Of Mobile App Development Benefits It's Important To
Offshore Mobile App Development Companies. We (Codexina Technologies) Have Also Blogs For Mobile App Development Just Have A Look :
mobile app development company in kuwait & saudi arabia

learn digital marketing said...

Thank you for sharing very informative and creative content.This content is very useful best way to extend the knowledge of custom software development in indore

Anita said...

Nice!

Anita said...

IT is surely one of the biggest thing on global market that develop so fast. EVERY companies needs some kind of IT Service. Even if they do not realize that. Companies like https://pro4people.com/ do their best to provide it:) I wonder what we witness in next decade:)_

yuliia said...

Thank you for those tips, really glad to read them. Here's a good article about software development costs https://www.cleveroad.com/blog/software-development-costs, and what do you think, which technologies may reduce it?

Edward Bailey said...
This comment has been removed by the author.
Edward Bailey said...

A question that we are asked quite frequently. And it’s a tough one, even for someone who has been developing software for over 15 years. Well, here’s our three-word answer: “It really depends!”

You can get all your answer in this blog on cost of custom software development.

Rubina said...

Really Great Post & Thanks for sharing.

Oflox Is The Best Airtel Fancy Numbers Seller.

interestingthoughts said...

Nice article, also about useful software To Keep You Financially Healthy i highly advice you to use best bitcoin wallet for your money.

interestingthoughts said...

When businesses are driven right by experts in the digital transformation journey, they become aligned with customers’ demands and flexible in the fast-moving digital future. To become a part of it use our Digital Transformation Services.

Angelina said...

Excellent post! Outsourced software development can seamlessly reduce costs & improve organizational efficiencies for an enterprise.

Unknown said...

Thanks for one's marvelous posting! I truly enjoyed reading it, you can be a great author.I will make certain to bookmark your blog and may come back from now on. I want to encourage you to continue your great writing, have a nice holiday weekend!

flutter entwickler

Jacob Barlee said...

Nice blog. Thanks for sharing such great information. Mobzway is a Rummy Game Development company offers quality Rummy Game development services best in software industries. Visit: Rummy Game Development Company

Anna Evans said...

Thanks for the great article! It`s so interesting and useful!

I`m from Requestum company https://requestum.com/ and I think it was great to take the example of modeling a plane that can be either flying or landed and it`s takeOff and land methods.

erection pills said...

Wow, incredible weblog format! How long have you been running a blog for? you make blogging look easy. The total glance of your website is magnificent, as smartly as the content material!

Techsaga Corporations said...

Indian business consultancies focus on the facility providing distinctive operational competency to the unique business needs reading them through business strategy, changes in IT landscape, current pin-points, etc.

emailtaai said...

Software development company in Noida team has to perform in accord with the client's engineering team for ideal results. Techsaga Corporations address this facet of software development process most aggressively with our streamlined and well-planned resources.

Natali said...

A very excellent blog post. Recently I found blog of java development company, maybe you will interested in it too!

TECHWRAPPERS SOLUTION said...

Really amazing!

Susunia Hill said...

Susunia Hill Hotel
Hotel in Susunia Hill
Resort in Susunia Hill
Susunia Hill Resort
Hotels in Susunia Hill
Visit Site Hotel in Susunia Hill
For Booking Resort in Susunia Hill


rahulramesh said...


Wonderful blog to check out and reference links also related to the topic.
DevOps certification in Chennai
DevOps Online Course
Best DevOps Training in Bangalore
What is DevOps Best Practice
AWS Course in Chennai
AWS Online Course
AWS Course in Bangalore
What is Amazon Web Service

Ikokas Technologies said...

Using the unique features and functionality, we at Ikokas push the limits of custom eCommerce website designing. We strive hard to bring new ideas to fruition and deliver a professional and creative experience.

Software Development Outsourcing said...

Valuable piece of information about java software development. Keep sharing the stuff like that.

David Smith said...

The good post This is very helpful to me and I was very impressed by your meaningful thoughts. Considering something really interesting about your blog, I saved it in Favorites.
Share Tips | Stock Tips

Oryx Web Technology Pvt. Ltd. said...

Hello,
Your content is Amazing and very useful, please have a look on mine too!
Local SEO Agency

Bhaskar Sharma said...

Get the best software development company services in Noida

Media & Entertainment Software in India

Techsaga Corporations said...
This comment has been removed by the author.
Ab said...

Excellant shared! To know more about List of Top Custom Software Development Companies, please go through our website and get consulted yourself.

MednetLabs said...

Good Blog, Such a Nice Content, Informative for Readers Keep Posting.

Also checkout our website for best hospital management software in India.
Who we are?
Mednet Labs is the best Hospital Management Software In India for hospitals & clinics.
Best Hospital Management Software in India
Best Hospital Software in India

Aakash Shahakar said...

Thank you for this amazing blog.The Article which you have shared is very informative..
Imperial Money is a dedicated company that provides personalized services for wealth creation. It is an all-around choice to go for to induce your monetary assets at ease with multiple innovative prospects that add more value to your profile. The services and ideas include innovative products, best-in-class experience, mutual funds, and equities.
Imperial Money is a mutual fund company in India that helps you to create wealth from your income. Imperial Money provides services like a SIP calculator yearly, education calculator, and many more.
Step Up sip calculator
Mutual fund investment app
The Human life value calculator has been designed to help you assess your financial value to those you love by estimating the future financial contributions you will make to your family or the financial loss that your family would incur if something happens to you.

Insbytech said...

Great content with amazing coding skills.
Thanks!
Also, want to know about Product Design and Development, Visit by click on the link.

I m really enjoying articles.
Keep it up buddy :-)

Dhamaal Games said...

Excellent post! thanks for sharing this useful and meaningful information. visit:Dhamaal Games

Alfa Designs said...

Hey, nice blog, I found many things that are very informative.
Venetian Mirror
Buy venetian mirror online

yash said...

Hey, nice blog, I found many things that are very informative.

Visit us for
Human Specimens
Human Serum Samples
Whole Blood Samples

Offshore Software Development Company said...

Nice post..!!!
I want to share some information about Aggregator app development

yash said...

Very Helpful Post. Keep sharing such informative articles.
Supplier of frozen foods in UK
frozen food supplier in UK

RoyexMetaverse said...

Very informative Post. Keep sharing such kind of informative Post to help others

Thanks

Metaverse Development Company in Dubai

ayesha.irshad said...

if you are looking for Software development Services Our company is providing the best services around the globe. You can also get benefit from them.

Decy Johnson said...

Web development is a complex process that requires a variety of skills. The most important skill for a web developer is the ability to write code. Other important skills include the ability to create and maintain websites, the ability to troubleshoot problems, and the ability to work with a team of developers. But Cms web development has made this job so much easy.

rani said...

All your works of yours are actually so very beautiful because they actually share so much knowledge with everyone present here.

SEO Company said...

Very nice article! Thanks for sharing the content.software development companies Mumbai

web design agency india said...

Nice blog share about for website designing company.

emma said...

Absolutely fascinating insights on software development, Gabriel! Your articles are always enlightening. On a related note, I've been exploring ways to enhance my online presence for a book project. Any thoughts on synergies between software development and partnering with a top-notch book marketing company for effective outreach? Would love your perspective!