Coding style and organization - java

So I am currently making a airplane reservation system for a summer project to keep fresh with Java. With any reservation system its requiring a lot of classes and methods. Currently I'm working on importing the fleet.
My main method is acting like the chronological guide to my program.
public static void main(String[] args){
//start here
//accept passenger credentials
//place passenger in seat on plane
}
My question is a formatting problem. When I'm looking to start "making" my aircraft for my fleet. It goes a little like this.
//...
Airplane Boeing737 = new Airplane(seats[], nameOfAircraft);
This will put all values that i need to construct my airplane, obviously there are more variables for the airplane constructor.
My thought is to make a method in the Airplane class that will do this for me. but in order to do this i need to call a blank constructor for the other class (the one with my main method) to see it. I feel like this is horrible form for some reason. Is there a better way to do this?
Another thought as I'm posting is to modify the constructor to not accept any arguments and have that do everything in there. I feel like that's what I should be doing but I'm not 100% sure that would be the correct choice. I guess my overall question would be what are best practices in situations like this.

Use builder pattern, this will allow you:
dynamic way of building events
maintainable code (you can add more params when you want)
preserve integrity of the objects when created
Joshua Bloch's in Effective Java Chapter 1 Item 2 states:
Luckily, there is a third alternative that combines the safety of the telescoping
constructor pattern with the readability of the JavaBeans pattern. It is a form of the
Builder pattern. Instead of making the desired object directly,
the client calls a constructor (or static factory) with all of the required parameters and gets a builder object.
Modifying his example:
//Builder Pattern
public class Airplane {
private final int[] seats;
private final String name;
private final int maxSpeed;
private final int maxPassengers;
public static class Builder {
// Required parameters
private final int[] seats;
private final String name;
// Optional parameters - initialized to default values
private int maxSpeed = 1000;
private int maxPassengers = 150;
public Builder(int[] seats, String name) {
this.seats = seats;
this.name = name;
}
public Builder maxSpeed(int val) {
maxSpeed = val;
return this;
}
public Builder maxPassengers(int val) {
maxPassengers = val;
return this;
}
public Airplane build() {
return new Airplane(this);
}
}
private Airplane(Builder builder) {
seats = builder.seats;
name = builder.name;
maxSpeed = builder.maxSpeed;
maxPassengers = builder.maxPassengers;
}
}
Then you can create several different airplanes
public static void main(String[] args) {
// only mandatory params
Airplane boeing747 = new Airplane.Builder(new int[] {1,0,1}, "boeing747").build();
// just one param
Airplane boeing646 = new Airplane.Builder(new int[] {1,1,1}, "boeing646").maxPassengers(250).build();
// all params
Airplane fighter = new Airplane.Builder(new int[] {1,0,0}, "fighter_1").maxPassengers(3).maxSpeed(1600).build();
}

Forget the main method for now, you don't know if it will be a command line program, desktop app with a UI, web service or what. You don't know if it will be standalone or hosted in some framework or application server.
I would suggest starting with unit tests and drive the design of your domain model / business logic with TDD.
You don't want to see anything like Boeing737 hard coded like that. It will get its input from some other source, e.g. typed in, xml file, existing database, some other system.
You will then create instances of Airplane dynamically. You will pass something like a DTO from the UI or DB or XML parser to the constructor. There are other ways, look up Factory Pattern for example, but they tend to get overused IMHO.
You seem to be starting off in a way that doesn't match anything anyone does in the real world. Its hard to give any better advice.

Related

How to make code dynamic for similar kind of blocks

