Posts

Showing posts with the label optimisation

Java: Use Constants For Maintainability

Encountering repeated variable declarations, such as configurations and error messages, across multiple functions and classes is more common than you might think, especially with junior developers. Often, similar variables are needed in different parts of the code and are simply redeclared—leading to, you guessed it, a maintenance nightmare! The solution is simple: Constants ! Using constants makes your code more readable and maintainable because declared values are reusable, reducing careless errors. As a bonus, static variables are handled efficiently by the JVM. For best practice, make sure that constant variables are: static - The variable belongs to the class rather than any specific instance, so there's only one instance of the variable. final - The value cannot be reassigned after it's set. Example Usage: Disclosure:  This entry is based on a collection of my personal notes, and some of the information may be outdated or no longer relevant. If you notice any inaccu...

Java: Try-with-resources to Simplify Resource Management

Discovering try-with-resources many years ago was quite a revelation. Before this, I needed to be disciplined in handling resource management, especially with streams and database connections. Admittedly, I sometimes forgot to close resources, which inevitably led to memory leaks. With try-with-resources , the close() method is called automatically when exiting the block, preventing memory leaks caused by unclosed resources. Additionally, it simplifies your code by eliminating the need for an explicit finally block to handle resource cleanups. Classes with the AutoCloseable Interface: Database Connections Streams Files Sockets Beyond the standard classes that implement the AutoCloseable interface, you can also create your own classes that support this feature. For more details, read here:  Baeldung: Java – Try with Resources Disclosure:  This entry is based on a collection of my personal notes, and some of the information may be outdated or no longer relevant. If you ...

Java: For Loop Optimisation

When discussing for loops in Java, we often overlook whether certain formats are more efficient than others. Whether for readability or performance, understanding these differences can be important. The optimization here is minor (a micro-optimization, so to speak) and may vary in significance depending on factors such as the JVM used. However, in the spirit of writing efficient code, this approach can help your functions run more efficiently in certain scenarios. For more information and test data, check out this Stack Overflow thread:  For Loop Optimisation Disclosure:  This entry is based on a collection of my personal notes, and some of the information may be outdated or no longer relevant. If you notice any inaccuracies, please let me know in the comments. I appreciate your feedback and will correct the entry as needed. :)