What other Java tricks are there?

I learned some time ago that I can open a connection in a try-with-resources and I don't need a finally to take care of closing it.
something like this:

 try(Connection c = DriverManager.getConnection(url, benutzer, passwort)){ //irgendwas mit der connection machen } catch(Exception e){ //handling } ;

I think it's really cool and wanted to ask what else is out there. Feel free to send me a link; I'll read through everything.

(1 votes)
Loading...

Similar Posts

Subscribe
Notify of
13 Answers
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Franky12345678
1 year ago

Java is a great language πŸ™‚

Try-with-resources is not a trick, but rather a syntax simplification that keeps the code narrow.

Example

Autsch:
public ResultSet getPerson(int id) throws SQLException {
	try (PreparedStatement stmt = getConnection().prepareStatement("SELECT bla bla FROM persons WHERE id = " + id)) {
		return stmt.executeQuery();
	}
}


Besser:
public PersonData getPerson(int id) throws SQLException {
	try (PreparedStatement stmt = getConnection.prepareStatement("SELECT bla bla FROM persons WHERE id = ?")) {
		stmt.putInteger(1, id);
		try (ResultSet set = stmt.executeQuery()) {	
			if (set.next()) {
				return new PersonData(set.getString("name"), set.getInt("age"));
			}
			return null;
		}
	}
}


Das zweite mit normalem try, funktional identisch:
public PersonData getPerson(int id) throws SQLException {
	PreparedStatement stmt;
	try {
		stmt = getConnection.prepareStatement("SELECT bla bla FROM persons WHERE id = ?"
		stmt.putInteger(1, id);
		ResultSet set;
		try {	
			set = stmt.executeQuery();
			if (set.next()) {
				return new PersonData(set.getString("name"), set.getInt("age"));
			}
			return null;
		} finally {
			set.close();
		}
	} finally {
		stmt.close();
	}
}

(Was im Beispiel fehlt: getConnection() ist eine Methode, die prüft, ob die bestehende Verbindung noch gut ist und ggf. erneut âffnet, bevor sie zurückgegeben wird. Ein Pool mit einer Verbindung sozusagen. Diese ist bei Programmende natürlich zu closen. Ich bevorzuge Pooling gegenüber immer âffnen/schließen neuer Verbindungen für jeder Abfrage. Gibt Libraries, die genau diese FunktionalitÀt bereithalten).

I always meet this Autsch method from colleagues, where the ResultSet is chopped somewhere outside. What is often forgotten (from ignorance): Also the ResultSet is to close. If you don’t do it, most drivers do it when closing the connection from which it comes. A closed ResultSet is returned.

Who programmed and used SQL objects beyond the query has nix of this simplification.

Memory leak. When testing with a manually managed connection, it works a few times but as soon as load gets on or you use a PoolLibrary, the most adventurous bugs are created with time. The try-with-resources are vllt here. “contra-productive” because the ResultSet is still needed.

In the second example with try-with-resources it can be seen immediately what is considered in the service life.

The third variant is functionally identical to the second, but in relation to a pretty chunk.

Oh, yes, your question:

Java features that I often and like to use:

  • Collection.stream() – saves these clobular loops that fish anything out of an array, process and return to a new array
  • () -> {} – abbreviation for Runnable and Callable
  • Interfaces – Helpful in structuring and forming APIs where only certain methods should be externally visible
  • Generics prevents a lot of casting (such as ArrayList does)
  • ExecutorService – It’s hard to get to workerthreads.
  • InputStream, OutputStream and ByteBuffer
AldoradoXYZ
1 year ago
Reply to  Franky12345678

I hope that no one in the professional environment is still making connections and statements.
But there might be something “Cooles”, take JPA/Hibernate for ORM.

AldoradoXYZ
1 year ago

Hey,

AutoCloseable It’s nice.

Otherwise, it is worth looking at the features of the new Java versions.

Generics for a long time (1.5), but very powerful. Records, especially suitable for DTOs.
Streams are now very much used, who writes “normal” loops in which the loop index is probably wrong xD.

Not really Java specific, but always worth a look are Desing Patterns:
Singleton, Command-Pattern, Observer-Pattern, Factory batteries, Builder batteries

And then very large natural frameworks like Spring (Spring boot), JPA/Hibernate for DBs, who simply take a massive job and often bring a clear structure and structure (keyword Dependency injection).
Of course you can also use without a framework, for example, if you build a smaller project on dependency injection – you don’t need a big framework for that.

For me, the “largest trick” is once Clean code to have read. You’re lucky that the code examples are written with Java. Even though the book is also useful for many other languages.
Then you know something about Single Responsibility Principle and facilitates his life in general and above all the testability.
In a professional environment, I even expect developers to have a look at the book at least.

And for hobby developers, I’d say, “Look at everything,” but of course it doesn’t have to be. Private projects are usually rather small and especially developed with far fewer developers – there is cleanly structured code and high testability (private: what are tests? xD) maybe not so important.

Greeting and fun

Xandros0506
1 year ago

I think it’s cool

You mean it’s cool that the Garbage collector should take care of what resources are no longer needed and then dispose of them?

Why not program it cleanly and do it properly?
You know what variables are no longer needed, you know when which resources are no longer needed. Then you can dispose of it yourself instead of relying on it to be automatically recognized and done. This is part of a neat and clean programming style and then also at runtime less memory….

Your “trick” is ultimately just a bad programming style.

AldoradoXYZ
1 year ago
Reply to  Mar3ike

AutoCloseable is interface and if you want, you can also implement it yourself.

This has nothing to do with the GarbageCollector eventually closing the resource. That’s not what the GarbageCollector does.

I can understand, of course, if someone thinks “man lets go finally, now that’s magic,” but that’s not at all.
As stated, the respective resource must implement the AutoCloseable interface and without it, of course, it is not possible. Means resources that do not have to implement AutoCloseable are still closed in the finally.
In this case it is worth looking at how AutoCloseable is implemented and then it quickly becomes clear that it has nothing to do with magic, or the GarbageCollector.
In essence, AutocloseAble is also cleaner because the resource itself is “best white” as it is properly closed.

Greeting

ZaoDaDong
1 year ago
Reply to  Xandros0506

It’s best to go back with “System.gc()” because of nem memory leak.

Franky12345678
1 year ago
Reply to  Xandros0506

You should read again how try-with-resources works.

In his code example, nothing leaks.

What is really bad here is the recommendation to call System.gc() (which would not replace .close() anyway!)

Lamanini
1 year ago
Reply to  Xandros0506

Then you can dispose of it yourself instead of relying on it to be automatically recognized and done.

This setting, which does not make a mistake in manual storage management, ensures that you only make more errors in storage cleaning.

This belongs to a neat and clean programming style

No, not with Java.

then also displays less memory at runtime….

With memory leak, it’s even more.

Soros25
1 year ago

Tenaire operations are you a term?

variable = bedingung ? wert1 : wert2

Instead if query with many brackets and so.

Soros25
1 year ago
Reply to  Soros25

Also super cool: Live Templates in IntelliJ https://youtu.be/XhCNoN40QTU

AldoradoXYZ
1 year ago
Reply to  Soros25

Live Templates are super πŸ˜€

There I have some for tests, loggers, etc etc

AldoradoXYZ
1 year ago
Reply to  Soros25

For ternary operators, you have to be very careful that the code remains legible.
The case you show is popular, so to assign.
It becomes difficult when ternary operators are nested several times.