When I first started learning java GUI (swing) programming the way I was shown was more of an MVC model which involved using interfaces to call things and pass variables across classes.
I recently started programming in a more static way, having a Jframe call its static Jpanel's and using static methods to change components. Bascially i program everything statically so I can call them from the different classes with ease.
Heres an example:
My main JFrame class called "Home", I initialise the Toolbar class statically:
private static Toolbar toolbar = new Toolbar();
Now whenever I want to do something e.g. change the colour I just call from another class:
Home.toolbar.setForeground(Color.green);
Is this an ok way of programming? So far i've not run into any troubles but I was caught out by the fact that the people I learnt from didn't do this when it seems so much easier to do.
Are there any big down sides to this way of programming? What are the alternatives?
Basically, you should ask yourself:
"Should toolbar
be associated with each object I create? Or should it be one for all objects, and once I change it, it changes for all objects?"
If you answer yourself "Yes", then it's OK, otherwise it shouldn't be static
.
Of course there are many things to consider beside that.. For example, static
resources are not thread-safe.
If it works, then great... It's correct.
However, I make it my goal to write code that's both maintainable and testable. The problem with static instances is that it creates strong coupling throughout the entire project. Moreover, trying to isolate a class is impossible because the static dependency cannot be mocked or injected.
Typically, GUI code cannot be unit tested. MVC, however, ensures that the testable code is separated from the GUI code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With