1

after seeing few projects on GitHub I've been thinking, should I use static methods in my controller? I use Javalin and I created NoteController class to service all requests. What's the difference between my idea and the other one, to use static methods and don't create instance of NoteController?

public static void main(String[] args){
        NoteController controller = new NoteController();

        Javalin app = Javalin.create(javalinConfig -> javalinConfig.staticFiles.add("/public"))
                .start();
        app.routes(()-> {
           path("notes", ()->{
                post(controller::insertNote);
                get(controller::getNotes);
                delete(controller::deleteNote);
                put(controller::updateNote);
           });
public void insertNote(Context ctx){
        database.insertNote(gson.fromJson(ctx.body(), Note.class));
        ctx.status(200);
    }

    public void getNotes(Context ctx){
        ctx.json(gson.toJson(database.getNotes(ctx.queryParam("id"))));
        ctx.status(200);
    }

    public void deleteNote(Context ctx){
        database.deleteNote(ctx.queryParam("id"));
        ctx.status(200);
    }

    public void updateNote(Context ctx){
        database.updateNote(gson.fromJson(ctx.body(), Note.class));
        ctx.status(200);
    }

Is my way of doing that incorrect? If I use static methods, I won't be able to use gson object as well as database instance to do database operations

Samson
  • 11
  • 1
  • Not if they're instance variables, no, but you made the choice to make them instance variables. There's no generic way to answer whether or not something "should" be implemented a certain way. – Dave Newton Mar 01 '23 at 20:36

1 Answers1

1

Static methods only have access to static objects/variables directly. In order to use any instance you will need to supply it as a parameter.

Because you're accessing an Instance of a database you should leave your code as is. See this answer for a precise difference between Static methods and Instance methods.

Also, you don't need to call gson#toJson if you're using ctx#json, since the latter already does the JSON parsing for you. If you want to use gson you can define it as the default mapper (available since version 5.3.1):

Javalin app = Javalin.create(javalinConfig -> {
    javalinConfig.staticFiles.add("/public");
    javalinConfig.jsonMapper(new JavalinGson());
}).start();