Boilerplate code in java

Using the Java Class object in boilerplate code

Let me give you an example: A usual structure in in a backend could look something like this: Define a functional domain object: Foobar Create the entity FoobarEntity: Now the boilerplate party starts, create data transfer objects, data access objects, services, . Create (to get started), (CRUD) and default implementation , (CRUD) and default implementation , a mapper to map from Entity to Dto , maybe a Spring config , maybe a filter object to search , maybe some more Classes for a REST api like , , . Question: I want to use Java annotations to insert code (method invocations and so on).

Using the Java Class object in boilerplate code

On occasion, as much as I try to avoid it, I do generate a fair amount of boilerplate code in my programming. I’ve been told that the Java Class object can be used to get around boilerplate code, but I don’t currently see how.

When I say boilerplate code, I’m referring to the term used to refer to text that is reused again and again, with slight modification.

public Map loadBooleanTags(File in) < // Code that extracts boolean tags >

Now, suppose, you then want to load int tags, where the files are in the exact same format, but you want the data structure to be a Map . The only way I can think of handling this is like so:

public Map loadIntegerTags(File in) < // Code that extracts integer tags >

Essentially, I copy and past the boolean method, but I make it parse an Integer instead. What are some better ways to handle this? Ideally, I’d like to have one method that outputs a map with the correct generics.

Читайте также:  Variable and reference variable in php

Interesting question. First of all, Class has been around since Java 1. Second, I think this is the pattern you’re looking for:

public abstract class GenericMapFactory  < public MapmakeMap(File in) throws InstantiationException, IllegalAccessException, IOException < Mapresult = new HashMap(); BufferedReader rdr = new BufferedReader(new FileReader(in)); String line = null; while ((line=rdr.readLine()) != null) < String key = "" /* something meaningful for your application */; T item = parse(line); result.put(key, item); >return result; > protected abstract T parse(String line); > 

For every variation you need you provide a specialization, for example:

public static class IntMapFactory extends GenericMapFactory  < @Override protected Integer parse(String line) < Integer result = null; // parse the line, setting the value of result return result; >> 

All the ‘boilerplate’ code is factored out into a generic superclass and only the type-specific code needs to be written. You use it as follows:

File in = . Map msi = new IntMapFactory().makeMap(in); 

Java boiler plater Code Example, “java boiler plater” Code Answer. java boilerplate . java by CodeCat on Apr 23 2021 Donate Comment

Creating Java Boilerplate Code with IntelliJ

Is it possible to create a template/live template with IntelliJ to create the full stack of usual boilerplate for a Domain Object?

Let me give you an example: A usual structure in in a backend could look something like this:

@Entity @Table(name=»foobar») @Getter @Setter public class FoobarEntity implements Persistable

Some further considerations: More annotations (like @Service or something like that) would be somehow useless since the all the classes start with the same code base (like add , delete , edit , load methods for a service and a dao) but, however, will grow in the further process of development.

Is this somehow possible with IntelliJ (or another tool you know)?

You can create entities like that with hibernate plugin. It creates entities according to your table structure. Just add hibernate framework to your project (in linux, press Ctrl + Shift + a , then type hibernate and select add hibernate framework ), then you’ll get a task window like that:

Now right click on your projects name (will be different in your case) and select Generate Persistence Mapping > By Database Schema .

Now a window will open and you can select the tables you want to create an entity for.

Note that you need to have set up your database in idea to make this work.

For your third point, use file templates. Again, press Ctrl + Shift + a , but then type file template — create the templates once and just use them.

How to modify Java boilerplate code generation in, not sure if you can modify existing code snippets (or ones added through plugins) but you can always create your own identical snippets, minus the JavaDoc in the menu bar, select Preferences>Snippets, in the dropdown type Java, and follow along with the example that is in the editor window that will open up. …

How can I use Java annotations to insert some boilerplate code as with C macro?

I want to use Java annotations to insert code (method invocations and so on). Let’s say I have such code:

 ActionBar bar = getActionBar(); assert bar != null; bar.setIcon(android.R.color.transparent); EventBus.getDefault().register(this); checkGPS(); 

