Alternative to creating separate class - java

At the moment I have two classes, first one is called "Building" and second one is called "Happening". Every building has its own name, and ArrayList of events (Happening) for one day. The class Happening has start time and end time. There can be many buildings and every building can have multiple events (Happening). But as you see I am using two classes to get this job done. I know it is probably the best way, but I am curious if I could handle all this with only one class (Building) without needing the Happening class. I tried using Happening as an inner class, but it won't work for me, because my main method that gets data from Building also needs to know this class, because my Building has a method to return all its happenings as an Array. So I am wondering if there is any alternative way of doing this.

Do not consider creating separate classes to be a bad thing. It makes your code easier to read, use and understand. While you undoubtedly could combine these into one class through the use of multi-dimensional lists/arrays or some other hack, the result would be a much less readable codebase. (Think of it as the same reason why, in database design, we try to separate things out into separate tables where we can, unless performance reasons dictate otherwise).

Related

Is it necessary to call a function/method outside the main body

Im currently learning java. SO I had this Question if it is necessary to create a method or function(create a class) outside the main body and then create its object and call it in main body?
There's several answers:
It is possible to have all the code of your program in a single main method and not split it into multiple methods or classes. That restricts what exactly you can do, but you could still get pretty far with that.
It's a terribly bad idea to do that, since your code will become really hard to read and you can't easily encapsulate individual sub-tasks and many design patterns won't be usable in such an environment
There is a technical restriction which limits how far you can go with that in Java and that is that the byte code of a single method can not exceed 64k bytes.
tl;dr: yes, but you shouldn't. Also no, you can't (for any serious code).
If you are asking if you can put all your application's code into the main method (without creating any other methods or classes): Yeah, I guess, but it is better to structure your code into smaller pieces. And there is a size limit for a method.
Also see:
https://softwareengineering.stackexchange.com/questions/141563/should-main-method-be-only-consists-of-object-creations-and-method-calls
https://softwareengineering.stackexchange.com/questions/154228/why-is-it-good-to-split-a-program-into-multiple-classes
It's not necessary to create a method/function outside the main body and then call it in main body, but if your code line in main is more i.e. 1000 or 2000 line then it is very difficult to manage code. So, if you create method outside main (In other class file) then call in main method using object then your code will be more readable.
It's part of the concept of object orientation in Java. You are not forced to use objects and methods apart from main, but I would really reccomended it. Java is instead of C based languages not procedural but object oriented.
As vimal said, This totally depends upon your code.
This question is not only limited to java but to all other languages too.
Suppose you are making an movie booking application for the explanation of this answer.
Then writing the whole code inside(Booking a ticket, deleting a ticket, Paying for a ticket purchased, and so on) main function would not be a good idea. One may think to write whole code in main method but it will make the code more tedious and complex. Whereas if you write your code in different functions, It will make your code modular, And also it will make your code easier for others to understand. Hope this helps to clear question.
It depends. You can do both, but there is a huge difference between them.
Java follows OOP paradigm. When you are defining a method outside your main(), you are associating the method with the class. You are defining the behaviour of a class.
However, if you are defining a method within main(), then it's just like any other method. You can call them as per your requirement.

What is the best way to Handle multiple threads in one class

I want to create a class that some of its methods on separate threads, and I'm not what us the best way to achieve that.
I've thought about three options:
Anonymous class for each method - On the one hand it's easier to implement, on the other hand it's less readable, and more difficult to maintain if in the future I'll decide not to run on a separate thread for a specific method.
implementing runnable and using a switch case statement - On the one hand it's more readable, and i can code the class such that it will be more maintainable in some if it's aspects. But, it will have a large switch case in the run method
Divide the class into multiple classes, and put each method that requires a separate thread in a separate class. - It doesn't have any of the disadvantages the previous options have, but it might lead to to many classes with only one method (run). Also, it's still has some mainatinability issues
Create a special class for each thread, and there run all necessary methods from all classes. - breaks SRP?
Thank you for your help
I want to create a class that some of its methods on separate threads, and I'm not what us the best way to achieve that.
Anonymous class for each method
I agree with your assessment. This will make the code less readable for sure. Not an immediate win. When it comes down to it, anonymous classes are true classes just done inline. I'd pay the extra characters in your Java file and create sub-classes. See below.
implementing runnable and using a switch case statement
This has certainly been done before and may be necessary if the multiple methods share a lot of data and methods. But I think that the below answer is better.
Divide the class into multiple classes
I think that this is the right thing to do. Each of your classes can implement Runnable so you can submit them to a thread-pool easily. If the methods need to share data and other methods then you could make the classes be subclasses in a larger class and make sure they are not static.
Create a special class for each thread
Not sure what "special" means here.

