Where should my user interface code be located? - java

Where should my user interface located in a simple CRUD application (with Java).
In my application I have the main class as well as another class which handles all the things which have something to do with the database e.g. getting information from it or adding new info to it.
Is it wiser to keep the UI-elements in the main class and leave the database class take the user input forward e.g. add a new element into database class, like this:
public static void main(String[] args) {
Scanner scan = new Scanner(system.in);
System.out.println("Give me your name:");
String name = scan.nextLine();
DatabaseHandler db = new DatabaseHandler();
db.addNameToDatabase(name);
}
Or should the input prompt exist inside the DatabaseHandler, so in the main-class only the method call is shown, like this:
public static void main(String[] args) {
DatabaseHandler db = new DatabaseHandler();
db.addNameToDatabase(); //user interface now inside addNameToDatabase method
}

It really depends on the size of your program. If your program is small and easy to read in one file then let it be so. As the program gets bigger then it becomes necessary for clarity to break it out. (If it is really small than a straight procedural way of coding might be the best within one class.)
In the case you break it out then the main class should be a driver for both the UI and data portions, which should be in different modules. You might want to look at different patterns like MVC or MVP on how to split it up.
As you can see there is no one way fits all. Large programs that are broken up into components/modules/packages are harder to get your arms around because of the wiring, but make it easier for a team to work on.

Always during development, remember - high cohesion and low coupling. For your particular question, think this way - in either approach, are you having high cohesion? No. Why should the database class handle user input? And why the main method should handle user input? No, both your ways are,well ideally, wrong.
But we seldom come across ideal situations. Your IO should be handled by another class and your database should be handled by another class,so should your UI. And inside these classes as well, each method should have a specific task. Use getters and setters,for instance, in your IO class,to get and set variables. Each method doing what it should do ensures high cohesion. And in this way, you end up ensuring low coupling as well,because your modules won't be interdependent. You might think - oh well, I can write all this in just one class and get it over with, but remember, this approach has a lot of advantage. In situations where the maintenance of your code has to be done by someone else, they would know by the names of classes and methods to know where to look for the issues. In situations where you have to look at your own code after ages, you wouldn't even recognize one word if you aren't organized in this manner.
Remember - high cohesion and low coupling FTW!
Ideally - your main should just be a starting point to your program, and nothing else.

Related

Struts2 application scope instances

