Using a utility to generate Java code to make my project more concise. A good idea?

The project I'm working on requires me to write a lot of repetitive code. For example, if I want to load an image file named "logo.png" into my code, I would write something like this: Bitmap logoImage;

...
// Init
logoImage = load("logo.png")

...
// Usage
logoImage.draw(0, 0);

..
// Cleanup
logoImage.release();

Having this code to use every new image is a pain, including the need to indicate that logoImage should load the file "logo.png".

Since I am working on a Java Android game, and images are used in internal loops, I really want to avoid slow actions like making virtual function calls, etc. access to arrays / maps / fields of objects when I can avoid this. Copying an idea from the Android API (generated class R), I thought I could run the utility before compiling to generate part of this repeating code for it. For example, the actual code in the project file will be reduced to this:

logoImage.draw(0, 0);

(, grep, sed), "Image.draw(..." ), , .. / .png "Bitmap logoImage" -. , , , .

, , , . . , , int- , .

? , , , , , . - (.. )? - , ?

+3
5

- . (IMO, , , .)

, ( ) ; .

public class ImageRegistry {
    private Map<String, Image> map = new HashMap<String, Image>();

    public synchronized Image getImage(String filename) {
        Image image = map.get(filename);
        if (image == null) {
            image = load(filename);
            map.put(filename, image);
        }
        return image;
    }

    public synchronized void shutdown() {
        for (Image image : map.valueSet()) {
            image.release();
        }
        map.clear();  // probably redundant ...
    }
}

logoImage.draw(0, 0) ..

registry.getImage("logo.png").draw(0, 0);

load release registry.shutdown().

EDIT OP :

... , . HashMap , , .

... .

  • ( ) - . , , HashMap . , , , (< 10%) , . , .

  • ( ) , , :

    = registry.getImage( "logo.png" ); (...) {   ...   image.draw(0, 0); }


, Google , , GC, Iterator .

.

  • HashMap . .

  • " GC Iterator". Java . C/++.

  • new , GC , new . .


, "file_that_does_not_exist.png" .

, .

+5

. .

, :

public class ImageUtils {
    public static void drawAndRelease(String name) {
        logoImage = load(name)
        logoImage.draw(0, 0);
        logoImage.release();
    }
}

:

ImageUtils.drawAndRelease("logo.png");

- , , , , .

+2

, , IDE . IntelliJ IDEA , Live Templates. , Eclipse NetBeans .

+1

You convey the complexity of code generation, and it (generation) is not trivial and may be a mistake. Code is harder to read and maintain. Below are some clear design and coding rules.

+1
source

Several ways:

Eclipse code2code, you select a template using a template language such as FreeMarker, groovy, etc.

The eclipse sqLite plugin for Android automatically generates sqlite code

MotoDevStudio4android has code snippets that you can use

0
source

Source: https://habr.com/ru/post/1731802/


All Articles