Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java constructors pattern

Tags:

java

guice

I use the pattern quite a lot:

class Blah
  int a;   
  double b;   
  String c;   
  Date d;   

  public Blah(int a, double b, String c, Date d) {
      super(); // possibly   
      this.a = a;   
      this.b = b;
      this.c = c;
      this.d = d;
  }

This is indeed a great deal of boilerplate for something so simple. I was thinking of a generic object factory to do this with introspection, but this feels very evil (special cases, inheritance, and speed issues). Guice could be used and the constructor skipped altogether, but then manual object creation is going to be ugly.

Is this something I will have to live with in Java or is there a way to avoid this boilerplate?

like image 525
Jaco Van Niekerk Avatar asked May 29 '13 07:05

Jaco Van Niekerk


People also ask

What is constructor design pattern?

In classical object-oriented programming languages, a constructor is a special method used to initialize a newly created object once memory has been allocated for it. In JavaScript, as almost everything is an object, we're most often interested in object constructors.

What are the 3 types of patterns?

Three Types of Design Patterns (Behavioral, Creational, Structural) Distinguish between Behavioral, Creational, and Structural Design Patterns.

What is a Java builder pattern?

The Builder pattern, which is one of the 23 Gang of Four (GoF) design patterns described by Erich Gamma et al., is a creational design pattern that lets you construct complex objects step by step. It allows you to produce different types and representations of a product using the same construction code.

Why do we use builder pattern in Java?

Builder pattern aims to “Separate the construction of a complex object from its representation so that the same construction process can create different representations.” It is used to construct a complex object step by step and the final step will return the object.


1 Answers

Try using Lombok (http://projectlombok.org/)

You can generate getters, setters and constructors with mere annotations.

like image 57
darijan Avatar answered Oct 13 '22 23:10

darijan