Game programming: passing main class to every object

I know it's not efficient, but I don't really know why.
Most of the time, when you implement your game you got a main class which has a loop and updates every frame and creates certain objects.
My question is why it's not considered efficient to pass the main class to every object in its constructor?
In my case, I developed my game in Java for Android, using LibGDX.
Thank you!
It increases coupling (how much objects depend on each other) and therefore reduces re-usability and has the tenancy to produce 'spaghetti code'. I don't really understand what you mean by not being 'efficient', but this is why you shouldn't do it.
You should also consider why you need that main class in every single object. If you really think you do, you might need to reconsider your system design. Would you mind elaborating on why you think you need it?
Mostly, it is a matter of coupling the code and making proper design decisions.
You should avoid dependencies between classes whenever possible. It makes the code easily maintainable and the whole design clearer.
Consider the case: you are creating a simulation racing game. You have a few classes for such entities: wheel, engine, gearshift knob, etc... and non-entities: level, player...
Let's say, you have some main point (i.e. GameEngine class where you create instances).
According to you're approach you want to pass GameEngine's instance in entities constructors (or related mutator methods). It's not the best idea.
You really want to allow wheels or breaks to have the knowledge about the rest of the world (such as player's informations, scores, level etc.) and give them access to it's public interface methods?
All classes should have at small level of responsibility (and knowledge about other items) as possible.
If you really need reference to some kind of main point object in you're classes consider using dependency injection tools, such as Dagger.
It won't make you're game design better, but, at least, forces you to favor composition over inheritance - what leads to create better code.
It's not entirely inefficient, since (afiak in the general case) passing a reference to a method is quite cheap when you consider the number of JVM opcodes required, however, a possibly more efficient way of doing this would be to make a static instance of the game class and access that static field from the other classes. You would have to test these two options yourself.
In addition, passing a reference to the methods could make maintaining the code harder, as you have ultimately added a dependency.

Java Design Questions - Class, Function, Access Modifiers

I am newbie to Java. I have some design questions.
Say I have a crawler application, that does the following:
1. Crawls a url and gets its content
2. Parses the contents
3. Displays the contents
How do you decide between implementing a function or a class?
-- Should the parser be a function of the crawler class, or should it be a class in itself, so it can be used by other applications as well?
-- If it should be a class, should it be protected or public class?
How do you decide between implementing a public or protected class?
-- If I had to create a class to generate stats from the parsed contents for eg, should that class be protected (so only the crawler class can access it) or should it be public?
Thanks
Ron
I think Andy's answer is very good. I have a few additions:
If you believe that a class will be extended in the future, you can set all your private methods (if any) to protected. In this way, any future extending classes can also access these.
I like the rule that a method shouldn't be longer than that you can see its opening and closing brackets ({ }) without scrolling. If a method is longer than that, try to split it up into several methods (private, protected or public by your preference). This makes code more readable, and could also save on lines of code.
So let's say a method is getting big and you split it up into several private methods. If these new methods are only used within the first "mother"-method, it makes sense to move all of that into a class of its own. In this way you will make the original class smaller and more readable. In addition, you will make the functionality of the new class easier to understand, as it is not mixed up with that of the original class.
The best guidance I've seen for these types of questions is the "SOLID Principles of OO Design."
http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod
The most basic of these principles, and the one that sort of answers your first question is the "Single Responsibility Principle." This states that, "a class should have one, and only one, reason to change." In other words, your classes should each do exactly one thing. If you end up needing to change how that one thing works, you only have one class to change, and hopefully just one place to make the change within that class. In your case, you would probably want a class to retrieve the content from the URL, another class to parse it into some sort of in-memory data structure, another class to process the data (if needed), and yet another class (or classes) to display the content in whatever format you need. Obviously, you can get carried away with classes, but it's typically easier to test a lot of small, single-operation classes, as opposed to one or two large, all-encompassing classes.
The question on public vs. protected depends on how you plan to use this code. If your class could be used independently outside your library, you could think about making it public, but if it accomplishes some task which is specific or tied to your other classes, it could probably be protected. For example, a class to retrieve content from a URL is a good general-purpose class, so you could make it public, but a class that does some specific type of manipulation of data might not be useful outside your library, so it can be protected. Overall, it's not always black and white, but ultimately, it's usually not a huge deal either way.
I like to think of classes as "guys" who can do specific stuff "methods".
In your case, theres a guy who can fetch the content of an url if you tell him which url that is.
Then there is this another guy, that is really good at parsing content. I think he does that with a tool called rome, but i'm not sure. he keeps that private (hint ;) )
Then we have that third guy, who displays stuff. He's a bit retarded and only understands stuff that "another guy" produces, but hey thats fine.
Finally the project needs a boss guy, who gives orders to the other 3 guys and passes messages between them.
ps: I never really though about making classes protected or not. Usually they are simply public without any specific reason. As long as it don't hurt, why bother?

How to deal with monstrous Struts Actions?

I inherited this gigantic legacy Java web app using Struts 1.2.4. I have a specific question regarding Actions. Most of the pages have exactly one Action, and the processExecute() methods are hideous monsters (very long and tons of nested if statements based on request parameters).
Given that Actions are an implementation of the command pattern, I'm thinking to split these Actions into one Action per user gesture. This will be a large refactoring though, and I'm wondering:
Is this the right direction?
Is there an intermediate step I could take, a pattern that deals with the mess inside the monolithic actions? Maybe another command pattern inside the Action?
My way of dealing with this would be:
dont do 'everything at once'
whenever you change anything, leave it better than you found it
replacing conditionals with separate Action implementations is one step.
Better yet: Make your implementations separate from the Action classes so that you can use it when you change frameworks
Keep your new Command implementation absolutely without references to Struts, use your new Actions as Wrapper around these implementations.
You might need to provide interfaces to your Struts ActionForms in order to pass them around without copying all the data. On the other hand - you might want to pass around other objects than ActionForms that are usually a bunch of Strings (see your other question about Struts 1.2 ActionForms)
start migrating parts to newer & better technology. Struts 1.2 was great when it came out, but is definitely not what you want to support in eternity. There are some generations of better frameworks now.
There's definitely more - Sorry, I'm running out of time here...
Struts Actions, in my mind, shouldn't have very much code in them at all. They should just interact directly with the request and response - take some data from a form or a request parameter, hand that info off to the Service Layer, and then put some stuff in a Response object or maybe save some data in the user's session.
I'd recommend staying away from doing inheritance with action classes. It sounds like a good idea at first but I think sooner or later you realize that you're shoe-horning things more than you're actually making the code base robust. Struts has enough base actions as is, if you're creating new ones you've probably got code in the web layer that shouldn't be there.
That is just my personal experience.
I've dealt with this type of thing before. A good first step is to insert another base class into the inheritance chain between Action and one of the original monstrous action classes (lets call it ClassA). Especially if you don't have time to do everything at once. Then you can start pulling out pieces of functionality into smaller parallel Action classes (ClassB, ClassC). Anything that's common between the original ClassA and the new refactored classes can be pulled up into the new base class. So the hierarchy now looks like this:
Original Hierarchy: New Hierarchy:
Action Action
| |
| BaseA
(old)ClassA |
+--------+----------+
| | |
ClassB (new)ClassA ClassC
Go one method at a time
Record some test cases you can play back later. Example here (make sure to hit as many paths through the code as you can, i.e. all user gestures on the page that call this action)
refactor the method to reduce its complexity by creating smaller methods that do smaller things.
Re-run tests as you do this
At this point, you have refactored version of the big huge annoying method. Now you can actually start creating specific actions.
You can use your newly refactored class as a base class, and implement each specific action as a subclass using those refactored small methods.
Once you've done this, you should have a good picture of the logic shared between the classes and can pull-up or push-down those methods as needed.
It's not fun, but if you will be working on the codebase for a while, it will save you time and headaches.
Tough problem but typical of early web app development.
First things first you need to start thinking about which logic constitutes business behavior, which logic constitutes "flow" (i.e. what the user sees), and which logic gets the content for what he sees.
You don't have to go down the route of factories and interfaces and all that; retroactive implementation is far less useful... but consolidating business logic and data retrieval logic into delegates of some kind... and leaving the struts actions to determine page flow based on success/failure of that logic.
From there you just have to take a few weeks and grind it out
One long method is never good, unless it happens to be a single switch statement where the cases are very short (token parsing or something like that).
You could at least refactor the long method into smaller methods with descriptive names.
If at all possible you could start your method with recognizing what it is it should do by examining the form, and then if/else your way to the various options. No nested ifs though, those tend to make code unreadable. Just
enum Operation {
ADD, DELETE;
}
...
Operation operation = determineOperation(form);
if (operation == Operation.DELETE) {
doDelete(form);
} else if (operation == Operation.ADD) {
doAdd(form);
}
If you can go that far you have your logic nice and clean and you can do whatever refactoring you want.
The hard part is to get your logic clear, and you can do that in steps. Don't choose a pattern untill you understand exactly what your problem is.
If you're planning to refactor the code you should make sure to write tests for the existing code first so you can be sure you haven't altered the functionality of it once you start refactoring.

Categories