What are the benefits of code blocks inside a method? - java

I've seen a method, which contains several blocks:
public class SomeClass {
public void someMethod() {
{
...
}
{
...
}
{
...
}
}
}
What are the benefits of such structure compared to the usual approach (put the code of each of the blocks into its own method and call them from someMethod) ?
What could be the reason the author of that source wrote it that way?

They can be useful for organising local variables:
{
List<String> someTemporaryThing = getTemporaryThing();
processTemporaryThing1(someTemporaryThing);
processTemporaryThing2(someTemporaryThing);
}
// other code that doesn't need to see someTemporaryThing
Of course, if you have more than a few lines in one of these it might be a good idea to make it a separate method.
I haven't found any other use for them.

This is legacy from C, where, originally, variables could be declared only at the start of a code block (i.e. right after a {).
In Java, it is only useful if, as you said already, you don't want to move the code in these blocks to separate methods, but want to keep their variables out of your method's scope. This could theoretically get some increase in performance compared to taking the stuff out to methods.

Related

Efficiency of accessing local variable vs field?

I read that you should avoid referencing a field too often in a method and instead just do it once, assigning it to a local variable, e.g.:
public static void doSomething() {
final Map<String, Integer> myMap = this.theMap;
//do some processing with myMap
}
The reason being efficiency, it just takes longer to access the field every time. Is that something you should worry about?
This is absolutely wrong.
It makes no difference at all how the variable is accessed (locally or using the class' member). In the end both fields will just contain a reference to the very same location in the memory without any impact to performance. Even when using a getter for your class' field it will make no difference as the JIT compiler will inline the method call once it noticed that this might improve performance.
Optimisationwise: it does nothing really. Any benefit if any would also be provided by an optimizer.
Only benefit is for you, the coder, by being able to name it differently so you know it's purpose in the method better.
public function test() {
Produce harvestedFruits = this.produce;
for(Produce fruit : harvestedFruits ) {
if(fruit.isRotten()) {
harvestFruits.remove(fruit);
}
}
}
And even then, I'd advice using getter and setter methods, so extended functions can do their own thing and testing becomes easier, and with documentation you provide nice highlights when hovering over the method in an relatively advanced IDE
Produce fruit = this.getProduce();

Grouping together "main" methods and their "helper" methods in Java

Avoiding large, monolithic methods is considered a good practice. I, personally, like to identify all pieces of code that serve a unique, unambiguous purpose and refactor them into a method. This way, the code reads more like a book.
The obvious problem with this approach is that my class ends up having a large number of methods available outside their intended scope, which I find highly undesirable.
There are ways to create nested functions in Java, but since the feature is not directly supported by the language, the resulting code is generally unfathomably ugly --at least, to me.
One could also use nested classes. What I don't like about this solution is that it's somewhat clumsy --is it?-- when some of the involved methods in the "grouping together" are overridden methods.
Rather vague question, but anyway I'd like to know how people go about doing this.
EDIT: Example of what I mean:
public class ClassWithTwoMainMethods {
private int var1;
private int var2;
public void doSomething(int a) {
if (conditionToCheck(a)) {
doSomethingSpecific();
}
}
private void doSomethingSpecific() {
...
}
private boolean conditionToCheck(int a) {
...
}
public void doSomethingElse(int a, int b) {
doSomethingElseHelper1(a+b);
doSomethingElseHelper2();
doSomethingElseHelper3();
}
private void doSomethingElseHelper1(int arg) {
...
}
private void doSomethingElseHelper2() {
...
}
private void doSomethingElseHelper3() {
...
}
}
At first glance, it isn't obvious that the class above has one "main" method with two "helpers" that should not be used anywhere else, and another "main" method with three helpers.
I use "worker objects" for this. A worker object exists only inside of a method and helps to achieve a goal. A typical example for this is String except that this worker is so useful that methods often return it.
So what I do is I group methods in a worker object, create it in a public API method (i.e. something is supposed to be used and documented in the public API) and let it do it's thing:
public void doSomethingElse(int a, int b) {
new Worker( a, b ).run();
}
This approach has some benefits:
You can test those workers in isolation.
It keeps code together that belongs together
It helps to avoid cluttering the namespace of a class. It does pollute the global namespace somewhat, though.
It allows you to reuse workers in different classes.
I can lessen the restrictions on fields for workers. For main classes, I prefer fields that don't change. In workers, fields are often more like local variables. That way, I can reduce the number of method parameters but I need to write more unit tests.

Java: What is considered more readable, "this" or no "this"

You don't really need to write the "this" keyword in Java. But is it better to do so anyway? Does it make sense to homogenise your style, i.e. if you use "this" once, you use it every time it's implied? Or is there a place where you would always use it and others where you never use it?
The general consensus is that you should use this only when it is necessary and not at any other time.
private String param;
public Construct(String param) {
// Usually the only place you need to use this.
this.param = param;
}
// A less common use of this
public Function() {
synchronized(this) {
// Some synchronized stuff.
}
}
As a rule I tend not to use it - if you can reduce redundant code then all the better.
There are however three places that I can think of where the this keyword cant be avoided:
Constructors (delegating to another constructor in the same class)
public MyClass() {
this("Default Parameter");
Synchronizing on the current object
synchronized(this) {
Passing the current object to another class
public void methodOne() {
anotherClass.doSomething(this);
You sometimes need it in constructors where the field name is the same as the parameter, but this isnt really mandatory as you could simply rename the paramter:
public MyClass(String data) {
this.data = data
Other than these I cant think of too many other scenarios where I'd use the this keyword. I have seen it overused (on every method and field reference) and this can make the code very hard to read.
Use it only when you have to, or when you believe that it enhances code readability.
As a general rule you should avoid redundant syntax wherever it may arise. You will read lots of opinion to the contrary, mostly referring to a thoroughly mythical programmer who doesn't know about member variables, doesn't know what parentheses are for, and doesn't remember the rules of operator precedence he was taught in third grade. I've never met him in 40 years. That isn't enough to justify disfiguring your code for him on the assumption that he will (a) not understand it and (b) therefore break it. I've never seen that happen at all.
What I have seen is code produced by such a person. That's not a reason to dumb down your own code for him. The occasions on which someone has actually gone as far as to incorrectly rewrite a piece of code of mine are exactly two: once in 1979, where someone refactored a grammar to remove the operator precedence, which was dumb, and he shouldn't have done it, and another time in about 1992, but in both cases there is no way I could have written the grammar or the code that would have prevented it.
There are some places in code, where you couldn't skip this keyword, e.g. setters:
public void setValue(String value) {
this.value = value;
}
But if its possible it's better to skip:
public String getValue() {
return value;
}

What is alone { code } in Java for?

I recently read some code that uses a special syntax regarding {}, I've asked a more experienced Java developer, but he also can't answer.
public void doSomething() {
someWorks();
{
someVariables;
someMoreWorks();
}
someEvenWorks();
{
...
}
}
Why does the code author put these lines inside {}? I guess that the variables declared within the {} will be released right after execution exits {}, right, because I can't access these outside the {} anymore?
Yes, the only difference is for scoping.
Occasionally this can be useful for throwaway code such as micro-benchmarks where you want to be able to cut and paste a block and make a minor change, then potentially reorder the blocks.
I would rarely (if ever) have something like this in "real" code though.
This gives him a nested scope to declare "more local" variables.
I guess that the variables declared within the {} will be released right after exit {}, right, because I can't access these outside the {} anymore?
Depends on your definition of "release" (they will most likely not be garbage collected until the method ends, so if this is important, you might want to null them out), but yes.
Other rarely seen uses of curly brackets include class and instance initializers:
class A {
static {
// some class initialization code
}
{
// some instance initialization code
}
}
The fact that the author put those variables in {} indicates the scope of those variables will only be that of the method defined by the {}; in turn, those variables will be up for garbage collection once method finishes execution.

Change private member to default for testing

Is that good idea to change private class members to default(package access) for testing their behavior? I mean test case should destinate in test directory but in same package as tested member's class.
EDIT: All you guys tell the true. But classes have helper private methods often. And these methods can be complicated so need to be tested. And that is too bad - to test public methods for ensure correct working for private complicated methods. Don't you think so?
I generally prefer writing my classes and tests in a way that writing the tests against the public API makes sense. So basically I'm saying if you need to access the private state of your class under test you're probably already too involved in the internals of that class with your test..
No, it isn't. Because changing the test object may change the result. If you really need to call private members or methods during test, it's safer to add an accessor. This still changes the class, but with a lower risk. Example:
private void method() { /* ... */ }
// For testing purpose only, remove for production
#Deprecated // just another way to create awareness ;)
void testMethod() {
method();
}
OK - one more solution, if you need to test private methods: you can call any method with reflection and instantiation API.
Assuming, we have:
public class SomeClass {
private Object helper(String s, String t) { /* ... +/ }
}
then we can test it like
#Test public void testHelper() {
try {
SomeClass some = new SomeClass();
Method helperMethod = some.getClass().getDeclaredMethod("helper", String.class, String,class);
helperMethod.setAccessible(true);
Object result = helperMethod.invoke(some, "s", "t");
// do some assert...
catch(Exception e) {
// TODO - proper exception handling
}
}
I understand what you mean about needing to test private methods, and I also see why people say only test the public methods. I have just encountered some legacy code that has a lot of private methods, some of which are called by public methods, but some are threads, or called by threads, which are kicked off when the object is constructed. Since the code is riddled with bugs and lacks any comments I am forced to test the private code.
I have used this method to address the issue.
MainObject.cs
class MainObject
{
protected int MethodOne(); // Should have been private.
....
}
TestMainObject.cs
class ExposeMainObject : MainObject
{
public int MethodOne();
}
class TestMainObject
{
public void TestOne()
{
}
}
Since the test objects aren't shipped I can't see a problem with it, but if there is please tell me.
Testing trumps privacy modifiers. Really, how often is a bug caused by having "a little too much" visibility for a method? Compared to bugs caused by a method that was not fully tested?
It would be nice if Java had a "friend" option, like C++. But a limitation in the language should never be an excuse for not testing something.
Michael Feathers chimes in on this debate in "Working Effectively with Legacy Code" (excellent book), and suggests that this may be a smell of a sub-class that wants to be extracted (and have public methods).
In our shop (~ 1M LOC), we replace 'private' with '/TestScope/' as an indicator that a method should be effectively private, but still testable.
Trying to circumvent 'private' with reflection is IMHO a smell. It's making the tests harder to write, read, and debug in order to retain a 'fetish' of privacy, which you're working around anyway. Why bother?

Categories