Commenting out System.out.println - java

Do System.out.println(...) calls pose any effect if left in BlackBerry code or any other programming language?
When removed, the compilation time may be reduced, but is there any particular other reason to remove them?

There are a couple of things you need to know before using System.out.println() on Blackberry:
Once you print out something to the standard output any person that has your application installed on the device will be able to see them. All they need to do is to attach the device to the simulator and run in debug mode. So make sure you do not print out anything sensitive such as passwords, class names etc. in the released application.
The performance overhead that the System.out.println() itself makes is minimal, especially when the output stream is not attached to anything (i.e. Device is not connected and not in debug mode).
I myself rather use Blackberry preprocessor to be able to disable all logs before making a release. For this reason I define a logging directive LOGGING and then in my code:
//#ifdef LOGGING
System.out.println("LOGGING is enabled");
//#endif
For more on how to use preprocessors in Blackberry Eclipse plugin see this.

I prefer to use a flag to disable sysouts. Sysouts are really slow if you use them a lot, eg. in loops.

If you don't intend to use the output for anything like debugging ect. then it's best to take it out. Your program will only run as fast as the line can be output so in theory the less system.out line you have the faster the process will be.
Hope this helps.

Runtime might be also reduced, as the statements are actually executed - even if the user doesn't see the output on the screen. If you're using a lot of these (e.g. in tight loops) or you're passing to them Objects with expensive toString() methods, the useless output may be slowing you down.
Also, if you're passing String as an argument, those will take some space in bytecode and in memory. You on your souped-up machine with 173 PB of RAM may not care, but there are resource-constrained systems (such as mobile devices).

You should be able to use Ant to preprocess these lines out of your source code. (Make sure that none of them have side-effects!)

I don't know specifically about Blackberry, but if your program is writing to an unknown device (i.e. you are not sure where standard out is going), there may be a potential for your app to occasionally/sporadically/inexplicably block momentarily in the attempt to write.

Create your own method, i.e. :
public static void consoleMessage(String msg){
if(DEBUG_FLAG){
System.out.println(msg);
}
}
Then use only this throughout your code. It will save you the time for changing all the lines.

Use something like Log4J instead of system out print statements, it gives you much more flexibility

Keeping System.out statements isn't that bad a thing to do usually. Users might be able to see them so it doesnt always look good in a production environment. A better idea is to use a logging framework such as java.util.logging or log4j. These can be configured to dump output to the console, to a file, a DB, a webservice ...
Keep in mind that just becuase you can't see the output it doesn't mean that no work is being done at runtime. The JVM still has to create a String to pass to system.out (or a log statement) which can take a fair bit of memory/CPU for large/complex objects like collections.

Sysout statements access a synchronized, shared resource, which causes synchronization between threads using it. That can prevent memory consistency bugs in multithreaded programs if there is no other code which enforces synchronization. When the sysout statements are removed, any existing memory consistency bugs in the code may surface for the first time.
For an example of this effect, see: Loop doesn't see changed value without a print statement.

It's not an object and it doesn't have any memory attached to it so there shouldn't be any effect besides the time to run it and compile it. And of course readability maybe lol

Related

Is there a way to tell if there is code not being used in java?