This code appears in each my Activity class. And instead of writing it each time I want to have something like this : @PrepareActivity which will expand code. In C or C++ I can simply use #define PrepareActivity \ . . Can I write the same with Java annotations? And how to do this? Thanks.

Annotations aren’t meant to change the code. There are special Java compilers (for example Projekt Lombok) which bend those rules.

But you don’t need anything fancy. Just make the class implement an interface which contains getActionBar() and checkGPS() and then you can write a static helper method:

public static void prepare( IThing thing )

What I gather from answers to this this post, there seems to be no standard way of doing what you want. It might be possible using Aspect oriented programming, or maybe an answer in the linked post can help?

Project Lombok does something similar and they explain their trick here

Java — What is the difference between boilerplate code, Boilerplate code and API are two different things. Boilerplate code is common patterns of code that you must write to accomplish a given task. Often this is the code required just to get a running program. For example in Java, you must declare a class with a main () method at the very least. An API, on the other …

Источник

What is boilerplate code and the boilerplate meaning in Java?

In Java you have to write a lot of additional and repetitive code along with your own code. This additional — unfortunately mandatory — code is eating up space in your preferred IDE and also eating up your time. In this article we will dig deeper into the topic.

What does boilerplate mean?

The name boilerplate comes from the newspaper printing industry and was used for any repetitive text, which was used in various contexts and pages and was mandatory for the newspapers to use it. So this repetitive text, mostly used as a filler for the newspaper, has been stamped in special metal plates for the printing process. Since the plates looked like plates on boilers, they quickly got the name boilerplates and the text got the name boilerplate text, or even shorter, boilerplate.

But what is the meaning of boilerplate in the programming context?

Let’s say you want to define a simple model class with the following class fields:

  • boolean field someBoolean
  • String field someStringField
  • float field someFloatField

This requirement seems pretty simple and the code could look something like this (unfortunately that is not the case):

/**
* my model class with fields.
/
public class MyModelClass private boolean someBoolean;
private String someStringField;
private float someExcludedField;
>

To make this class usable and runnable you would need to add the following methods:

  • a no argument constructor
  • an all field as argument constructor
  • getters for all fields
  • setters for all fields
  • a human usable toString method
  • an equals method to fulfill the object identity requirements in Java
  • a hashCode method to fulfill the object identity requirements in Java

With these requirements your code is getting extended by a lot of boilerplate code.

/** 
* my model class with fields.
*
*/
public class MyModelClass private boolean someBoolean;
private String someStringField;
private float someExcludedField;

public MyModelClass() >

public MyModelClass(boolean someBoolean, String someStringField, float someExcludedField) super();
this.someBoolean = someBoolean;
this.someStringField = someStringField;
this.someExcludedField = someExcludedField;
>

@Override
public String toString() return "MyModelClass [someBoolean=" + someBoolean + ", someStringField=" + someStringField + ", someExcludedField=" + someExcludedField + "]";
>

@Override
public int hashCode() final int prime = 31;
int result = 1;
result = prime * result + (someBoolean ? 1231 : 1237);
result = prime * result + Float.floatToIntBits(someExcludedField);
result = prime * result + ((someStringField == null) ? 0 : someStringField.hashCode());
return result;
>

@Override
public boolean equals(Object obj) if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MyModelClass other = (MyModelClass) obj;
if (someBoolean != other.someBoolean)
return false;
if (Float.floatToIntBits(someExcludedField) != Float.floatToIntBits(other.someExcludedField))
return false;
if (someStringField == null) if (other.someStringField != null)
return false;
> else if (!someStringField.equals(other.someStringField))
return false;
return true;
>

public boolean getSomeBoolean() return someBoolean;
>

public void setSomeBoolean(boolean someBoolean) this.someBoolean = someBoolean;
>

public String getSomeStringField() return someStringField;
>

public void setSomeStringField(String someStringField) this.someStringField = someStringField;
>

public float getSomeExcludedField() return someExcludedField;
>

public void setSomeExcludedField(float someExcludedField) this.someExcludedField = someExcludedField;
>
>

You can see that the main interesting code is getting inflated with a lot of boilerplate code, which is needed in Java.

If you want to learn how to get rid of all this boilerplate code in Java read the article about How to Get Rid of Boilerplate Code with Lombok.

Источник

Оцените статью