Java Puzzle 30 – The Unwelcome Guest

Merhaba Arkadaslar
Ornek kodumuzu inceleyelim ;

UnwelcomeGuest.java
static initialization block icerisinde  USER_ID static final variable’a deger atamak istiyoruz. Bunun icin getUserIdFromEnvironment metodunu kullaniyoruz , test amacli metotta bir exception throw etmekteyiz , bu durumda initialize islemini catch blogunda yapmak istiyoruz ve GUEST_USER_ID olacak sekilde assignment yapiyoruz.

Ornegimizi calistirdigimizda ciktimiz ne olacaktir ?

package _30.catch$.final$;

public class UnwelcomeGuest {
	public static final long GUEST_USER_ID = -1;
	private static final long USER_ID;
	static {
		try {
			USER_ID = getUserIdFromEnvironment();
		} catch (IdUnavailableException e) {
			USER_ID = GUEST_USER_ID;
			System.out.println("Logging in as guest");
		}
	}

	private static long getUserIdFromEnvironment() throws IdUnavailableException {
		throw new IdUnavailableException(); // Simulate an error
	}

	public static void main(String[] args) {
		System.out.println("User ID: " + USER_ID);
	}
}

@SuppressWarnings("serial")
class IdUnavailableException extends Exception {
	
}

Bu kod derleme hatasi verecektir !

The final field USER_ID may already have been 
 assigned

Java8 Spect’i soyle der ;

every blank final variable must be assigned at most once;

Yani bir final degiskene en fazla 1 kez assignment islemi yapilabilir.
Kodumuzu refactor edip problemi cozebiliriz ;

UnwelcomeGuestFixed.java

package _30.catch$.final$.fixed;

public class UnwelcomeGuestFixed {
	public static final long GUEST_USER_ID = -1;
	private static final long USER_ID = getUserIdOrGuest();

	private static long getUserIdOrGuest() {
		try {
			return getUserIdFromEnvironment();
		} catch (IdUnavailableException e) {
			System.out.println("Logging in as guest");
			return GUEST_USER_ID;
		}
	}

	private static long getUserIdFromEnvironment() throws IdUnavailableException {
		throw new IdUnavailableException(); // Simulate an error
	}

	public static void main(String[] args) {
		System.out.println("User ID: " + USER_ID);
	}
}

@SuppressWarnings("serial")
class IdUnavailableException extends Exception {

}

Ornegimizi calistirdigimizda bekledigimiz gibi calisacaktir ;

Logging in as guest
User ID: -1

Github kaynak kodlar / Source Code ;
leventerguder/injavawetrust-puzzler

Yazimi burada sonlandiriyorum.
Herkese Bol Javali Gunler dilerim.
Be an oracle man , import java.*;
Levent Erguder
OCP, Java SE 6 Programmer
OCE, Java EE 6 Web Component Developer

Print Friendly, PDF & Email

Leave a Reply

Your email address will not be published. Required fields are marked *