I am creating my web page with vaadin where I need to create same kind of blocks for different type for example need to show blocks having car details, so only car name would be different but the block design would be same with same label but different labels. I want to write generic code so that i can expand it for any car name, without adding it manually.
Attaching the code snippet which i am using where i am repeating my code for different type. Want to implement it dynamically.
private Grid<PresentableGenerateInputHeaders> winTSHeaderColumnsGrid;
private Grid<PresentableGenerateInputHeaders> fRHeaderColumnsGrid;
private ListDataProvider<PresentableGenerateInputHeaders> listDataProvider;
private List<PresentableGenerateInputHeaders> presentableGenerateInputHeaders = new ArrayList<>();
private void initWinTsGrid() {
listDataProvider = new ListDataProvider<>(presentableGenerateInputHeaders);
winTSHeaderColumnsGrid = new Grid<PresentableGenerateInputHeaders>(PresentableGenerateInputHeaders.class);
winTSHeaderColumnsGrid.setDataProvider(listDataProvider);
winTSHeaderColumnsGrid.setCaption(i18n.get("view.ruleDetails.general.csvHeaderColumns"));
winTSHeaderColumnsGrid.setStyleName("a-units");
winTSHeaderColumnsGrid.setWidth("450px");
winTSHeaderColumnsGrid.setItems(addGridValues(DataSource.WIN_TS, winTSHeaderColumnsGrid));
winTSHeaderColumnsGrid.getEditor().setEnabled(true);
winTSHeaderColumnsGrid.setColumnOrder("header", "count");
winTSHeaderColumnsGrid.sort("header");
winTSHeaderColumnsGrid.getEditor().addSaveListener((EditorSaveEvent<PresentableGenerateInputHeaders> event) -> {
event.getGrid().select(event.getBean());
selectedGapFillingCountWINTS.add(event.getBean());
});
}
private void initFRGrid() {
listDataProvider = new ListDataProvider<>(presentableGenerateInputHeaders);
fRHeaderColumnsGrid = new Grid<PresentableGenerateInputHeaders>(PresentableGenerateInputHeaders.class);
fRHeaderColumnsGrid.setDataProvider(listDataProvider);
fRHeaderColumnsGrid.setCaption(i18n.get("view.ruleDetails.general.csvHeaderColumns"));
fRHeaderColumnsGrid.setStyleName("a-units");
fRHeaderColumnsGrid.setWidth("450px");
fRHeaderColumnsGrid.setItems(addGridValues(DataSource.FR, fRHeaderColumnsGrid));
fRHeaderColumnsGrid.getEditor().setEnabled(true);
fRHeaderColumnsGrid.setColumnOrder("header", "count");
fRHeaderColumnsGrid.sort("header");
fRHeaderColumnsGrid.getEditor().addSaveListener((EditorSaveEvent<PresentableGenerateInputHeaders> event) -> {
event.getGrid().select(event.getBean());
selectedGapFillingCountFR.add(event.getBean());
});
}
You can change methods to be more generic by identifying all the parts you don't want to keep static, and moving those to be populated by method parameters instead. I.e. instead of
private void myMethod() {
grid.setCaption("myCaption");
}
you would write
private void myMethod(String caption) {
grid.setCaption(caption);
}
and then call it
myMethod("myCaption");
If you need to be outside of the whole class to be able to determine what the real values are, you can for example make the method public or pass on the necessary values in the class constructor.
public MyClass(String gridCaption) {
myMethod(gridCaption);
}
If there are a lot of values you need to set dynamically, you might consider using an object that contains all the necessary values instead.
public void myMethod(MyPojo pojo) {
grid.setCaption(pojo.getGridCaption());
}
In your example it looks like the generic values you want to pass are DataSource dataSource and whatever type of collection selectedGapFillingCountWINTS and selectedGapFillingCountFR happen to be, and the method should probably return the grid rather than set it directly to a class variable.

How to sort an instantiated custom arraylist in javafx

I am trying to learn programming and started using javafx.
I am now facing a problem which is probably caused by my gaps of knowledge and understanding of java
So far I have created a class as shown below
public class Sheet {
private String material;
private int DimX,DimY;
private double quantity;;
public Sheet(String _material,int _DimX,int _DimY,double _quantity){
material = _material;
DimX =_DimX;
DimY =_DimY;
quantity = _quantity ;
}
public String getMaterial(){return material;}
public void setMaterial(String _material) {material = _material;}
public int getDimX(){return DimX;}
public void setDimX(int _DimX){DimX = _DimX;}
public int getDimY(){return DimY;}
public void setDimY(int _DimY){DimY = _DimY;}
public double getQuantity(){return quantity;}
public void setQuantity(double _quantity) {quantity = _quantity;}
}
The arraylist is created using
List<Sheet> Sheet_list= new ArrayList<>();
Through a bit complicated ui the user enters some data which I take parts of, do some calculations and instantiate new entries to an arraylist of the object (sheet)above using the code similar to the linebelow
Sheet_list.add(new Sheet(string_i, int_x, int_y,double_e));
What I need is to sort this arraylist but I am receiving an error that the class is not abstract and does not override abstract method.
Is there any way to sort an arraylist formed from instantiated user data and not programmatically inserted?
Thank you in advance
List interface provides convenient sort() method taking a Comparator. Thus you can either make the Sheet class implement Comparable, then add all your sheet objects to the list, and call Collections.sort(list) on the list object, or use sort(Comparator) version to sort your list.
If you expect that holing your Sheets in some kind of order will be used often, I would go with the first approach.
By the way, I would go with #jewelsea remark and start with basics, then go to JavaFX and more complicated stuff.