I've inherited a Struts2 project which needs some functionality addition. When I ran into de code to guess how the previous guy did things, I found out that if he wants a class to instantiate only once when the Tomcat server starts (because it has to read heavy loads of data from disk, but only once to get its config, for instance), he did this in the following way:
public class ExampleClass {
public ExampleClass(){//Read files and stuff to initialize}
public Object method(Object[] args){//The job to do}
}
And then, in the struts action which uses it he instantiates it this way:
public class SomeAction extends ActionSupport {
ExampleClass example = new ExampleClass()
public String execute() {
//Do stuff every time the action is called
Object result = example.method(args);
// Do stuff with results
}
}
I know from servlet times that this does the trick, however, I feel like the guy who handled this before was as inexperienced in Struts2 as I am, so here comes my question:
Is this the proper way to do so according to style recommendations and best practices? Does struts2 provide a more controlled way to do so?
I found some answers related to simple parameters here, but I'm not sure if this is the proper way for objects like those? What would happen if ExampleClass instance is really heavy? I don't want them to be copied around:
How to set a value in application scope in struts2?
Some background about ExampleClass: When the constructor is called, it reads large sets of files and extracts it's configurations from them, creating complex internal representations.
When method() is called, it analyzes it's parameters using the rules, and outputs results to the user. This process usually takes seconds, and doesn't modify the previously initialized rule values.
This is running in Tomcat 7, however, I'm planning to upgrade to Tomcat 8.5 when everything is in place. I'd like to know if there are known issues about this regarding to this setup aswell (there are no other incompatibilities in the code).
BTW: He's not checking if ExampleClass is broken or anything like that, this definetly looks like a recipe to disaster xD. In fact, If I remove the source files, it is still trying to execute the method()... Poor soul...
Ideally, I need a way to instantiate all my application-level objects on start-up (they're the application itself, the rest is just a mere interface) in a way that if they fail Struts2 will tell Tomcat not to start that war, with the corresponding error logging and so on.
If Struts2 doesn't support this, which is the commonly accepted work-around? Maybe some Interceptor to check the object status and return to a error page if it hasn't been correctly instantiated? Execute a partial stop of tomcat from within?
All the objects of this project are thread safe (the only write operation inside them is performed on initialization), but I'd like to know best practices for Struts2 when objects are not so simple. What happens if a user can actually break one? (I know I should by any means avoid that, and I do, but mistakes happen, so I need a secure way to get through them, and get properly alerted, and of course I need a way to reinstantiate it safelly or to stop the whole service).
Right now, I can manually execute something like:
public class SomeAction extends ActionSupport {
ExampleClass example = new ExampleClass();
private boolean otherIsBuildingExample = false;
public String execute() {
if(otherIsBuildingExample) return '500 error';
if(example==null || example.isBroken()){
otherIsBuildingExample = true;
example = new ExampleClass();
otherIsBuildingExample = false;
}
Object result = example.method(args);
// Do stuff with results
}
}
Indeed, this would be cleaner with Interceptors, or so, however, this sounds like a pain in the *** for concurrency, specially taking into consideration thay example takes several seconds to start, and that more requests can come, so more concerns to take into consideration, like: what if two people call if(otherIsBuildingExample) and the second one gets the value before the first one performs otherIsBuildingExample=true? Nothing good... If the class is simple enough, both will instantiate and the slower one will prevail, but if one instantiation blocks the other's resources... well, more problems.
The only clean solution I can think of is to make ExampleClass robust enough so you can repare it using its own methods (not reinstantiating) and make those thread safe in the common way (if 10 people try to repair it, only one will proceed, while the others are just waiting for the first to end to continue, for instance).
Or maybe everytime you call execute() you get a copy of example, so no worries at all about this?
I'm digging into struts documentation
Thanks in advance.

Using the Command Pattern with Parameters

I have a ReloadableWeapon class like this:
public class ReloadableWeapon {
private int numberofbullets;
public ReloadableWeapon(int numberofbullets){
this.numberofbullets = numberofbullets;
}
public void attack(){
numberofbullets--;
}
public void reload(int reloadBullets){
this.numberofbullets += reloadBullets;
}
}
with the following interface:
public interface Command {
void execute();
}
and use it like so:
public class ReloadWeaponCommand implements Command {
private int reloadBullets;
private ReloadableWeapon weapon;
// Is is okay to specify the number of bullets?
public ReloadWeaponCommand(ReloadableWeapon weapon, int bullets){
this.weapon = weapon;
this.reloadBullets = bullets;
}
#Override
public void execute() {
weapon.reload(reloadBullets);
}
}
Client:
ReloadableWeapon chargeGun = new ReloadableWeapon(10);
Command reload = new ReloadWeaponCommand(chargeGun,10);
ReloadWeaponController controlReload = new ReloadWeaponController(reload);
controlReload.executeCommand();
I was wondering, with the command pattern, with the examples I've seen, other than the object that the command is acting on, there are no other parameters.
This example, alters the execute method to allow for a parameter.
Another example, more close to what I have here, with parameters in the constructor.
Is it bad practice/code smell to include parameters in the command pattern, in this case the constructor with the number of bullets?
I don't think adding parameters into execute will be bad design or violate command pattern.
It totally depends on how you want to use Command Object: Singleton Or Prototype scope.
If you use Prototype scope, you can pass command parameters in Constructor methods. Each command instance has its own parameters.
If you use Singleton scope (shared/reused instance), you can pass command parameters in execute method. The singleton of the command should be thread safe for this case. This solution is a friend of IoC/DI framework too.
The very purpose of this pattern is to allow to define actions, and to execute them later, once or several times.
The code you provide is a good example of this pattern : you define the action "reload", that charges the gun with an amount of bullets=10 ammunition.
Now, if you decide to modify this code to add bullets as a parameter, then you completely lose the purpose of this pattern, because you will have to define the amount of ammunition every time.
IMHO, you can keep your code as it is. You will have to define several ReloadWeaponCommand instances, with different value of bullets. Then you may have to use another pattern (such as Strategy) to switch between the commands.
Consider a case you have 95 bullets in hand in starting, and you have made 9 commands with 10 bullets and 1 command with 5 bullets. And you have submitted these commands to Invoker, now invoker doesn't have to worry about how much bullets are left. He will just execute the command. On the other hand if invoker has to provide the no of bullets at run time then it could be the case supplied number of bullets are not available.
My point here is that Invoker must not have to worry about any extra information needs to execute the command. And as mentioned in wiki "an object is used to encapsulate all information needed to perform an action or trigger an event at a later time"
Using the Command Pattern with Parameters
Consider the related 'Extension Patterns' in order to hold to a Top-Down Control paradigm 'Inversion of Control'.
This pattern, the Command Pattern, is commonly used in concert with the Composite, Iterator, and Visitor Design Patterns.
Commands are 'First Class Objects'. So it is critical that the integrity of their encapsulation is protected. Also, inverting Control From Top Down to Bottom Up, Violates a Cardinal principle of Object Oriented Design, though I see people suggesting it all of the time...
The Composite pattern will allow you to store Commands, in iterative data structures.
Before going any further, and while your code is still manageable, look at these Patterns.
There are some reasonable points made here in this thread. #Loc has it closest IMO, However, If you consider the patterns mentioned above, then, regardless of the scope of your project (it appears that you intend to make a game, no small task) you will be able to remain in control of lower-level dependency. As #Loc pointed out, with 'Dependency Injection' lower class Objects should be kept 'in the dark' when it comes to any specific implementation, in terms of the data that is consumed by them; this is (should be) reserved for the top level hierarchy. 'Programming to Interfaces, not Implementation'.
It seems that you have a notion of this. Let me just point out where I see a likely mistake at this point. Actually a couple, already, you are focused on grains of sand I.e. "Bullets" you are not at the point where trivialities like that serve any purpose, except to be a cautionary sign, that you are presently about to lose control of higher level dependencies.
Whether you are able to see it yet or not, granular parts can and should be dealt with at higher levels. I will make a couple of suggestions. #Loc already mentioned the best practice 'Constructor Injection' loosely qualified, better to maybe look up this term 'Dependency Injection'.
Take the Bullets for e.g. Since they have already appeared on your scope. The Composite Pattern is designed to deal with many differing yet related First Class Objects e.g. Commands. Between the Iterator and Visitor Patterns you are able to store all of your pre-instantiated Commands, and future instantiations as well, in a dynamic data structure, like a Linked List OR a Binary Search Tree even. At this point forget about the Strategy
Pattern, A few possible scenarios is one thing, but It makes no sense to be writing adaptive interfaces at the outset.
Another thing, I see no indication that you are spawning projectiles from a class, bullets I mean. However, even if it were just a matter of keeping track of weapon configurations, and capacities(int items) (I'm only guessing that is the cause of necessary changes in projectile counts) use a stack structure or depending on what the actual scenario is; a circular queue. If you are actually spawning projectiles from a factory, or if you decide to in the future, you are ready to take advantage of Object Pooling; which, as it turns out, was motivated by this express consideration.
Not that anyone here has done this, but I find it particularly asinine for someone to suggest that it is ok to mishandle or disregard a particular motivation behind any established (especially GoF) Design pattern. If you find yourself having to modify a GoF Design pattern, then you are using the wrong one. Just sayin'
P.S. if you absolutely must, why don't you instead, use a template solution, rather than alter an intentionally specific Interface design;

How to correctly implement communication between Java classes

I'm a beginner in Java programming and I'm currently working on an app with more complex class structure and a GUI. This might be a stupid questions, but it is very hard to google, so I'm asking here.
I have a main class, looking like this:
package app;
public class App {
private FirstClass fc;
private SecondClass sc;
public App () {
fc = new FirstClass ();
sc = new SecondClass ();
// ... code continues ...
}
}
Say the SecondClass is defined outside of this .java file (like GUI forms are). Is there a way for me to access the "fc" instance (or other member variables of the App instance) from the "sc" instance (without passing the "this" pointer)? Something like:
class SecondClass {
public void someMethod() {
getWhoeverCreatedThisInstance().fc.getSomeData();
// ... code continues ...
}
}
And if not, what am I doing wrong? Should I design this differently? Maybe setting the "fc" as static? But what if I want more of my app's classes to communicate with each other, should I make them all static? What would be the point of having something non-static then? I could pass the "this" pointer of "App" or "fc" instance in the constructor of "SecondClass", but that solution just seems non-elegant when the number of classes that need this behavior rises.
Any ideas? Thanks in advance!
My suggestion is to implement a callback system with interfaces. Each of your classes communicating with each other should implement these.
The classes should Register to the creating class.
Then they can call a method in the creating class which invokes the interface method of each registered class and passed the data this way.
This SO answer might help
https://stackoverflow.com/a/18279545
If you want to develop GUI applications, you should really get into the basic concepts. This can be very time-consuming, but it is necessary, otherwise you will encouter strange behaviour. I will just give you a basic understanding to answer your question.
You think of simple console applications, where you usually have a single thread and passing around objects is valid. With multiple threads, this is fatal, even with static variables. Each variable or object can be modified concurrently and the other thread may not be able to 'see' the changes in time. This is a complex matter, since there are also caches and separate stacks for each thread. In short, fc may not always be synchronized in App and sc, therefore reads and writes may be inconsistent.
What to do now? Learn the concepts of GUI programming. Often you do not even have to share objects for simple things. If a GUI control triggers an action, use a Listener, look here. If you want to access a database for example, then just make a new connection object for each request or button click, whatever. This is simple to start, add complexity later.
A simple variant to share objects is to use the synchronized keyword, which ensures that a method or a field is only accessed by one thread at a time. Here is an example. Also look at thread-safe data structures provided by Java (java.util.concurrent).
For advanced purposes you would have a separate thread and you would connect them with Sockets to pass messages or data.

Java command Storage

Yes, this question is for a bot, but it requires little knowledge of bots. So please, don't be put off by that.
This question may seem similar to other PircBot questions, but bear with me, it isn't.
So, I've recently been working on an IRC bot based off of PircBot, and I've come upon a snag. I have a rapidly growing command list, and currently I'm using a horribly inefficient and very ugly block of these:
if(message.equalsIgnoreCase("!thatcommand"))
processMessage(channel,"returnforthatcommand"+sender);
I have a huge block of these where it just checks the message time after time for if it matches. That's my main problem. The process message method just sends the message after checking if I'm running the logger (printing the message to the console).
What I really want to do is to streamline it. I want to make some sort of chart, like a HashMap, that will process the strings accordingly. I've also considered making a Command class that stores the response and a boolean that tells whether or not a chatter has to be "opped" to use it. I've tried making files and started making a few attempts at HashMaps, but I could really use some direction on the simplest and/or most efficient way to go about this. I do have a few different "modes" for the bot, so making separate HashMaps for different privilege levels may be a good option.
One last thing: I later want to put the bot into a Jar file with a GUI for outside running (Eclipse takes ages to start up on this laptop), and I want to be able to make permanent changes to the command list through the bot itself as opposed to recoding it... That's why I was considering trying to reference a file, but then I had tons of problems with the program not being able to find said file.
Any suggestions?
Alright, for the people that don't like reading long things: I have sets of data that are called by a trigger String (message) and return a certain response String. How can I store these and call them in the simplest fashion, and how can I make it so that I can write things onto the list on the fly?
You could the use the Abstract Factory design pattern. It would be something like this:
public abstract class CommandFactory {
private static Map<String,Command> commands;
public static Command getInstance(String commandName) {
if (commands == null) initialize();
return commands.get(commandName);
}
private static void initialize() {
commands.put("commandA", new CommandA());
commands.put("commandB", new CommandB());
}
}
And write CommandFactory.getInstance("commandString") in the place of your if clauses.
Suggestion: Hashtable of objects implementing an interface which includes a method such as execute(). Use the hashtable to go from command to object, call its execute, done.
Yes, you'll need to initialize that table as your server starts up. Whether you do that from literal strings or have each actor announce its own keyword is up to you. The latter's probably more elegant but doesn't permit aliases.

Java - how much logic to put in the main class?

How much logic do you normally put in the main class? Should logic in the main class be at minimum, only instantiating other, specialized classes, and running all the tasks from there?
If you have any suggestions on this topic (or external articles), I'd appreciate it.
For small tools, I'm happy to have most or all of the logic in the main class - there tends to be less of a model to work with. (For very small tools, I confess I usually don't bother with unit tests. In particular, there's less benefit on the design side of things than there is if you're building something which will be a component in a larger app.)
For large scale apps, the main class is really just involved with setting things up and getting them in motion. If you're using a DI framework that can be very little code indeed; if you're not using dependency injection then the main class often acts as a "manual" dependency injection framework.
Should logic in the main class be at minimum, only instantiating other, specialized classes, and running all the tasks from there?
Yes. main method and its surrounding class should ideally be used only as an entry point to start the program. The mere existence of the surrounding class is just an artifact of the way Java programs are composed (everything must be inside some class), and there's no reason why it should contain other stuff in addition to the main method (but there definitely are reasons why it shouldn't).
When you get the interesting classes (those that form the actual program) separated, you open doors for all kinds of flexibility. Perhaps some of those classes could be used in some other projects. Perhaps some day you'll want to replace some of them with better implementations. Maybe you'll find a better order to instantiate all those classes - so just swap a few lines. Or how about executing lengthy startup loadings and instantiations in parallel threads? Just wrap some of them to suitable Executors. Good luck trying this with a 1000+ line main class.
This kind of flexibility matters for everything except maybe for 100-line elementary examples, prototypes and such. But given that even small tools tend to grow, why not do it correctly right from the beginning?
It's not so much a question of whether a class is "the main class". It's a question of how much logic is in the public static void main(String args[]) method. Ideally, it should contain very little logic. It should essentially construct one or two objects, and then call methods on those objects. One of those objects might be a this() - an instance of the main class, and that's ok.
You have to put the main() method somewhere - there's no need to create a special class just to hold that method.
As a general rule, try to avoid having too much in static methods - static methods can't be mocked for testing.
The main class should be an entry point to your program and should thus be relatively small. However this all depends on your actual program. If it's 50 lines long, it might be overkill to create two files for it.
As an example, consider the default Swing Application Framework Desktop Application as it would be generated by the NetBeans template, which is simple and short, and whose main() method is a single line that launches it:
public class MyApp extends SingleFrameApplication {
#Override protected void startup() {
show(new MyView(this));
}
#Override protected void configureWindow(java.awt.Window root) {}
public static MyApp getApplication() {
return Application.getInstance(MyApp.class);
}
public static void main(String[] args) {
launch(MyApp.class, args);
}
}

Categories

Resources