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

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.

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.

Change method accessibility in order to test it

I have a public method that calls group of private methods.
I would like to test each of the private method with unit test as it is too complicated to test everything through the public method ,
Is think it will be a bad practice to change method accessibility only for testing purposes.
But I dont see any other way to test it (maybe reflection , but it is ugly)
Private methods should only exist as a consequence of refactoring a public method, that you've developed using TDD.
If you create a class with public methods and plan to add private methods to it, then your architecture will fail.
I know it's harsh, but what you're asking for is really, really bad software design.
I suggest you buy Uncle Bob's book "Clean Code"
http://www.amazon.co.uk/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882
Which basically gives you a great foundation for getting it right and saving you a lot of grief in your future as a developer.
There is IMO only one correct answer to this question; If the the class is too complex it means it's doing too much and has too many responsibilities. You need to extract those responsibilities into other classes that can be tested separately.
So the answer to your question is NO!
What you have is a code smell. You're seeing the symptoms of a problem, but you're not curing it. What you need to do is to use refactoring techniques like extract class or extract subclass. Try to see if you can extract one of those private methods (or parts of it) into a class of itself. Then you can add unit test to that new class. Divide and conquer untill you have the code under control.
You could, as has been mentioned, change the visibility from private to package, and then ensure that the unit-tests are in the same package (which should normally be the case anyway).
This can be an acceptable solution to your testing problem, given that the interfaces of the (now) private functions are sufficiently stable and that you also do some integration testing (that is, checking that the public methods call the private ones in the correct way).
There are, however, some other options you might want to consider:
If the private functions are interface-stable but sufficiently complex, you might consider creating separate classes for them - it is likely that some of them might benefit from being split into several smaller functions themselves.
If testing the private functions via the public interface is inconvenient (maybe because of the need for a complex setup), this can sometimes be solved by the use of helper functions that simplify the setup and allow different tests to share common setup code.
You are right, changing the visibility of methods just so you are able to test them is a bad thing to do. Here are the options you have:
Test it through existing public methods. You really shouldn't test methods but behavior, which normally needs multiple methods anyway. So stop thinking about testing that method, but figure out the behavior that is not tested. If your class is well designed it should be easily testable.
Move the method into a new class. This is probably the best solution to your problem from a design perspective. If your code is so complex that you can't reach all the paths in that private method, parts of it should probably live in their own class. In that class they will have at least package scope and can easily be tested. Again: you should still test behavior not methods.
Use reflection. You can access private fields and methods using reflection. While this is technical possible it just adds more legacy code to the existing legacy code in order to hide the legacy code. In the general case a rather stupid thing to do. There are exceptions to this. For example is for some reason you are not allowed to make even the smallest change to the production source code. If you really need this, google it.
Just change the visibility Yes it is bad practice. But sometimes the alternatives are: Make large changes without tests or don't test it at all. So sometimes it is ok to just bite the bullet and change the visibility. Especially when it is the first step for writing some tests and then extracting the behavior in its own class.

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.

How to format methods in a class

I have nearly about 12 methods in my class. My doubt is, is there any formatting style like the called method has to be written next to the caller method" Is there any standard that maximum methods per class?
I would suggest reading Robert C. Martin's thoughts on this in his book Clean Code. He writes that a class should be readable as an article or a page of a book, so you preferable keep methods close to which they call into. Of course it is impossible to keep everything this way but you can head towards it. This eliminates the need to browse big sources frequently. For maximum methods Fowler has some rules also but it really depends on the class, but: keep methods and classes as small as possible.
It is impossible to keep calling and called methods next to each other, most obviously due to the fact that they can be in different classes.
There are no standards that would say "you can't have over 20 methods in a class", since it's not something that you can standardize (or rather it wouldn't make sense). With experience you'll learn to see if a class has too many methods (one indication would be that a class seems to be responsible for 2 different things, in which case you'd refactor the class into 2 different classes).
Generally speaking, 12 methods are too many for a class, I think you should think it over, if there are too many methods, maybe they are contradict to object-oriented thoughts. If you are OK with a specific language, you can get to know some design models such as MVC, maybe that will give you some ideas.

Alternative to creating separate class

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).

Categories