Whenever I program, I seem to accumulate a lot of "trash" code, code that is not in use anymore. Just to keep my code neat, and to avoid making any expensive and unnecessary computations, Is there an easy way to tell if there is code that is not being used?
One of the basic principles which will help you in this regard is to reduce visibility of everything as much as possible. If a class can be private don't make it default, protected or public. Same applies for methods and variables. It is much easier when you can say for sure if something is not being used outside a class. In cases like this even IDEs like Eclipse and IntelliJ Idea will suggest you about unused code.
Using this practice while developing and refactoring code is the best way to clean unused code confidently without the possibility of breaking the application. This will help in scenarios even when reflection is being used.
It's difficult to do in Java since it's a reflective language. (You can't simply hunt for calls to a certain class or function, for example, since reflection can be used to call a function using strings that can only be resolved at runtime.)
So in full generality, you cannot be certain.
If you have adequate unit tests for your code base then the possibility of redundant code should not be a cause for concern.
I think "unused code" means the code that is always not executed at runtime. I hope I interpreted you correctly.
The way to do a simple check on this is very easy. Just use IntelliJ IDEA to write your code. It will tell you that parts of your code that will never be executed and also the parts where the code can be simplified. For example,
if (x == 5) {
}
And then it will tell you that this if statement is redundant. Or if you have this:
return;
someMethod();
The IDE will tell you that someMethod() can never be reached. And it also provides a lot of other cool features.
But sometimes this isn't enough. What if you have
if (x == 5) {
someMethod();
}
But actually in your code, x can only be in the range of 1 to 4? The IDE won't tell you about this. You can use a tool that shows your code coverage by running lots of tests. Then you can see which part of your code is not executed.
If you don't want to use such a tool, you can put breakpoints in your methods. Then run some tests by hand. When the debugger steps through your code, you can see exactly where the code goes and exactly which piece(s) of code is not executed.
Another method to do this is to use the Find/Replace function of the IDE. Check if some of your public/private methods are not being called anywhere. For example, to check whether someMethod() is called, search for someMethod in the whole project and see if there are occurrences other than the declaration.
But the most effective way would be,
Stop writing this kind of code in the first place!
i think the best way to check that is to install a plugin of coverage like eclemma and create unit and integration tests to get 100% of coverage of the code that accomplish the use code/task you have.
The code that don't need to be tested or don't pass over it after the tests are completed and run, is code that you are not using
Try to avoid accumulating trash in the first place. Remove stuff you don't need anymore. (You could make a backup or better use a source code management system.)
You should also write unit tests for your functions. So you know if it still works after you remove something.
Aside from that, most IDEs will show you unused local variables and private methods.
I do imagine situation when you have app developed by years and some part of your functions doesn't used anymore even they still working. Example: Let's assume you make some changes on internal systems when specific event occured but it is not occurs anymore.
I would say you could use AspectJ to obtain such data / log and then analyze after some time.

do comments have any effect on the android runtime?

I like to add...
...
System.out.println(" *description* ");
...
... lines to my code blocks for debugging purposes (mostly to catch runtime and logic errors. I usually delete them, but lately I have been just adding "//" before them so that they stay there to prevent having to retype them, slash, to use them as a marker reminding myself that I've already debugged that part.
Is better to delete these "debug println's" rather than adding "//" before them, or if they would both have the same effect on the app runtime ?
Any insights appreciated.
No. By design comments are not used as part of the code (except with certain cases of javadocs appearing in jars).
The compiler which translates the source code into JVM bytecode will simply ignore the comments,
Comments and commented out code have no effect on runtime performance. None whatsoever. (Not even javadoc comments!!)
However, leaving "commented out" debug statements in your code is bad practice because it makes your code a lot harder to read. Obviously, this is not a concern while you are debugging ... but you shouldn't leave them there in the long term.
I recommend two alternatives:
Replace the println calls with use of a logging framework, and log those things at "debug" level. You need to be a bit careful because logging does have an impact on performance. But there are ways to minimize the impact ... depending on the framework you are using.
Use your version control history to keep a snapshot of the code with the debug statements active. Then delete them.
See also:
Commenting out System.out.println

how can I get the History of an object or trace an Object

I have a requirement, where support in my application a lot of processing is happening, at some point of time an exception occrured, due to an object. Now I would like to know the whole history of that object. I mean whatever happened with that object over the period of time since the application has started.
Is this peeping into this history of Object possible thru anyway using JMX or anything else ?
Thanks
In one word: No
With a few more words:
The JVM does not keep any history on any object past its current state, except for very little information related to garbage collection and perhaps some method call metrics needed for the HotSpot optimizer. Doing otherwise would imply a huge processing and memory overhead. There is also the question of granularity; do you log field changes only? Every method call? Every CPU instruction during a method call? The JVM simply takes the easy way out and does none of the above.
You have to isolate the class and/or specific instance of that object and log any operation that you need on your own. You will probably have to do that manually - I have yet to find a bytecode instrumentation library that would allow me to insert logging code at runtime...
Alternatively, you might be able to use an instrumenting profiler, but be prepared for a huge performance drop when doing that.
That's not possible with standard Java (or any other programming language I'm aware of). You should add sufficient logging to your application, which will allow you to get some idea of what's happened. Also, learn to use your IDE's debugger if you don't already know how.
I generally agree with #thkala and #artbristol (+1 for both).
But you have a requirement and have no choice: you need a solution.
I'd recommend you to try to wrap your objects with dynamic proxies that perform auditing, i.e. write all changes that happen to object.
You can probably use AspectJ for this. The aspect will note what method was called and what are the parameters that were sent. You can also use other, lower level tools, e.g. Javasist or CgLib.
Answer is No.JVM doesn't mainatain the history of object's state.Maximum what you can do you can keep track of states of your object that could be some where in-memory and when you get exception you can serialize that in-memory object and then i think you can do analysis.

Hooking an existing method in Java

I want to hook the method System.out.print in Java and have the ability to read/change the variables used in the method before the part of the method is called that actually adds the string to whatever the output stream is.
In C++ I would just detour the function, or set an int3 instruction so I could access the registers but in java I have no idea how to accomplish something similar.
You can rewrite the byte code of the methods, and in the process capture/change the local variables. It is not trivial. See some notes here.
Maybe what you really want is a java debugger? You can connect a debugger to a remote process, add a breakpoint, and capture/change the local variables pretty easily using eclipse.
What is the real problem you are trying to solve?
Have a look at this link.
He sneakily defines a static anonymous class so that System.out points to something different, and therefore print and println will route through that object.
You can reassign System.out (and System.err) to another object which does what you want to do with it. Said object usually gets the old System.out value so that output can be made in the end.
This is usually done in main() and influences the whole JVM.
We use this to have automatic wrapping at 130 columns in a very peculiar setting where longer lines are truncated.
Since JDK 1.1, the System.setOut and System.setErr methods are added to enable applications to hook the streams.
Link : http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#setOut(java.io.PrintStream)
http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#setErr(java.io.PrintStream)
#Nowayz Some time before i too had the same problem with me.
After some research i came to know About AOP. AOP i.e. AspectJ provides a facility to intercept the java APIs by applying the pointcuts before,after, around. So have a look at it .You can refer my question on stack .it may help you.

are there any potential issues with obfuscating an application?

I am building a spring mvc web application.
I plan on using hibernate.
I don't have much experience with obfuscating etc.
What are the potential downsides to obfuscating an application?
I understand that there might be issues with debugging the app, and recovering lost source code is also an issue.
Are there any known issues with the actually running of the application? Can bugs be introduced?
Since this is an area I am looking for general guidance, please feel free to open up any issues that I should be aware of.
There are certainly some potential performance/maintenance issues, but a good obfuscator will let you get round at least some of them. Things to look out for:
an obvious one: if your code calls methods by reflection or dynamically loads classes, then this is liable to fail if the class/method names are obfuscated; a good obfuscator will let you select class/method names not to obfuscate to get round this problem;
a similar issue can occur if not all of your application is compiled at the same time;
if it deals directly at the bytecode level, an obfuscator can create code that in principle a Java compiler cannot create (e.g. it can insert arbitrary GOTO instructions, whereas from Java these can only be created as part of a loop)-- this may be a bit theoretical, but if I were writing a JVM, I'd optimise performance for sequences of bytecodes that a Java compiler can create, not ones that it can't...
the obfuscator is liable to make other subtle changes to performance if it significantly alters the number of bytecodes in a method, or in some way changes whether a given method/piece of code hits thresholds for certain JVM optimisations (e.g. "inline methods with fewer than X bytecodes").
But as you can see, some of these effects are a little subtle and theoretical-- so to some extent what you need to do is soak-test your application after obfuscation, just as you would with any other major change.
You should also be careful not to assume that obfuscation hides your code/algorithm (if that is your intention) as much as you want it to-- use a decompiler to have a look at the contents of the resulting obfuscated classes.
Surprised no one has mentioned speed - in general, more obfuscated = slower-running code
[Edit] I can't believe this has -2. It is a correct answer.
Shortening identifiers and removing unused methods will decrease the file-size, but have 0 impact on the running speed (other than the few nanoseconds shaved off the loading time). In the meanwhile, most of the obfuscation of the program comes from added code:
Breaking 1 method into 5; interleaving methods; merging classes [aggregation transformations]
Splitting 1 arithmetic expression into 10; jumbling the control-flow [computation transformations]
And adding chunks of code that do nothing [opaque predicates]
are all common obfuscation techniques that cause a program to run slower.
You may want to look at some of the comments here, to decide if obfuscating makes sense:
https://stackoverflow.com/questions/1988451/net-obfuscation
You may want to express why you want to obfuscate. IMO the best reasons are mainly to have a smaller application, as you can get rid of classes that aren't being used in your project, while obfuscating.
I have never seen bugs introduced, as long as you aren't using reflection, assuming you can find something, as private methods for example will have their names changed.
The biggest problem centers around that fact that obfuscating programs generally make a guarantee of not changing the behavior of their target program. In some cases it proves to be very hard to do this -- for example, imagine a program which checks the value of certain private fields via reflection from a string array. An obfuscator may not be able to tell that this string also needs to be updated correspondingly, and the result will be unexpected access errors that pop up at runtime.
Worse still, it may not be obvious that the behavior of a program has changed subtly -- then you may not know that there's a problem at all, until your customer finds it first and gets upset.
Generally, professional-grade obfuscation products are sophisticated enough to catch some kinds of problems and prevent them, but ultimately it can be challenging to cover all the bases. The best defense is to run unit tests against the obfuscated result and make sure that all your expected behavior continues to hold true.
1 free one you might want to check out is Babel. It is designed to be used on the command line (like many other obfuscators), there is a Reflector addin that will provide a UI for you.
When it comes to obfuscation, you really need to analyze what your goal is. In your case - if you have a web application (mvc) are you planning on selling it as a canned downloadable application? (if not and you keep the source on your web servers then you don't need it).
You might look at the components and pick only certain parts to obfuscate ... not the whole thing. In general ASP.Net apps break pretty easy when you try to add obfuscation after you developed them due to all the reflection used.
Pretty much everything mentioned above is true ... it all depends on how many features you turn on to make it hard to reverse your code:
Renaming of members (fields/methods/events/properties) is most common (comes in different flavors: simple renaming of methods from something like GetId() to a() all the way to unreadable characters and removal of namespaces). BTW: This is where reflection usually breaks. Your assembly file may end up being smaller due to smaller strings being used too.
String encryption: this makes it harder to reverse your static strings used in your code. BTW: this paired with renaming makes it difficult for you to debug your renaming problems ... so you might turn it on after you have that working. This also will have to add code to decrypt the string right before it is used in IL
Code mangling ... this is what BlueRaja was refering to. It makes your code look like spagetti code - to make it harder for someone to figure out. The CLR does not like this ... it can't optimize things as easy and your final code will mostlikely proccess slower due to the additional branching and something not being inlined due to the IL rewriting used for this option. BTW: this option really does raise the bar on what it takes to reverse you source code, but may come with a performance hit.
Removal of unused code. Some obfuscators offer you the option to trim any code that it finds not being used. This may make your assembly a little smaller if you have alot of dead code hanging around ... but it is just a free benefit obfuscators throw in.
My advice is to only use it if you know why you are using it and design with that end in mind ... don't try to add it after you've finished your code (I've done that and it's not fun)

Categories