Wednesday, February 3, 2016

Definition of the Trait Pattern in Java

In this article I will present the concept of traits and give you a concrete example of how they can be used in Java to achieve less redundancy in your object design. I will begin by presenting a fictional case where traits could be used to reduce repetition and then finish with an example implementation of the trait pattern using Java 8.

Suppose you are developing a message board software and you have identified the following as your data models: “topics”, “comments” and “attachments”. A topic has a title, a content and an author. A comment has a content and an author. An attachment has a title and a blob. A topic can have multiple comments and attachments. A comment can also have multiple comments, but no attachments.

Soon you realise that no matter how you implement the three models, there will be code repetition in the program. If you for an example want to write a method that adds a new comment to a post, you will need to write one method for commenting topics and one for commenting comments. Writing a method that summarizes a discussion by printing out the discussion tree will have to take into consideration that a node can be either a topic, a comment or an attachment.

Since the inception of Java over 20 years ago, object-oriented programming has been the flesh and soul of the language, but during this time, other languages has experimented with other tools for organizing the structure of a program. One such tool that we use in Speedment Open Source is something called “Traits”. A trait is kind of a “micro interface” that describes some characteristic of a class design that can be found in many different components throughout the system. By referring to the traits instead of the implementing class itself you can keep the system decoupled and modular.

Let’s look at how this would change our example with the message board.

Now the different traits of each entity has been separated into different interfaces. This is good. Since Java allows us to have multiple interfaces per class, we can reference the interfaces directly when writing our business logic. In fact, the classes will not have to be exposed at all!

Traits have existed for many years in other programming languages such as Scala, PHP, Groovy, and many more. To my knowledge there is no consensus regarding what is considered a trait between different languages. On the Wikipedia page regarding traits it says that:

“Traits both provide a set of methods that implement behaviour to a class and require that the class implement a set of methods that parameterize the provided behaviour”

The following properties are named as distinctive for traits:

  • traits can be combined (symmetric sum)
  • traits can be overriden (asymmetric sum)
  • traits can be expanded (alias)
  • traits can be excluded (exclusion)

Since Java 8 you can actually fulfill most of these criteria using interfaces. You can for an example cast an implementing class of an unknown type to a union of traits using the and (&) operator, which satisfies the symmetric sum criteria. A good example of this is described here. By creating a new interface and using default implementations you can override some methods to fulfill the asymmetric sum criteria. Aliases can be created in a similar way. The only problem is exclusion. Currently java has no way of removing a method from inheritance so there is no way to prevent a child class from accessing a method defined in a trait.

If we return to the message board example, we could for an example require the implementing class to have a method getComments, but all additional logic regarding adding, removing and streaming over comments could be put in the interface.


public interface HasComments<R extends HasComments<R>> {
    
    // one method that parameterize the provided behaviour
    List<Comment> getComments();

    // two methods that implement the behaviour
    default R add(Comment comment) {
        getComments().add(comment);
        return (R) this;
    }

    default R remove(Comment comment) {
        getComments().remove(comment);
        return (R) this;
    }
}

If we have an object and we want to cast it to a symmetric sum of HasComments and HasContent, we could do it using the and (&) operator:


final Object obj = ...;
Optional.of(obj)
    .map(o -> (HasComments<?> & HasContent<?>) o)
    .ifPresent(sum -> {/* do something */});

That was all for this time!

PS: If you want to read more about traits as a concept, I really suggest you to read the Traits: Composable Units of Behaviour paper from 2003 by N. Schärli et al.