How to save state when using strategy pattern

I'm am trying to implement a feed using the strategy pattern.
I have a few different types of ways in which feeds item are retrieved, e.g. all, suggested, by a search.
public interface IGetFeedItemsStrategy{
FeedItems getFeedItems(int start, int amount);
}
The implementations looks like this:
public Class GetSuggestedFeedItemsStrategy implements IGetFeedItemsStrategy{
private FeedDao feedDao;
public GetSearchedFeedItemsStrategy(FeedDao feedDao
this.feedDao = feedDao;
}
FeedItems getFeedItems(int start, int amount){
return feedDao.getSuggestedItems(start, amount);
}
}
public Class GetSearchedFeedItemsStrategy implements IGetFeedItemsStrategy{
private FeedModel feedModel;
private FeedDao feedDao;
public GetSearchedFeedItemsStrategy(FeedDao feedDao, FeedModel feedModel){
this.feedDao = feedDao;
this.feedModel = feedModel;
}
FeedItems getFeedItems(int start, int amount){
return feedDao.getSearchedItems(start, amount, feedModel.getSearchPhrase());
}
}
When a user clicks a button to change what type of results they want the controller calls setGetFeedItemsStategy(new GetSuggestedFeedItemsStrategy) or whatever. Now whenever the controller has to refresh the feed or paginate through result it uses whatever strategy has been set.
My question is whether it is okay to save references to other 'entity' and 'service' objects in strategy class implementations? Here the feedDao was injected into the controller and the feedModel was created by feedModel = new FeedModel() in the constructor. I'm confused because I've read that entities and services should be kept seperate. e.g. (http://thinkbeforecoding.com/post/2009/03/04/How-not-to-inject-services-in-entities). I'm wondering whether a strategy object is either?

GWT: how to format number on server and client (Gin/Guice)

In my GWT + App Engine project, I have a function that formats a double into a String that I need to use on the client and server side.
As you cannot use DecimalFormat in GWT, you have to use NumberFormat on the client-side, and DecimalFormat on the server-side.
I have a class that is used on both sides of the wire (UnitRate) which needs to use this function, so I implemented two classes: ClientUtilities and ServerUtilities which both implement the Utilities interface like so:
public interface Utilities extends Serializable
{
public String formatUnitOnePlace(Double value);
}
public class ClientUtilities implements Utilities
{
#Override
public String formatUnitOnePlace(Double value)
{
NumberFormat fmt = NumberFormat.getFormat("#0.0");
return fmt.format(value);
}
}
public class ServerUtilities implements Utilities
{
#Override
public String formatUnitOnePlace(Double value)
{
DecimalFormat oneDigit = new DecimalFormat("#0.0");// format to 1 decimal place
return oneDigit.format(value);
}
}
The initial idea was to bind the classes using Gin/Guice and inject Utilities into the UnitRate class so that the right implementation gets used depending which side of the wire we are on. UnitRate can be a child of Offer (server-side) and OfferDto (client-side), but this is seeming like a rather long-winded way to do it as the UnitRate entities need to be created by hand, and the only way to do it I have managed is using Assisted Injection.
This however which is creating a ripple effect through the program meaning that more and more of my domain model has dependencies so need to be created by Gin/Guice which is obviously not ideal.
See usage here:
public class UnitRate implements Serializable, HasUnitType, Comparable<HasUnitType>, HasTotal
{
// omitted for brevity
private Utilities utilities;
#AssistedInject
private UnitRate(#Assisted UnitType unitType, Utilities utilities)
{
this.unitType = unitType;
this.price = "";
this.utilities = utilities;
}
#Override
public String getTotal()
{
// some calculations first...
return utilities.formatUnitOnePlace(result);
}
}
I'm not sure what the ideal solution for this would be...
I could go the route of not using DecimalFormat and NumberFormat altogether and implementing some kind of math-based solution, but I'd rather not.
I could split UnitRate into UnitRate and UnitRateDto but I don't see the point - they are never stored in the datastore and only ever exist as child entities of another.
How do I solve this problem? WHY, GWT, WHY?
(I'd just like to add that this is highly simplified. In reality there are other formatting things the Utilities interface needs to do, and other places it needs to be used/injected.)
You may be able to get this working by using the #GwtIncompatible for the method where you are trying to retrieve the DecimalFormat class. This notifies the compiler to ignore this method and or class. Take a look at com.google.gwt.core.shared.GwtIncompatible for more info on how the annotation works.
Let me know if this solves your issue.
This might solve your issue btw.
#GwtIncompatible
public class ServerUtilities implements Utilities
{
#Override
public String formatUnitOnePlace(Double value)
{
DecimalFormat oneDigit = new DecimalFormat("#0.0");// format to 1 decimal place
return oneDigit.format(value);
}
}

When would you use the Builder Pattern? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
What are some common, real world examples of using the Builder Pattern? What does it buy you? Why not just use a Factory Pattern?
Below are some reasons arguing for the use of the pattern and example code in Java, but it is an implementation of the Builder Pattern covered by the Gang of Four in Design Patterns. The reasons you would use it in Java are also applicable to other programming languages as well.
As Joshua Bloch states in Effective Java, 2nd Edition:
The builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters.
We've all at some point encountered a class with a list of constructors where each addition adds a new option parameter:
Pizza(int size) { ... }
Pizza(int size, boolean cheese) { ... }
Pizza(int size, boolean cheese, boolean pepperoni) { ... }
Pizza(int size, boolean cheese, boolean pepperoni, boolean bacon) { ... }
This is called the Telescoping Constructor Pattern. The problem with this pattern is that once constructors are 4 or 5 parameters long it becomes difficult to remember the required order of the parameters as well as what particular constructor you might want in a given situation.
One alternative you have to the Telescoping Constructor Pattern is the JavaBean Pattern where you call a constructor with the mandatory parameters and then call any optional setters after:
Pizza pizza = new Pizza(12);
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);
The problem here is that because the object is created over several calls it may be in an inconsistent state partway through its construction. This also requires a lot of extra effort to ensure thread safety.
The better alternative is to use the Builder Pattern.
public class Pizza {
private int size;
private boolean cheese;
private boolean pepperoni;
private boolean bacon;
public static class Builder {
//required
private final int size;
//optional
private boolean cheese = false;
private boolean pepperoni = false;
private boolean bacon = false;
public Builder(int size) {
this.size = size;
}
public Builder cheese(boolean value) {
cheese = value;
return this;
}
public Builder pepperoni(boolean value) {
pepperoni = value;
return this;
}
public Builder bacon(boolean value) {
bacon = value;
return this;
}
public Pizza build() {
return new Pizza(this);
}
}
private Pizza(Builder builder) {
size = builder.size;
cheese = builder.cheese;
pepperoni = builder.pepperoni;
bacon = builder.bacon;
}
}
Note that Pizza is immutable and that parameter values are all in a single location. Because the Builder's setter methods return the Builder object they are able to be chained.
Pizza pizza = new Pizza.Builder(12)
.cheese(true)
.pepperoni(true)
.bacon(true)
.build();
This results in code that is easy to write and very easy to read and understand. In this example, the build method could be modified to check parameters after they have been copied from the builder to the Pizza object and throw an IllegalStateException if an invalid parameter value has been supplied. This pattern is flexible and it is easy to add more parameters to it in the future. It is really only useful if you are going to have more than 4 or 5 parameters for a constructor. That said, it might be worthwhile in the first place if you suspect you may be adding more parameters in the future.
I have borrowed heavily on this topic from the book Effective Java, 2nd Edition by Joshua Bloch. To learn more about this pattern and other effective Java practices I highly recommend it.
Consider a restaurant. The creation of "today's meal" is a factory pattern, because you tell the kitchen "get me today's meal" and the kitchen (factory) decides what object to generate, based on hidden criteria.
The builder appears if you order a custom pizza. In this case, the waiter tells the chef (builder) "I need a pizza; add cheese, onions and bacon to it!" Thus, the builder exposes the attributes the generated object should have, but hides how to set them.
The key difference between a builder and factory IMHO, is that a builder is useful when you need to do lots of things to build an object. For example imagine a DOM. You have to create plenty of nodes and attributes to get your final object. A factory is used when the factory can easily create the entire object within one method call.
One example of using a builder is a building an XML document, I've used this model when building HTML fragments for example I might have a Builder for building a specific type of table and it might have the following methods (parameters are not shown):
BuildOrderHeaderRow()
BuildLineItemSubHeaderRow()
BuildOrderRow()
BuildLineItemSubRow()
This builder would then spit out the HTML for me. This is much easier to read than walking through a large procedural method.
Check out Builder Pattern on Wikipedia.
.NET StringBuilder class is a great example of builder pattern. It is mostly used to create a string in a series of steps. The final result you get on doing ToString() is always a string but the creation of that string varies according to what functions in the StringBuilder class were used. To sum up, the basic idea is to build complex objects and hide the implementation details of how it is being built.
I always disliked the Builder pattern as something unwieldy, obtrusive and very often abused by less experienced programmers. Its a pattern which only makes sense if you need to assemble the object from some data which requires a post-initialisation step (i.e. once all the data is collected - do something with it). Instead, in 99% of the time builders are simply used to initialise the class members.
In such cases it is far better to simply declare withXyz(...) type setters inside the class and make them return a reference to itself.
Consider this:
public class Complex {
private String first;
private String second;
private String third;
public String getFirst(){
return first;
}
public void setFirst(String first){
this.first=first;
}
...
public Complex withFirst(String first){
this.first=first;
return this;
}
public Complex withSecond(String second){
this.second=second;
return this;
}
public Complex withThird(String third){
this.third=third;
return this;
}
}
Complex complex = new Complex()
.withFirst("first value")
.withSecond("second value")
.withThird("third value");
Now we have a neat single class that manages its own initialization and does pretty much the same job as the builder, except that its far more elegant.
For a multi-threaded problem, we needed a complex object to be built up for each thread. The object represented the data being processed, and could change depending on the user input.
Could we use a factory instead? Yes
Why didn't we? Builder makes more sense I guess.
Factories are used for creating different types of objects that are the same basic type (implement the same interface or base class).
Builders build the same type of object over and over, but the construction is dynamic so it can be changed at runtime.
You use it when you have lots of options to deal with. Think about things like jmock:
m.expects(once())
.method("testMethod")
.with(eq(1), eq(2))
.returns("someResponse");
It feels a lot more natural and is...possible.
There's also xml building, string building and many other things. Imagine if java.util.Map had put as a builder. You could do stuff like this:
Map<String, Integer> m = new HashMap<String, Integer>()
.put("a", 1)
.put("b", 2)
.put("c", 3);
While going through Microsoft MVC framework, I got a thought about builder pattern. I came across the pattern in the ControllerBuilder class. This class is to return the controller factory class, which is then used to build concrete controller.
Advantage I see in using builder pattern is that, you can create a factory of your own and plug it into the framework.
#Tetha, there can be a restaurant (Framework) run by Italian guy, that serves Pizza. In order to prepare pizza Italian guy (Object Builder) uses Owen (Factory) with a pizza base (base class).
Now Indian guy takes over the restaurant from Italian guy. Indian restaurant (Framework) servers dosa instead of pizza. In order to prepare dosa Indian guy (object builder) uses Frying Pan (Factory) with a Maida (base class)
If you look at scenario, food is different,way food is prepared is different, but in the same restaurant (under same framework). Restaurant should be build in such a way that it can support Chinese, Mexican or any cuisine. Object builder inside framework facilitates to plugin kind of cuisine you want. for example
class RestaurantObjectBuilder
{
IFactory _factory = new DefaultFoodFactory();
//This can be used when you want to plugin the
public void SetFoodFactory(IFactory customFactory)
{
_factory = customFactory;
}
public IFactory GetFoodFactory()
{
return _factory;
}
}
Building on the previous answers (pun intended), an excellent real-world example is Groovy's built in support for Builders.
Creating XML using Groovy's MarkupBuilder
Creating XML using Groovy's StreamingMarkupBuilder
Swing Builder
SwingXBuilder
See Builders in the Groovy Documentation
Another advantage of the builder is that if you have a Factory, there is still some coupling in you code, because for the Factory to work, it has to know all the objects it can possibly create. If you add another object that could be created, you will have to modify the factory class to include him. This happens in the Abstract Factory as well.
With the builder, on the other hand, you just have to create a new concrete builder for this new class. The director class will stay the same, because it receives the builder in the constructor.
Also, there are many flavors of builder. Kamikaze Mercenary`s gives another one.
/// <summary>
/// Builder
/// </summary>
public interface IWebRequestBuilder
{
IWebRequestBuilder BuildHost(string host);
IWebRequestBuilder BuildPort(int port);
IWebRequestBuilder BuildPath(string path);
IWebRequestBuilder BuildQuery(string query);
IWebRequestBuilder BuildScheme(string scheme);
IWebRequestBuilder BuildTimeout(int timeout);
WebRequest Build();
}
/// <summary>
/// ConcreteBuilder #1
/// </summary>
public class HttpWebRequestBuilder : IWebRequestBuilder
{
private string _host;
private string _path = string.Empty;
private string _query = string.Empty;
private string _scheme = "http";
private int _port = 80;
private int _timeout = -1;
public IWebRequestBuilder BuildHost(string host)
{
_host = host;
return this;
}
public IWebRequestBuilder BuildPort(int port)
{
_port = port;
return this;
}
public IWebRequestBuilder BuildPath(string path)
{
_path = path;
return this;
}
public IWebRequestBuilder BuildQuery(string query)
{
_query = query;
return this;
}
public IWebRequestBuilder BuildScheme(string scheme)
{
_scheme = scheme;
return this;
}
public IWebRequestBuilder BuildTimeout(int timeout)
{
_timeout = timeout;
return this;
}
protected virtual void BeforeBuild(HttpWebRequest httpWebRequest) {
}
public WebRequest Build()
{
var uri = _scheme + "://" + _host + ":" + _port + "/" + _path + "?" + _query;
var httpWebRequest = WebRequest.CreateHttp(uri);
httpWebRequest.Timeout = _timeout;
BeforeBuild(httpWebRequest);
return httpWebRequest;
}
}
/// <summary>
/// ConcreteBuilder #2
/// </summary>
public class ProxyHttpWebRequestBuilder : HttpWebRequestBuilder
{
private string _proxy = null;
public ProxyHttpWebRequestBuilder(string proxy)
{
_proxy = proxy;
}
protected override void BeforeBuild(HttpWebRequest httpWebRequest)
{
httpWebRequest.Proxy = new WebProxy(_proxy);
}
}
/// <summary>
/// Director
/// </summary>
public class SearchRequest
{
private IWebRequestBuilder _requestBuilder;
public SearchRequest(IWebRequestBuilder requestBuilder)
{
_requestBuilder = requestBuilder;
}
public WebRequest Construct(string searchQuery)
{
return _requestBuilder
.BuildHost("ajax.googleapis.com")
.BuildPort(80)
.BuildPath("ajax/services/search/web")
.BuildQuery("v=1.0&q=" + HttpUtility.UrlEncode(searchQuery))
.BuildScheme("http")
.BuildTimeout(-1)
.Build();
}
public string GetResults(string searchQuery) {
var request = Construct(searchQuery);
var resp = request.GetResponse();
using (StreamReader stream = new StreamReader(resp.GetResponseStream()))
{
return stream.ReadToEnd();
}
}
}
class Program
{
/// <summary>
/// Inside both requests the same SearchRequest.Construct(string) method is used.
/// But finally different HttpWebRequest objects are built.
/// </summary>
static void Main(string[] args)
{
var request1 = new SearchRequest(new HttpWebRequestBuilder());
var results1 = request1.GetResults("IBM");
Console.WriteLine(results1);
var request2 = new SearchRequest(new ProxyHttpWebRequestBuilder("localhost:80"));
var results2 = request2.GetResults("IBM");
Console.WriteLine(results2);
}
}
I used builder in home-grown messaging library. The library core was receiving data from the wire, collecting it with Builder instance, then, once Builder decided it've got everything it needed to create a Message instance, Builder.GetMessage() was constructing a message instance using the data collected from the wire.
When I wanted to use the standard XMLGregorianCalendar for my XML to object marshalling of DateTime in Java, I heard a lot of comments on how heavy weight and cumbersome it was to use it. I was trying to comtrol the XML fields in the xs:datetime structs to manage timezone, milliseconds, etc.
So I designed a utility to build an XMLGregorian calendar from a GregorianCalendar or java.util.Date.
Because of where I work I'm not allowed to share it online without legal, but here's an example of how a client uses it. It abstracts the details and filters some of the implementation of XMLGregorianCalendar that are less used for xs:datetime.
XMLGregorianCalendarBuilder builder = XMLGregorianCalendarBuilder.newInstance(jdkDate);
XMLGregorianCalendar xmlCalendar = builder.excludeMillis().excludeOffset().build();
Granted this pattern is more of a filter as it sets fields in the xmlCalendar as undefined so they are excluded, it still "builds" it. I've easily added other options to the builder to create an xs:date, and xs:time struct and also to manipulate timezone offsets when needed.
If you've ever seen code that creates and uses XMLGregorianCalendar, you would see how this made it much easier to manipulate.

Categories