Advice for how Java classes should be organized [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I'm fairly new to Java but love it so far. My question is, i'm a little unfamiliar with Classes. I know what they are, and generally how to work with them as I'm not brand new to programming, but I would like a professionals opinion.
I'm currently writing a small multi threading program to launch parallel power shell sessions by spawning cmdlines for target machines in a csv, capture the output and write to a csv.
Should I put everything into one class and breakup the logical operations to methods within the class and string them together? Or should I make a Thread executor class, cmdline powershell class, a csv operations class, etc (My thought behind that was to allow code reuse, but that'll be kindove time consuming and in my mind impractical since i'd have to specify the datatypes and return types for new situations in the future).
Any help would be appreciated!

There is no "way" so to speak,
It's all your preference.
But just don't cram everything into one class.
Generally, you want to be as neat as possible.
In the future, you will thank yourself for using different classes.
If your project grows, and a bug is born, you don't want to be looking through one very long class, but instead simple broken up pieces.
Let's say you have these classes:
GPS,
Main,
Search
And someone reports a bug with the GPS not working.
Instead of looking everywhere saying, where did I put the GPS code,
it's right in front of your eyes!

I've went to everyones links and found the info very helpful. So far I've come up with this.
Make a package that contains classes that perform a specific set of tasks (also don't make utility kits that are very general). The package in my case would be called com.jt.threads.powershell or something.
Keep classes small and breakup the program by conceptual types. (ie. data reading and writing operations on a filesystem should be in one class with the focus on helping the package perform a certain task or range of tasks.)
Methods within classes should focus on getting, setting, changing the objects attributes or adding logic.
The program entry point should join it all together, except in the case of large applications, in which case an interface should be used (still learning about them).
With true OOP, i don't think it's a good idea to create code for reuse, unless it's supporting a range of very very very similar tasks (that way if I have to change something, it won't break other classes outside of the package).
Thank you all! I feel a lot better knowing that I'm on the right track. I was worried that by NOT making code reusable in a lot of situations that I was doing something wrong. I started programming in Python 6 months ago for my job, but I totally ignored classes and I want to have good programming habits and apply OOP as best I can going forward! Python is definitely convenient and a great starter language, but I wish I learnt Java first so I can get a solid grasp on OOP.

There is no “The way” to organize or group classes. Anything goes as long as it works as expected and you understand what you write.
As a Programmer you only need to,
1. Know and understand what you write.
2. Know and understand what other Programmer as written.

Related

My team mate seems to be offended often when I review his code [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
My team uses Scrum and we have code review (using Fisheye crucible), but from my observation working together for 2 years is that they care less about good code quality.
I am trying to learn code quality from reading Clean Code, and try to apply things I learn in code and by giving code review. I also had one sharing session on Clean code with my team and hoped that we all follow a good coding standard. Except me and another guy in the team, the rest are not interested in good coding practice nor the term Clean code at all.
I sense a great conflict during code review if I am the one who review my team mate's code. The is one guy that making the conflicts are so badly which I am getting tired of reviewing his code now, eventually I try to avoid a heated discussion that leads to nowhere.
Below are several examples in the my review for his code:
Asking him to create a variable with meaningful name for a magic number that was randomly put in code.
Asking to remove hard-coded values.
Asking to remove duplicate codes (for a particular business logic) in almost everywhere in one class, by asking him to create a method for those duplicate code instead (this time he commented in my code review that: "I could not do it because of this and that, why don't you just do it instead of asking me?" I told him I am a reviewer and not an author of the code and as per our standard the reviewer should not modify the code as she/he likes.)
He used static variables a lot, without any particular reasons. Even in unit tests, public static variables are declared many in the test classes. So I reviewed and put my comment asking to remove static variables instead; or if it is really needed then I suggest to have a #AfterClass method to destroy static variables when not being used (I said it's good for GC). He commented back, kind of: "Having these static variables won't cause any problems to GC for just running unit tests. Why he has to care for GC in unit tests?" and refused to change. My initial intention was that not only in unit tests, but also in production code too that we should not declare static variables as whatever we want.
His method is generally very long, contains of different logic putting in one method. Similar to one unit test method, generally just have two unit tests: one for failed case and one for successful case. So the failure conditions are all putting in one method and the rest are for successful case being put into one method. So when I reviewed, I asked for splitting each possible business logic for testing in one smaller method, and he refused to do so a few times.
My questions are:
I think he gets offended or I get him wrong?
Is there any of above examples I gave wrong comments?
Did I step on wrong line that I really offended him without me knowing?
When you have similar situation for 2 years without getting code review process improved, what would you do?
I tend to avoid reviewing his code and instead work on other stuffs on the board. Is that okay?
I do care for code quality as much as I can within my knowledge, it's a way to maintain a good product and also help myself to learn and improve technically. But getting into heated discussions and sometimes I feel annoyed for his comments are something I wish to avoid. But avoiding this situation for long is not a good solution I think.

When should I split a GUI class into several classes? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I'm working on what's basically my first GUI program in Java and it's been working well for me so far. Everything runs smoothly, however I want to make sure I use and understand solid programming principles.
For my GUI class I have about 300 lines of code (which I've come to understand is pretty small). I've been using SWT and this GUI one window for now. I have four tab items that each contain a different set of widgets for use. I intend on having a class for each tab to take care of their respective back end requirements.
As I've searched existing questions I've found the Single responsibility principle referenced on several occasions. To my understanding, one window per class would fit this principle. When (if ever) would I break a GUI into multiple classes outside of multiple windows?
Design principle are guidelines for writing good code. Single responsibility principle says we should have only single source of change for a class.
How do we know what is the source of change in a class ?
What can change in a class ?
Answers to these questions lies with the team directly in touch with the end users. For this it is important to reach to the team interacting with the client as soon as possible with a basic simple design. It is quite obvious , we will be asked to add more new features or add new requirements.
The process above will let us know what is the set of responsibilities that our class is performing is changing. We must put those set of behaviors in separate class(s). Now our existing class should communicate with the newly created classes via. Abstractions. This is dependency inversion. Now our class no longer is dependent upon the entities which change or which can potentially change with high probability. In the abstractions only the behaviors needed by the our old class are put. Implementation details are put in newly created concrete classes which extend the Abstraction class we have created.
From the very beginning, trying to figure out all the responsibilities and putting them in separate classes even when (they may never possibly change) will make the code scattered.
Large classes are verbose. They are not browsable, they have high risk of getting affected with changes un intentionally.
Regarding your specific question on when you would want to break out stuff into a separate class:
Let's assume you write an address book. You would probably want to present a contact's details in various places of the application. Or present multiple contacts at once. This would be accomplished by writing a separate class, like ContactDetailsPanel.
In general, most of the usual patterns apply to GUI classes as well: don't repeat yourself, single responsibility, and so on. One pattern I would like to point out when writing GUI code is MVC: Model-View-Controller. It's basically about separating business logic, presentation, and data.
You might want to take a look at what kind of things get separate classes in SWT, too.

Alternatives to "Manager" Java [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I currently have several "manager" classes in a project I am working on but have seen a lot of things that advise you to not use manager classes but don't seem to provide any alternatives in my situation. I have a ClickManager which contains a map of "clickable" objects and a ConfigManager which is responsible for loading and saving config files as the config class comes from an API I am using and is too stupid to load itself.
What are some alternatives to using "manager" in these cases?
Ward Cunningham once said (1) that every programmer should have a dictionary and a thesaurus on his or her desk. There's also a saying that there are only two hard problems in computer science: cache invalidation and naming things. (2)
The point is that naming things is important, and it's hard, and it's often neglected. This is why there are classes named Data and Manager littered around many code bases.
There are at least two potential things going on here. One is that the class is doing something reasonable, and it just needs to have a good, concise, descriptive name applied to it. For example, with ClickManager, does it dispatch events to the clickable objects? If so, maybe it's a Dispatcher. Does it lay out the clickable objects? Maybe it's a Positioner. Does it contain the clickable objects (as Erwin Bolwidt suggested)? Maybe it's a Container. Does it execute something in response to a click? Maybe it's an InteractiveCommand. It's sometimes helpful to think more specifically about what a class is doing in order to come up with a good name.
Another possibility is that the class has too many responsibilities, that is, it violates the Single Responsibility Principle. This is often the reason that something is hard to name, because it does a bunch of different stuff. Suppose the class simultaneously contains clickable objects, dispatches events to them, positions them, and executes commands. It's no wonder that it's hard to come up with a name other than Manager because it's doing all of these related, but independent functions. (Note that in many UI toolkits, these responsibilities have been separated into different classes.)
If this is the case it might be advisable to do some refactoring of a big Manager class into smaller classes, each of which has fewer (or one) responsibilities. It should be easier to come up with better names for those classes.
(1) I think it was at an OOPSLA about ten years ago.
(2) And off-by-one errors.

Is it worth to rewrite an entire program? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have a Java Project I have been working hard on for about 6 months (3 months hardcore) and it is around 8000 lines of code... However I have gotten much better then I was 6 months ago, and I have multiple classes that are full of messy, unorganized, and uncommented code.
Although my new code is much better, I often find myself lost when looking at some of my older code. Do you think it is worth the time to rewrite about 4000-5000 ish lines of code, that I think are not written well? I do not have much time to work, only about 3 hours a day max.
I don't know if I should accept that my old code was old, and just continue on, or if I should go back, completely rewrite most of my program and then have a easier path in the future. Or maybe there is a different solution? Any thoughts? Thanks! I really appreciate the help because currently I don't know if I should proceed knowing I may be just wasting time.
Yes!
Having been in the same position (more than once sadly) I can say that it is well worth it - if you come back to one of your projects in 6 months time - you'll look at that old code and wonder what the heck you were trying to do. Also, you may want to send examples of your work to prospective employers at some point, and if they look at code which is sloppy - it doesnt look good. Worse yet, if they look at the code and see two wildly different styles (sloppy vs neat) they will think you plagiarised the code.
You will also (most likely) find that rewriting those 4k lines of code, results in far fewer lines of code. Or, that it results in code that is far more reusable. Try to think about DRY when you recode (dont repeat yourself) if you use something more than once, make it a function or a class.
Also, you will save LOTS of time in the future when you come to extend/change your work.
Sure go for the rewrite. You are still learning and probably learned a lot since you first started. Now that you know more about programming and have a better idea of what the software requirements are you can probably make it much better.
Having said that, this is just a project for fun. In the business world, you would have to consider the time it takes to do a rewrite in terms of money spent and time and money wasted not adding new features etc and compare that with the amount of money wasted trying to maintain the old system to keep it running. Only if it's cheaper overall to do a rewrite will most businesses go for it.
It may be very beneficial as the other posters have mentioned. You should take this opportunity to write JUnit tests for all your new code (if you're not already doing so), as this will help you write well-encapsulated and decoupled code. Two really good books for reference are Refactoring by Martin Fowler (http://martinfowler.com/books/refactoring.html), and Working Effectively with Legacy Code by Michael Feathers (http://www.amazon.ca/Working-Effectively-Legacy-Michael-Feathers/dp/0131177052).
Have fun!
This is a common question asked by many developers, and it leads to other more important questions that will aid you on your journey to become a better programmer.
Ask yourself:
do i use javadocs in my code?
do i often repeat code?
do i use established patterns and stick with them for the entire project?
The reason i ask is that the answer to these questions will effect how readable your new code will be in the future even if you do rewrite your code.
A good excercise that will prove very useful in the real world is: can i optimize the existing code without rewriting it? this is a much sort after skill if ever you were to program professionally.

Reading source code [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
If you read other people's source code, how do you approach the code? What patterns are you looking for (datatypes, loops, use of control flow, ... )? How long can you read other people's code without getting bored? What is the most exciting patterns that you have discovered so far?
At first, I ignore the urge to change the code. Which is sometimes hard to do. But understanding first and change later saves yourself a lot of nasty "learning experiences."
Next if the format is bad, reformat. Use a code formatter if you have one. This is because you tend to look at the indentation and if that is bad, your understanding of the code is also questionable.
Then, if there are complex datastructures, I like to draw a little diagram. The challenge here is keep it as simple as possible. Large diagrams are fun on the wall, but most of the time, they are to cumbersome to look at. So it is wasted time.
If you finally understand what a piece of code does, write a comment. This is essential, because else you won't understand it the next time you are here.
The following step is to create unit tests. Now you can not only test the code, but you can also test your understanding of the code.
Last, if you understand it al and you know it can (and need to be) better, change it. But be sure to run the tests. Unless you are paid by each solved bug.
A hip new term for this is Code Spelunking.
Aside from the obvious "work from the top down" general approach, it depends on why I'm reading it: code review, trying to understand a bit of avaialable code to adapt for my own use, trying to learn a new technique, etc.
It also depends heavily on the language. If it is an OOPL, I'll probably do something like this:
Look first for the primary class relationships and try to understand the primary responsibility of each class.
Look at the interactions between classes to see how they collaborate.
Look at the interfaces of the key classes to see what "services" they offer their collaborators.
Look inside the non-trivial methods if it's important to understand how they are working instead of what they are responsible for.
thanks, if I understand correctly, first step is to identify the context, second identify API's, and place the API's in context. I just realize it is a bit like looking at a building or piece of art, you could focus on the material used, or the function of parts, try different perspectives, judge how parts fit in the whole... there is a nice piece of the process of discovery: here - how mathematicans think
It all depends on what type of code you are reading. Is it a web app, a service, a desktop app? When I do start reading other's code I usually start looking for design patterns used. Or for the framework-specific things. But again this is if you are doing a review. If you are reading for your own interest and to learn something there really is no answer - you should read and understand the code thoroughly.
Pick an item you understand in the final product and see how it is put together. If you've got the unit tests then they are a great help.

Categories

Resources