27 comments:

  1. Java.net is moving to a new location in April 2017. All administrators, please copy your project resources before closing java.net

    ReplyDelete
  2. I really enjoyed while reading your article, the information you have delivered in this post was damn good. Keep sharing your post with efficient news.
    Regards,
    Hadoop Training in Chennai|Big Data Training in Chennai

    ReplyDelete
  3. Wonderful blog.. Thanks for sharing informative blog.. its very useful to me..

    iOS Training in Chennai

    ReplyDelete
  4. Why contract programmers are leading in software development industry is a question that is a frequently asked question. There is a curiosity regarding contract programmers and their work. This is not at all a new concept yet people are doubtful about hiring one. See more assignment help programming

    ReplyDelete
  5. Java programing vocation is fulfilling and prosperous in the event that you truly are intrigued coding, and have a distinct fascination in critical thinking. java

    ReplyDelete
  6. Ideas and advances, these days are getting obsoletewith every passing moment, henceforth making due in the profession of Java designer resembles strolling on the rope. java programming

    ReplyDelete
  7. Hi, Really your post was very informative. Today's internet era learn Hadoop Online Training will helps you to reach your goal.Selenium Online Training

    ReplyDelete
  8. Nice sharing. R is a language and environment for statistical computing and graphics. Want to make a career in R Programming. Learn R Programming Online Training course @ GangBoard. We are the best provider of online training on evergreen technologies.

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. Thanks for your informative article. As the demand quality apps and games increases in the mobile market, there is huge demand for the android developers in the job market
    Hi we at Colan Infotech Private Limited , a company which is Situated in US and India, will provide you best java web service and our talented java application development team will assure you best result and we are familiar with international markets, We work with customers in a wide variety of sectors. Our talented team can handle all the aspects of Java web application development, we are the best among the
    Java development company
    .

    We have quite an extensive experience working with java development services. we are the only Java application development company which offer custom services to a wide range of industries by exceeding our client’s expectations. You can even interact directly with the team regarding your project, just as you would with your in-house team.Our pro team will provide you the best java appliaction development services. We are best among the java development companies in Chennai, please review our customer feedbacks so that you may find a clue about us. If you want one stop solution for java development outsourcing, Colan infotech is the only stop you need to step in. Colan Infotech is the unique java web development company were our team of unique java application developer were ranked top in java enterprise application development.

    ReplyDelete
  11. Thank you for this valuable information. I have got some important suggestions from it. I'm working in Brave Technologies Private Limited. We provides lowest price of ERP Software for our clients. Contact us on info@bravetechnologies.in
    Manufacturing ERP software Chennai | Automotive ERP in Chennai

    ReplyDelete
  12. Thank you for this valuable information. I have got some important suggestions from it. Get your business to the next level in simple steps.
    ERP Software Solutions in Chennai.

    ReplyDelete
  13. Thank you for Sharing. I'm working in brave technologies private limited, We are the best erp software developers based in chennai. erp providers in chennai

    ReplyDelete


  14. Java application development

    Thanks for the awesome share
    Hi we at Colan Infotech Private Limited , a company which is Situated in US and India,
    will provide you best java web service and our talented java application development team will assure you best result
    and we are familiar with international markets,
    We work with customers in a wide variety of sectors. Our talented team can handle all the aspects of Java web application development,
    we are the best among the
    Java development company
    .

    We have quite an extensive experience working with java development services .
    we are the only Java application development company which offer custom services to a wide range of industries by
    exceeding our client’s expectations.
    You can even interact directly with the team regarding your project, just as you would with your in-house team.
    Our pro team will provide you the best java appliaction development services .
    We are best among the java development companies in Chennai ,
    please review our customer feedbacks so that you may find a clue about us. If you want one stop solution for java development outsourcing,
    Colan infotech is the only stop you need to step in.
    Colan Infotech is the unique java web development company were our team of unique
    java application developer were ranked top in java enterprise application development.

    ReplyDelete
  15. Thanks for your informative article. As the demand quality apps and games increases in the mobile market, there is huge demand for the android developers in the job market
    Hi we at Colan Infotech Private Limited , a company which is Situated in US and India, will provide you best java web service and our talented java application development team will assure you best result and we are familiar with international markets, We work with customers in a wide variety of sectors. Our talented team can handle all the aspects of Java web application development, we are the best among the
    Java development company
    .

    We have quite an extensive experience working with java development services. we are the only Java application development company which offer custom services to a wide range of industries by exceeding our client’s expectations. You can even interact directly with the team regarding your project, just as you would with your in-house team.Our pro team will provide you the best java appliaction development services. We are best among the java development companies in Chennai, please review our customer feedbacks so that you may find a clue about us. If you want one stop solution for java development outsourcing, Colan infotech is the only stop you need to step in. Colan Infotech is the unique java web development company were our team of unique java application developer were ranked top in java enterprise application development.

    ReplyDelete
  16. Nice blog. Thank you for sharing. The information you shared is very effective for learners I have got some important suggestions from it. erp in chennai.

    ReplyDelete
  17. Java, a programming language is the recent entry into the virtual world and has brought in a new perspective all together.
    best web design tutorials

    ReplyDelete
  18. This is my first visit to your blog, your post made productive reading, thank you. Java Training in Chennai

    ReplyDelete
  19. Thanks for sharing this useful and interesting Blog.. Keep updating your valuable post..

    Dot Net Training in Chennai | Dot Net Training Institute in Chennai | Online Training in Chennai



    ReplyDelete
  20. This content is so informatics and it was motivating all the programmers and beginners to switch over the career into the Big Data Technology. This article is so impressed and keeps updating us regularly.
    Hadoop Training in Chennai | Hadoop Training Chennai | Big Data Training in Chennai

    ReplyDelete