How to manage a proper structure in a java project - java

I have encountered with this problem often. Couldn't think of a way to how to face this. Now I got this excellent forum!! I'm sure experts here will help me with this.
This is not a problem about a specific code segment like thing. I am capable (as I think) of doing some advance projects in java. It means, simply, I can finish the project to give the exact result.
But the problem is, though I can finish it some how, I'm not satisfied with the management of the classes etc. Actually I don't know how to properly manage it. I'll explain considering the project I'm currently working on (I'm not a professional coder, this will be for my self learning).
I'm working on a database management system (MySQL + Java). There I'm hoping to implement several features there. The flow will be, roughly, like this.
1. Login
2. Main window
Main window will be like this.
In the left panel you can select what you need to do.
Eg.
*. Add some entries to the database
*. Search database
*. Other..(will be add later)
Can some one please tell me how to manage all those things, two frames and several panels.
What I've done is like this.
I've written a managerClass which has the main method. Then It'll call loginFrame first. After validation, loginFrame calls a method in managerClass, to load mainFrame. But I keep a reference to the managerClass in all the frames, panels etc.. as I save all the required info in managerClass, like user name ect..
But when modifying and debugging, things become really really difficult. As I haven't done thing according to any specific rule. I'll have to modify almost all the classes to do a slight modification. I've though a lot and sea

From what I can understand of your application, your main issue is the coupling between your components and the different layers of the application (presentation, interaction control, domain logic). I would suggest using two design patterns (or styles) that may help here:
Model-View-Presenter: separates the Model/Domain logic from the presentation (View) from the logic of controlling user interactions. I've used it recently in a large application and I've found it really helps to separate concerns in a clean way and makes testing much more simple. Please don't confuse it with the Model-View-Controller model, which is close, but have many issues. There's a nice article by Martin Fowler describing these two patterns
Adopt an event based interaction between your components. Instead of the Login frame calling the Manager class, make it fire an event ("user authenticated"), which is handle by the interested components. For example, you may have a small user account details panel in the main window which is not displayed until this event is triggered. Unfortunately, I'm not aware of any event framework for plain Java (which I suspect if the what you are using for development) The one I use is for Google Web Toolkit.

Related

Android App Architecture : How should the packages be formed?

I am new to android programming. I often see that programmers create packages as collection of activities, fragments, adapters, etc. To me it seems more intuitive to put all java code required for an activity/screen in one place. For example: For home screen, I will keep the activity, fragments, adapters, custom views, etc all at one place.
Is there is any definite reason the the general practice or is it just a traditional practice ?
This has to do with creating components, reusable objects and code maintenance in a codebase as it grows. Your approach will work for a small application, and there is no rule against it. However, generally creating package/file structures according to the recommended and common approaches makes it easier to make modifications to code and work with others on the same project. Consider the following:
If you have many Activities spread across many packages or folders, then someone tasked with changing the UI will have to traverse those packages. That makes it difficult to identify UI patterns that could be used across Activities and even harder to use those patterns, since you will need to implement them in each package/folder.
This also creates a problem seeing less obvious patterns in non-UI components like data object models, view controllers, etc. For example, if you need a "user" object in two different Activities do you create 2 different objects? This is not reusable code.
So let's say you decide to reuse the "user" object so that you only have 1 class. Then do you sub-class in the other packages that need it in order to follow your pattern? Then if one UI element needs a new method, do you implement it in just that place? Or the base object?
Or do you make the "user" object public and reference it from other packages/folders? If this is your answer then you will begin to create objects in places based on the evolution of the code, instead of based on logic or ease of maintenance. Among other things, this makes it very difficult to train a new person on "where everything is" in your codebase. The "user" object will sit in one place, and then the "user account" object ends up where it is first needed, but not likely to be with the "user" object.
As a project grows to hundreds of classes, I think it is obvious that this approach becomes unmanageable for many applications. Classes will appear in packages based on the UI requirement, not based on the function it performs. Maintaining them becomes challenging.
For example in the case of Lollipop to Marshmallow, Apache http became deprecated. If you had this dependency scattered throughout your project, then you will be looking in a lot of places at how to handle this change. On a small project that might be fine, but on a larger project if you try to do this while other development is taking place, this can become a real mess since you are now modifying across many packages and folders instead of in only a few locations.
If, however, you have a Data Access Layer or Model Layer components that encapsulate the behavior in one or several folders, then the scope of your changes is easier to see to those around you. When you merge your changes into the project, it is easy for the people you work with to know if other components were impacted.
So while it is not necessary to follow these guidelines (especially for small projects), as a project grows and several or many people become involved in the development, you will see variations but the general practice is to group by purpose or function rather than group by UI / visual component. If you start off with some of this in place, you will have less work later to deal with the change. (However, starting with too much structural support early in a project can put the project at risk of never being completed...)
Several answers provides links to the guidelines. I hope this answer helps to explain why those guidelines exist, which I believe is at the heart of your question.
Is there is any definite reason the the general practice or is it just
a traditional practice ?
Yes. In my current application I have over 50 custom UI views and a few activities. At least 10 singleton controller and a lot of database model. So to not lost in the project, I'm using a tidy structure like this:
Activity
Adapter
Controller
Native
Model
-Database
-Rest
Ui
I suggest you to use this structure.
There are no official rules, well maybe best practices which I have not in mind.
I so we get now a opinion based answer:
I use the package names for grouping classes to a logical topic like adapters, activities, etc.
If you want another structure do it like you want, just it could confuse other devs.
Keep in mind that the package name should be unique so you should use a prefix like a domain you own or you are allowed to use (in reversed order of cause).
Check also this link where are some more ideas pointed out: http://www.javapractices.com/topic/TopicAction.do?Id=205
The first question in building an application is "How do I divide it up into packages?". For typical business applications, there seems to be two ways of answering this question.
Package By Feature
Package-by-feature uses packages to reflect the feature set. It tries to place all items related to a single feature (and only that feature) into a single directory/package. This results in packages with high cohesion and high modularity, and with minimal coupling between packages. Items that work closely together are placed next to each other. They aren't spread out all over the application. It's also interesting to note that, in some cases, deleting a feature can reduce to a single operation - deleting a directory. (Deletion operations might be thought of as a good test for maximum modularity: an item has maximum modularity only if it can be deleted in a single operation.)
Normally the activities are places in the main package and fragments, adapters, utils, models in their own packages like fragments in fragments packages and ISODateParser class could go into utils package.
You can find more about it in the Android Best Practices guide which contains best practices for android.
The guidelines about which classes should be placed under which packages are discussed under the Java packages architecture heading in the guide.
Hope it Helps!

How to refactor procedural start-up code?

I have a class (Android Activity) which handles start-up of my application. The application has some pretty complex start-up rules. Right now it looks like a bunch of spaghetti and I'm looking for strategies for refactoring it.
It's honestly such a mess I'm having problems hacking it down to provides pseudo code. In general there are some rules for start-up that are basically codified in logic:
Steps:
Check for error on last exit and flush local cache if necessary
Download settings file
Parse settings and save settings to local native format
Using the values in settings, do a bunch of 'house keeping'
Using a value in settings, download core data component A
Parse component A and load up local cache
During this logic, its also updating the user interface. All of this is handled in a zig-zagging, single monolithic class. Its very long, its got a bunch of dependencies, the logic is very hard to follow and it seems to touch way too many parts of the application.
Is there a strategy or framework that can be used to break up procedural start-up code?
Hmmm. Based on your steps, I see various different "concerns":
Reading and saving settings.
Downloading settings and components (not sure what a "component" is here) from the server.
Reading and instantiating components.
Flush and read cache.
Housekeeping (not really sure what this all entails).
UI updates (not really sure what this requires either).
You might try splitting up the code into various objects along the lines of the above, for example:
SettingsReader
ServerCommunicationManager (?)
ComponentReader
Cache
Not sure about 5 and 6, since I don't have much to go on there.
Regarding frameworks, well, there are various ones such as the previously mentioned Roboguice, that can help with dependency injection. Those may come in handy, or it may be easier just to do this by hand. I think that before you consider dependency injection, though, you need to untangle the code. All that dependency injection frameworks do is to initialize your objects for you -- you have to make sure that the objects make sense first.
Without any more details, the only suggestion that I can think of is to group the various steps behind well structured functions which do one thing and one thing only.
Your 6 steps look to be a good start for the 6 functions your init function should have. If #2 was synchronous (I doubt it), I would merge #2, #3 into a getSettings function.

How to correctly communicate between two different MVC Controllers in Java Swing?

Can you explain me how a Controller can call another Controller method in a simple but still correct way?
Please provide some code!
background:
I Have 2 different Controllers-View-Model and 2 libraries and they need to communicate between each other:
SettingsWindow/SettingsController/SettingsModel: Responsible for the app settings. The model is a singleton because I need the settings data all over the app;
A Library for Monitoring a directory which creates an event every time a file is created in a specific directory. The monitored dir path is defined in the SettingsModel; I'm using the Java 7 WatchService API for that;
A Library for Monitoring a webserver and download new files. The webserver address and the save directory are both defined in the SettingsModel; I'm using HttpsUrlConnection and a timer for that;
MainWindow/MainController/MainModel: Responsible for the main app window, which has a table that must be updated every time a new file is created in the monitored directory, and also everytime a file is downloaded by the above libraries.
So how do I correctly Instantiate and communicate those 4 different features?
How do their Controllers commnuicate between them, since they are all related?
How should I organize this project in terms of MVC?
PLEASE provide the basic MVC scaffold (skeleton) and show where I create the instances, where and how I call each others method. I'm new to Java, specially swing and mvc. I've read a lot, but I got stuck in this situation.
As suggested here, patterns such as model-view-controller and observer represent recurring design elements. A simple outline may illustrate the interaction of classes, but a general solution is beyond the scope of StackOverflow.
Still, it may be useful to look at how the principles might be applied. Suppose you are following the tutorial and have implemented a WatchService in a SwingWorker, as shown here. Now, suppose you want the main view, a JTable, to update itself in response to an arriving WatchEvent. You would arrange for the corresponding TableModel to register itself with the worker as a PropertyChangeListener, shown here and here. When the PropertyChangeEvent arrives, you update the TableModel and fire the appropriate event to update the JTable. The known TableModel implementations already include the required methods.
A similar approach would be used to update the table in response to data arriving from the web.
For settings, consider java.util.Preferences, mentioned here, or javax.jnlp.BasicService, discussed here.

Multiple "pages" in GWT with human friendly URLs

I'm playing with a GWT/GAE project which will have three different "pages", although it is not really pages in a GWT sense. The top views (one for each page) will have completely different layouts, but some of the widgets will be shared.
One of the pages is the main page which is loaded by the default url (http://www.site.com), but the other two needs additional URL information to differentiate the page type. They also need a name parameter, (like http://www.site.com/project/project-name. There are at least two solutions to this that I'm aware of.
Use GWT history mechanism and let page type and parameters (such as project name) be part of the history token.
Use servlets with url-mapping patterns (like /project/*)
The first choice might seem obvious at first, but it has several drawbacks. First, a user should be able to easily remember and type URL directly to a project. It is hard to produce a human friendly URL with history tokens. Second, I'm using gwt-presenter and this approach would mean that we need to support subplaces in one token, which I'd rather avoid. Third, a user will typically stay at one page, so it makes more sense that the page information is part of the "static" URL.
Using servlets solves all these problems, but also creates other ones.
So my first questions is, what is the best solution here?
If I would go for the servlet solution, new questions pop up.
It might make sense to split the GWT app into three separate modules, each with an entry point. Each servlet that is mapped to a certain page would then simply forward the request to the GWT module that handles that page. Since a user typically stays at one page, the browser only needs to load the js for that page. Based on what I've read, this solution is not really recommended.
I could also stick with one module, but then GWT needs to find out which page it should display. It could either query the server or parse the URL itself.
If I stick with one GWT module, I need to keep the page information stored on server side. Naturally I thought about sessions, but I'm not sure if its a good idea to mix page information with user data. A session usually lives between user login and logout, but in this case it would need different behavior. Would it be bad practise to handle this via sessions?
The one GWT module + servlet solution also leads to another problem. If a user goes from a project page to the main page, how will GWT know that this has happened? The app will not be reloaded, so it will be treated as a simple state change. It seems rather ineffecient to have to check page info for every state change.
Anyone care to guide me out of the foggy darkness that surrounds me? :-)
I'd go with History tokens. It's the standard way of handling such situations. I don't understand though, what you mean by "It is hard to produce a human friendly URL with history tokens" - they seem pretty human friendly to me :) And if you use servlets for handling urls, I think that would cause the whole page to be reloaded - something which I think you'd rather want to avoid.
Second, I'm using gwt-presenter and
this approach would mean that we need
to support subplaces in one token,
which I'd rather avoid.
If you are not satisfied with gwt-presenter (like I was :)), roll out your own classes to help with MVP - it's really easy (you can start from scratch or modify the gwt-presenter classes) and you'll get a solution suited to your needs. I did precisely that, because gwt-presenter seemed to "complicated"/complex to me - to generic, when all I needed was a subset of what it offered (or try to offer).
As for the multiple modules idea - it's a good one, but I'd recommend using Code Splitting - this type of situation (pages/apps that can be divided into "standalone" modules/blocks) is just what it's meant to be used for, plus you bootstrap your application only once, so no extra code downloaded when switching between pages. Plus, it should be easier to share state that way (via event bus, for example).
Based on what you have posted I presume you come from building websites using a server side framework: JSP, JSF, Wicket, PHP or similar. GWT is not the solution for building page-based navigational websites, like you would with the aforementioned frameworks. With GWT, you load a webapp in the browser and stay there. Handle user events, talk with the server and update widgets; using gwt-presenter is a good thing here as you are forced to think about separation of controller logic and view state.
You can really exploit all features of GWT to build a high-performance app-in-the-browser, but it is definately not meant for building websites (using hyperlinked pages that transfer request parameters via the server session).
This is by far the most widely asked question about GWT here # StackOverflow :)
"How do I define pages and navigation between them in GWT?" Short answer: "You don't."
Use Wicket instead, it runs on the App Engine just fine and enables you to define page bookmarks and all stuff you mentioned above. Look here: http://stronglytypedblog.blogspot.com/2009/04/wicket-on-google-app-engine.html

Management of Java string resources

I'm working on a java SE 1.5+ swing application, in conjunction with others. I'm wondering what the best way of managing string resources is. I understand the principles behind resource bundles etc. I'd like to avoid having one property file for every class that needs a string, as this seems a bit of overkill. Especially when you have a lot of classes that may only make a single reference to a string (say in an error handler). On the other hand it makes it easier when collaborating with others as you reduce the risk of merge conflicts.
It seems particularly cumbersome to have to load resource bundles, every time you need to display simple user feedback, likewise in error handlers, when many classes are involved.
What is the most effective way to manage strings in a fairly large application with hundreds of classes, many of which aren't GUI related, but need to pass informative messages back up to the GUI when exceptions occur.
I'm using NetBeans which generally creates a property file for each GUI class, for all text relating to buttons, labels etc.
What makes you think you have to have a separate properties file for every class? Generally you only need a few (or just one!) properties file (per language, of course).
Just call ResourceBundle.getBundle() with appropriate parameters - you can use the same bundle from multiple classes.
EDIT: Having one set of property files per dialog etc makes it easier to see where any particular string is coming from, but it makes it harder to reuse the same messages etc. Quite where the right balance is will depend on the application.
JSR 296 Swing Application Framework has support for resource management (and it looks like will be part of Java 7). SAF aims to pre-build parts of a Swing app that many people frequently need while encapsulating best practices. You probably don't want to tie to it directly but its worth taking a look at what they do to see whether it gives you some ideas. If I recall, they use cascading resource bundles with well-defined naming conventions. The latter means you know where to look and the former means that you can reuse properties across some portion of your package hierarchy.
Many JSR 296 resources collected here.
This may be naive, but what about storing them in a database, either embedded or external? This might simplify management, and changing languages more configurable.
I'm going to implement something similar to Launchpad's translation platform this year:
https://launchpad.net/+tour/translation
In a nutshell:
Concurrent translation
Phrase suggestions based on previously-entered phrases
Policies, e.g. Partly restricted and structured: anyone can suggest translations, while trusted community members review and approve new work
UPDATE
Of course, this builds on top of ResourceBundle etc, but is a nice way to manage all them strings ;-)

Categories

Resources