For example, with Spark SQL's data DataFrameReader, you can invoke something like sqlContext.read().schema(customSchema).json(path) where schema function returns DataFrameReader itself with the added configuration of customSchema. Similarly, Jackson's ObjectWriter has with function which returns ObjectWriter itself with some custom configuration passed through the with function.

First, I am curious if this way of configuring through chaining method has it's own name, so that I can research further

Second, would this kind of method fit for a data format converter class where HTML, JSON, and CSV will be converted to one another? What I am imagining is having a static Converter class that has from and to methods, where you specify the input and its dataformat type and the output and its dataformat type. So, it would look something like Converter.from("inputPath", DataFormat.CSV).to("outputPath", DataFormat.JSON") and the blackbox should handle the process. The main reason I wanted to try this out is that, right now I have a method for each conversion, such as FromCSVToJSON, but I didn't think it looks clean enough. Any alternative design suggestion for the Converter class is welcome.

  • 1
    Hm, fluent interface is the answer to the first question, but could I leave this question up for the second part of the question of whether this fluent interface suits for convert class? – THIS USER NEEDS HELP Mar 13 '17 at 21:13
  • This duplicate marker is wrong, it is a Fluent Interface not the builder pattern. – Martin Spamer Mar 14 '17 at 20:26

See "Fluent Interface". I personally like your fluent from() and to() methods - it's convenient and aesthetic.

|improve this answer|||||

In Java it is known as a Fluent Interface. It was popularised by Martin Fowler however the idea is actually much older. It existed as method cascading in C and Smalltalk and is generally an inherent capability of functional languages.

A fluent interface would be useful for what you propose, but keep in mind it is a contract or interface not an implementation. Use the interface segregation principle and delegate behaviour to maintain the single responsibility principle.

|improve this answer|||||

Not the answer you're looking for? Browse other questions tagged or ask your own question.