Monday, March 1, 2021

Advantages and Disadvantages of using Enum as Singleton in Java

Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Singleton, Oracle Java Career

Enum Singletons are new ways of using Enum with only one instance to implement the Singleton pattern in Java. While there has been a Singleton pattern in Java for a long time, Enum Singletons are a comparatively recent term and in use since the implementation of Enum as a keyword and function from Java 5 onwards.

Advantages of using Enum as Singleton:

1.  Enum Singletons are easy to write:  If you have been writing Singletons before Java 5, this is by far the greatest benefit that you realize that you can have more than one instance even with double-checked locking. While this problem is solved by improving the Java memory model and guaranteeing volatile variables from Java 5 onwards, it is still difficult for many beginners to write.

Compared to double-checked locking with synchronization, Enum singletons are very easy. If you don’t think that the following code for traditional singleton with double-checked locking and Enum Singletons are compared:

Singleton using Enum in Java: By default creation of the Enum instance is thread-safe, but any other Enum method is the programmer’s responsibility.

public enum EasySingleton{

  INSTANCE;

}

You can access it by EasySingleton.INSTANCE, far simpler than calling getInstance() function on Singleton.

2. Enum Singletons handled Serialization by themselves

Another problem with conventional Singletons is that they are no longer Singleton once you implement a serializable interface because the method readObject() always returns a new instance just like the Java constructor. By using the readResolve() method and discarding newly created instances, you can avoid that by substituting Singleton, as shown in the example below:

 private Object readResolve(){

      return INSTANCE;

  }

If your Singleton Class maintains state, this can become even more complex, as you need to make them transient, but JVM guarantees serialization with Enum Singleton.

Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Singleton, Oracle Java Career

3. Creation of Enum instance is thread-safe

By default, the Enum instance is thread-safe, and you don’t need to worry about double-checked locking.

In summary, the Singleton pattern is the best way to create Singleton in Java 5 world, given the Serialization and thread-safety guaranteed and with some line of code enum.

filter_none

// Java program to demonstrate the example 

// of using Enum as Singleton 

enum SingletonEnum { 

INSTANCE; 

int value; 

public int getValue() { 

return value; 

public void setValue(int value) { 

this.value = value; 

class Main { 

public static void main(String[] args) { 

SingletonEnum singleton = SingletonEnum.INSTANCE; 

System.out.println(singleton.getValue()); 

singleton.setValue(2); 

System.out.println(singleton.getValue()); 

}

Output

0
2

Disadvantages of using Enum as a singleton:


1. Coding Constraints

In regular classes, there are things that can be achieved but prohibited in enum classes. Accessing a static field in the constructor, for example. Since he’s working at a special level, the programmer needs to be more careful.

2. Serializability

For singletons, it is very common to be stateful. In general, those singletons should not be serializable. There is no real example where transporting a stateful singleton from one VM to another VM makes sense; a singleton means “unique within a VM” not “unique in the universe”

If serialization really makes sense for a stateful singleton, the singleton should specify explicitly and accurately what it means in another VM to deserialize a singleton where there may already be a singleton of the same type.

Friday, February 26, 2021

Retry In The Future

Oracle Java Tutorial and Material, Oracle Java Preparation, Core Java, Oracle Java Learning, Oracle Java Career

Writing asynchronous code in Javascript is relatively easy.

// async function

let attempt = 1;

while (true) {

    try {

        const result = await operationThatMayFail();

        // it didn't fail

        return result;

    } catch (error) {

        if (attempt >= maxAttempts || 

              error !== 'Retryable') {

            // either unhandleable, or no further attempts

            throw error;

        }

    }

    attempt++;

    await sleep(pauseTime);   

}

This infinite loop runs until the operation succeeds, or it throws an error that we don’t like (not 'Retryable') or we run out of attempts. In between attempts it sleeps before retrying.

This apparently sequential code is made out of the async/await pattern and is easy to reason about, though the first await statement might look like it could be replaced immediately returning, which it can’t…

The Promise API in Javascript is very handy/powerful, but the flattening of it into what looks like blocking code is even better!

So How Do We Do This In Java?

Trigger warning – you don’t want to know the answer to this!!!

I’ll answer this in Java 11, though there’s an optimisation to be made with later versions.

I’ve produced an example library and its unit tests for you to play with, so go and have a look. This is terrifying code. The most weird thing about this code is that this isn’t the first time I’ve implemented one of these, though this implementation was written tonight from scratch.

The first thing we need to know is that Java 8 and onwards provides a CompletableFuture which is very similar in intent to the Javascript Promise. A CompletableFuture says it WILL have an answer in the future, and there are various options for composing further transformations and behaviour upon it.

Our goal in this exercise is to write something which will allow us to execute a function that completes in the future a few times, until it succeeds. As each attempt needs to call the function again, let’s characterise attempts via an attempter as Supplier<CompletableFuture<T>>. In other words, something that can supply a promise to be doing the work in the future can be used to get our first attempt and can be used in retries to perform subsequent attempts. Easy!

The function we want to write, therefore, should take a thing which it can call do to the attempts, and will return a CompletableFuture with the result, but somehow hide the fact that it’s baked some retries into the process.

Here’s a signature of the function we want:

/**

     * Compose a {@link CompletableFuture} using the <code>attempter</code> 

     * to create the first

     * attempt and any retries permitted by the <code>shouldRetry</code> 

     * predicate. All retries wait

     * for the <code>waitBetween</code> before going again, up to a 

     * maximum number of attempts

     * @param attempter produce an attempt as a {@link CompletableFuture}

     * @param shouldRetry determines whether a {@link Throwable} is retryable

     * @param attempts the number of attempts to make before allowing failure

     * @param waitBetween the duration of waiting between attempts

     * @param <T> the type of value the future will return

     * @return a composite {@link CompletableFuture} that runs until success or total failure

     */

    public static <T> CompletableFuture<T> withRetries(

        Supplier<CompletableFuture<T>> attempter,

        Predicate<Throwable> shouldRetry,

        int attempts, Duration waitBetween) {

    ...

}

The above looks good… if you have a function that returns a CompletableFuture already, it’s easy to harness this to repeatedly call it, and if you don’t, then you can easily use some local thread pool (or even the fork/join pool) to repeatedly schedule something to happen in the background and become a CompletableFuture. Indeed, CompletableFuture.supplyAsync will construct such an operation for you.

So how to do retries…

Retry Options

Java 11 doesn’t have the function we need (later Java versions do). It has the following methods of use to us on a CompletableFuture:

◉ thenApply – which converts the eventual result of a future into something

◉ thenCompose – which takes a function which produces a CompletionStage out of the result of an existing CompletableFuture and sort of flatMaps it into a CompletableFuture

◉ exceptionally – which allows a completable future, which is presently in error state, to render itself as a different value

◉ supplyAsync – allows a completable future to be created from a threadpool/Executor to do something eventually

What we want to do is somehow tell a completable future –

completableFuture.ifErrorThenRetry(() -> likeThis())

And we can’t… and even if we could, we’d rather it did it asynchronously after waiting without blocking any threads!

Can We Cook With This?

We have all the ingredients and we can cook them together… but it’s a bit clunky.

We can make a scheduler that will do our retry later without blocking:

// here's an `Executor` that can do scheduling

private static final ScheduledExecutorService SCHEDULER =

     Executors.newScheduledThreadPool(1);

// which we can convert into an `Executor` functional interface

// by simply creating a lambda that uses our `waitBetween` Duration

// to do things later:

Executor scheduler = runnable -> 

    SCHEDULER.schedule(runnable, 

        waitBetween.toMillis(), TimeUnit.MILLISECONDS);

So we have non-blocking waiting. A future that wants to have another go, can somehow schedule itself and become a new future which tries later… somehow.

We need the ability to flatten a future which may need to replace its return value with a future of a future:

private static <T> CompletableFuture<T> flatten(
        CompletableFuture<CompletableFuture<T>> completableCompletable) {
    return completableCompletable.thenCompose(Function.identity());
}

Squint and forget about it… it does the job.

Adding The First Try


Doing the first attempt is easy:

CompletableFuture<T> firstAttempt = attempter.get();

All we have to do now is attach the retrying to it. The retry will, itself, return a CompletableFuture so it can retry in future. This means that using firstAttempt.exceptionally needs the whole thing to become a future of a future..!!!

return flatten(
    firstAttempt.thenApply(CompletableFuture::completedFuture)
        .exceptionally(throwable -> 
             retry(attempter, 1, throwable, shouldRetry, attempts, scheduler)));

We have to escalate the first attempt to become a future of a future on success (with thenApply) so we can then use an alternate path with exceptionally to produce a different future of a future on failure (with attempt 1)… and then we use the flatten function to make it back into an easily consumer CompletableFuture.

If this looks like voodoo then two points:

◉ it works
◉ you ain’t seen nothing yet!!!

Retrying in the Future of the Future of the Future


Oracle Java Tutorial and Material, Oracle Java Preparation, Core Java, Oracle Java Learning, Oracle Java Career
Great Scott Marty, this one’s tricky. We can have some easy guard logic in the start of our retry function:

int nextAttempt = attemptsSoFar + 1;
if (nextAttempt > maxAttempts || !shouldRetry.test(throwable.getCause())) {
    return CompletableFuture.failedFuture(throwable);
}

This does the equivalent of the catch block of our original Javascript. It checks the number of attempts, decides if the predicate likes the error or not… and fails the future if it really doesn’t like what it finds.

Then we have to somehow have another attempt and add the retry logic onto the back of it. As we have a supplier of a CompletableFuture we need to use that with CompletableFuture.supplyAsync. We can’t call get on it, because we want it to happen in the future, according to the waiting time of the delaying Executor we used to give us a gap between attempts.

So we have to use flatten(CompletableFuture.supplyAsync(attempter, scheduler)) to put the operation into the future and then make it back into a CompletableFuture for onward use… and then… for reasons that are hard to fathom, we need to repeated the whole thenApply and exceptionally pattern and flatten the result again.

This is because we first need a future that will happen later, in a form where we can add stuff to it, and we can’t add stuff to it until… I mean, I understand it, but it’s just awkward:

return flatten(flatten(CompletableFuture.supplyAsync(attempter, scheduler))
    .thenApply(CompletableFuture::completedFuture)
    .exceptionally(nextThrowable ->
         retry(attempter, nextAttempt, nextThrowable, 
             shouldRetry, maxAttempts, scheduler)));

Well, if flattening’s so good, we may as well do it lots, eh?

Wednesday, February 24, 2021

Java.Lang.Float class in Java

Core Java, Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Certification, Oracle Java Exam Prep, Oracle Java Preparation

Float class is a wrapper class for the primitive type float which contains several methods to effectively deal with a float value like converting it to a string representation, and vice-versa. An object of Float class can hold a single float value. There are mainly two constructors to initialise a Float object-

◉ Float(float b: Creates a Float object initialized with the value provided.

Syntax: public Float(Float d)

Parameters:

d : value with which to initialize

◉ Float(String s): Creates a Float object initialized with the parsed float value provided by string representation. Defalut radix is taken to be 10.

Syntax:  public Float(String s) 

                    throws NumberFormatException

Parameters: 

s : string representation of the byte value 

Throws: 

NumberFormatException: If the string provided does not represent any float value.

Methods:

1. toString(): Returns the string corresponding to the float value.

Syntax : public String toString(float b)

Parameters :

b : float value for which string representaion required.

2. valueOf() : returns the Float object initialised with the value provided.

Syntax : public static Float valueOf(float b)

Parameters :

b : a float value

Another overloaded function valueOf(String val) which provides function similar to

new Float(Float.parseFloat(val,10))

Syntax : public static Float valueOf(String s)

           throws NumberFormatException

Parameters :

s : a String object to be parsed as float

Throws :

NumberFormatException : if String cannot be parsed to a float value.

3. parseFloat() : returns float value by parsing the string. Differs from valueOf() as it returns a primitive float value and valueOf() return Float object.

Syntax : public static float parseFloat(String val)

             throws NumberFormatException

Parameters :

val : String representation of float 

Throws :

NumberFormatException : if String cannot be parsed to a float value in given radix.

4. byteValue() : returns a byte value corresponding to this Float Object.

Syntax : public byte byteValue()

5. shortValue() : returns a short value corresponding to this Float Object.

Syntax : public short shortValue()

6. intValue() : returns a int value corresponding to this Float Object.

Syntax : public int intValue()

7. longValue() : returns a long value corresponding to this Float Object.

Syntax : public long longValue()

8. doubleValue() : returns a double value corresponding to this Float Object.

Syntax : public double doubleValue()

9. floatValue() : returns a float value corresponding to this Float Object.

Syntax : public float floatValue()

10. hashCode() : returns the hashcode corresponding to this Float Object.

Syntax : public int hashCode()

11. isNaN() : returns true if the float object in consideration is not a number, otherwise false.

Syntax : public boolean isNaN()

Another static method isNaN(float val) can be used if we dont need any object of float to be created. It provides similar functionality as the above version.

Syntax : public static boolean isNaN(float val)

Parameters :

val : float value to check for

12. isInfinite() : returns true if the float object in consideration is very large, otherwise false. Specifically any number beyond 0x7f800000 on positive side and below 0xff800000 on negative side are the infinity values.

Syntax : public boolean isInfinite()

Another static method isInfinite(float val) can be used if we dont need any object of float to be created. It provides similar functionality as the above version.

Syntax : public static boolean isInfinte(float val)

Parameters :

val : float value to check for

13. toHexString() : Returns the hexadecimal representation of the argument float value.

Syntax : public static String toHexString(float val)

Parameters

val : float value to be represented as hex string

14. floatToIntBits() : returns the IEEE 754 floating-point “single format” bit layout of the given float argument. Detailed summary of IEEE 754 floating-point “single format” can be found here.

Syntax : public static int floatToIntBits(float val)

Parameters :

val : float value to convert

15. floatToRawIntBits() : returns the IEEE 754 floating-point “single format” bit layout of the given float argument. It differs from previous method as it preserves the Nan values.

Syntax : public static int floatToRawIntBits(float val)

Parameters :

val : float value to convert

16. IntBitsToFloat() : Returns the float value corresponding to the long bit pattern of the argument. It does reverse work of the previous two methods.

Syntax : public static float IntBitsToFloat(long b)

Parameters :

b : long bit pattern

17. equals() : Used to compare the equality of two Float objects. This methods returns true if both the objects contains same float value. Should be used only if checking for equality. In all other cases compareTo method should be preferred.

Syntax : public boolean equals(Object obj)

Parameters :

obj : object to compare with

18. compareTo() : Used to compare two Float objects for numerical equality. This should be used when comparing two Float values for numerical equality as it would differentiate between less and greater values. Returns a value less than 0,0,value greater than 0 for less than,equal to and greater than.

Syntax : public int compareTo(Float b)

Parameters :

b : Float object to compare with

19. compare() : Used to compare two primitive float values for numerical equality. As it is a static method therefore it can be used without creating any object of Float.

Syntax : public static int compare(float x,float y)

Parameters :

x : float value

y : another float value

// Java program to illustrate 

// various float class methods 

// of Java.lang class 

public class GfG 

public static void main(String[] args) 

float b = 55.05F; 

String bb = "45"; 


// Construct two Float objects 

Float x = new Float(b); 

Float y = new Float(bb); 


// toString() 

System.out.println("toString(b) = " + Float.toString(b)); 


// valueOf() 

// return Float object 

Float z = Float.valueOf(b); 

System.out.println("valueOf(b) = " + z); 

z = Float.valueOf(bb); 

System.out.println("ValueOf(bb) = " + z); 


// parseFloat() 

// return primitive float value 

float zz = Float.parseFloat(bb); 

System.out.println("parseFloat(bb) = " + zz); 


System.out.println("bytevalue(x) = " + x.byteValue()); 

System.out.println("shortvalue(x) = " + x.shortValue()); 

System.out.println("intvalue(x) = " + x.intValue()); 

System.out.println("longvalue(x) = " + x.longValue()); 

System.out.println("doublevalue(x) = " + x.doubleValue()); 

System.out.println("floatvalue(x) = " + x.floatValue()); 


int hash = x.hashCode(); 

System.out.println("hashcode(x) = " + hash); 


boolean eq = x.equals(y); 

System.out.println("x.equals(y) = " + eq); 


int e = Float.compare(x, y); 

System.out.println("compare(x,y) = " + e); 


int f = x.compareTo(y); 

System.out.println("x.compareTo(y) = " + f); 


Float d = Float.valueOf("1010.54789654123654"); 

System.out.println("isNaN(d) = " + d.isNaN()); 


System.out.println("Float.isNaN(45.12452) = "

+ Float.isNaN(45.12452F)); 


// Float.POSITIVE_INFINITY stores 

// the positive infinite value 

d = Float.valueOf(Float.POSITIVE_INFINITY + 1); 

System.out.println("Float.isInfinite(d) = "

+ Float.isInfinite(d.floatValue())); 


float dd = 10245.21452F; 

System.out.println("Float.toString(dd) = "

+ Float.toHexString(dd)); 


int float_to_int = Float.floatToIntBits(dd); 

System.out.println("Float.floatToLongBits(dd) = "

+ float_to_int); 


float int_to_float = Float.intBitsToFloat(float_to_int); 

System.out.println("Float.intBitsToFloat(float_to_long) = "

+ int_to_float); 

Output :

toString(b) = 55.05
valueOf(b) = 55.05
ValueOf(bb) = 45.0
parseFloat(bb) = 45.0
bytevalue(x) = 55
shortvalue(x) = 55
intvalue(x) = 55
longvalue(x) = 55
doublevalue(x) = 55.04999923706055
floatvalue(x) = 55.05
hashcode(x) = 1113338675
x.equals(y) = false
compare(x,y) = 1
x.compareTo(y) = 1
isNaN(d) = false
Float.isNaN(45.12452) = false
Float.isInfinite(d) = true
Float.toString(dd) = 0x1.4029b8p13
Float.floatToLongBits(dd) = 1176507612
Float.intBitsToFloat(float_to_long) = 10245.215

Tuesday, February 23, 2021

Controlling the Visibility of Class and Interface in Java

Core Java, Oracle Java Learning, Oracle Java Certification, Oracle Java Exam Prep, Oracle Java Preparation

Maintenance is one of the important aspects of software development, and experience has shown that software that maintains its component’s visibility low is more maintainable than one that exposes its component more. You’re not going to know it upfront, but when redesigning the application, you’re going to miss it terribly.

You end up patching and repeating the same errors, as maintaining backward compatibility is a must-have requirement for many applications. You will not do much because the class and interfaces are tightly integrated with a lot of other applications. Java has always prioritized encapsulation, providing access modifiers of support from the very beginning. By making them public, package-private or private provides ways to monitor the visibility of some type, such as class or interface.

Below are some rules to control the visibility:

1. A top-level class (a class whose name is the same as the Java source file that contains it) can also be either a public or a private package (without an access modifier) and cannot be a private one. Private, public, or package-private may only be a nesting class.

2. A public class is accessible to all and most visible, try to keep public only key interfaces, never let the implementation go public until you believe it’s complete and mature.

3. The private type, on the other hand, is less visible, and in Java, only the nested class or interface can be private. You have full control over this class to change its actions with experiences, new technology, tools, and redesign, as it’s least visible.

4. Package-private visibility is a clever midway and is also default visibility, there’s no such keyword as package-private, instead if you don’t have any access modifier as Java thinks it’s package-private, and then make it only visible on the same package.

5. If the classes and interfaces are only shared within the same package between other classes, make them package-private. As the client is unable to reach them, they are therefore reasonably safe to change.

How to control Visibility of Class or Interface in Java?

In addition to decreasing class or interface visibility using the access modifier, based on your runtime environment, there are many other ways to do so. At the component level, such as Websphere, Weblogic, or JBoss in Application Server, an interface class may be proxied or wrapped to reduce external visibility.

No matter what you do, there will still be certain types that need to be exposed to the outside world, but you can always handle them with proxy or wrapper. Although client programs will load proxied implementation classes, an immutable proxy or wrapper would often be obtained.

For example, the Java Servlet API (javax.servlet) getServletContext() returns an implementation of javax.servlet.ServletContext, which is typically an immutable proxy to satisfy the ServletContext framework promises. It is most possible that a separate version of the javax.servlet.ServletContext specification operates on the application server.

It is possible to use a similar pattern in the implementation of other externally accessible interfaces, e.g. Javax.ejb.EJBContext, Javax.ejb.TimerService, ServletRequest, ServletResponse, etc. To support these global interfaces, various application servers can use various applications.

JDK Example of Controlling Visibility of Java Class

Core Java, Oracle Java Learning, Oracle Java Certification, Oracle Java Exam Prep, Oracle Java Preparation
EnumSet class is another fascinating example of managing visibility. In order to prevent instantiation, the Java designer made the abstract class and provided factory methods as the only way to create an instance of that class, e.g. Methods from EnumSet.of() or EnumSet.noneOf().

Internally, in the form of RegularEnumSet and JumboEnumSet, they have two separate implementations, which are automatically selected based on the size of the main universe by static factory methods.

For instance, if the number of values in Enum is less than 64, then RegularEnumSet is used, otherwise, the JumboEnumSet instance is returned. The beauty of this design is that package-private means that consumers have no idea about any of these implementations.

Modifier Description
Default  declarations are visible only within the package (package private)
Private  declarations are visible within the class only 
Protected  declarations are visible within the package or all subclasses 
Public  declarations are visible everywhere 

Private Access Modifier


// Java program for showcasing the behaviour 
// of Private Access Modifier 

class Data { 
// private variable 
private String name; 
public class Main { 
public static void main(String[] main){ 
// create an object of Data 
Data d = new Data(); 
// access private variable and field from another class 
d.name = "Kapil"; 
}

Output:

Main.java:18: error: name has private access in Data
     d.name = "Programiz";
      ^
In the above example, we have declared a private variable named name and a private method named display(). When we run the program, we will get the above error:

Protected Access Modifier


// Java program for showcasing the behaviour 
// of Protected Access Modifier 

class Animal { 
// protected method 
protected void display() { 
System.out.println("I am an animal"); 

class Dog extends Animal { 
public static void main(String[] args) { 

// create an object of Dog class 
Dog dog = new Dog(); 
// access protected method 
dog.display(); 
}

Output

I am an animal

Public Access Modifier:


// Java program for showcasing the behaviour 
// of Public Access Modifier 

// Animal.java file 
// public class 

class Animal { 
// public variable 
public int legCount; 

// public method 
public void display() { 
System.out.println("I am an animal."); 
System.out.println("I have " + legCount + " legs."); 

// Main.java 
public class Main { 
public static void main( String[] args ) { 
// accessing the public class 
Animal animal = new Animal(); 

// accessing the public variable 
animal.legCount = 4; 
// accessing the public method 
animal.display(); 
}

Output

I am an animal.
I have 4 legs.

Monday, February 22, 2021

Unit testing private methods

Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Exam Prep, Core Java, Java Career

Introduction

In this article, I will contemplate the testing of private methods in unit tests. After that, I will propose a way or pattern to do it, if you must. Finally, I will show how you can generate this pattern automatically.

Read More: 1Z0-900: Java EE 7 Application Developer

And yes, I will also write a takeaway section to know what you have read.

Test or not to Test Private Methods

Unit testing is usually not black-box testing. It is debatable if it ought to be or not. Practice shows that it rarely is. When we equip the tested unit with different mocks, we play around with the implementation and not the defined functionality that a black-box test should only deal with.

After setting up and injecting the mock objects, we invoke the tested methods, and these methods are usually public. In other words, the invocation of the tested system is more like a black-box test. You can say that the test setup is not a black-box test, but the actual test is.

The advantage of black-box testing is that it does not need to change if the tested module changes’ internal working. If the functionality changes, it is another story. It is easier to refactor, optimize, simplify, beautify your code if there are clean unit tests that do not depend on the implementation. If the unit tests depend on the implementation, then you cannot reliably refactor your code. As soon as you change the implementation, the test has to follow the change.

I do not particularly appreciate when the unit test cannot be black-box, but there are cases when it is unavoidable. An unusual and frequent case is when we want to test a private method. If you want to, or even God forgive, have to test a private method, it is a code smell. The method may be simple, and you can achieve the coverage of its functionality by invoking only the public API of the tested unit. You do not have to test the private method, and if you do not have to, you must not want.

Another possibility is that that the private method is so complicated that it deserves its own test. In that case, the functionality deserves a separate utility class.

Still, there is a third possibility. After all the contemplating, we decide that the private method remains inside the unit, and we want to test it.

It is a small, insignificant problem that you cannot invoke from outside, and the test is inevitably out of the unit. Some developers remove the private modifier changing the access level from private to “test-private”.

No kidding! After more than 500 technical interviews over the past ten years, I have heard many things. I regret that I did not start recording these. As I heard a few times, one of these lovely things: “test private” as a terminology instead of package-private. Two or three candidates out of the 500 said that the accessibility is test private when there is no access modifier in front of the class member. It means they said that the member can also be accessible from the unit tests. From other classes in the same package? Not so sure.

What this story suggests is that many developers struggle to test private methods. I have also seen this in many other projects.

I am not too fond of this approach because we weaken the access protection of a class member to ease testing.

A different approach is when the tests use reflection to access the class members. There are two issues with this approach. One is the suboptimal performance. The other is the bloated code. The fact that the access to the class members via reflection is slower than the direct access is usually not significant. We are talking about tests. If the test execution needs significant time, then the tests are wrong, or the project is large or has some particular testing need. Even in these cases, the reason for the slow speed is usually not the reflective access.

The bloated code, on the other hand, hinders readability. It is also cumbersome to write every time things like

Field f = sut.getClass().getDeclaredField("counter");

f.setAccessible(true);

f.set(sut, z);

when we want to set a private field, or

Method m = sut.getClass().getDeclaredMethod("increment");

m.setAccessible(true);

m.invoke(sut);

when we want to invoke a private method. The maintenance of such tests is also questionable. If the name of the method or field changes, the test has to follow. There is no significant risk of forgetting because the test will fail, but still, it is a manual editing functionality. Most of the IDEs support renaming. Whenever I rename a method or field, the IDE renames all the references to it. Not when the reference is part of a string.

There is no real solution to this issue, except when you write code that does not need the testing of private methods and fields. Still, some approaches have advantages.

Doing it with a Style

One approach is to declare a private static delegating inner class with the same name as the tested class. This class has to implement the same methods as the original tested class, and these implementations should delegate to the original methods. The class also has to implement setters and getters to all the fields.

If we instantiate this class instead of the original one, then we can invoke any method or set any field without reflective access in the test code. The inner class hides the reflective access.

The reason to name the class with the same simple name as the tested class is that the tests do not need to change this way. If a test has a code that instantiated the tested class calling new Sut() and now we start to have an inner class named Sut, then the constructor all of a sudden will refer to the inner class.

Let’s see an example. The following class is a simple example that has one public method and a private one. The complexity of the methods barely reaches the level that would rectify extensive testing, but this makes it suitable for demonstration purposes.

public class SystemUnderTest {

private int counter = 0;

public int count(int z) {

while (z > 0) {

z--;

increment();

}

return counter;

}

private void increment(){

counter++;

}

}

The test itself is also very simple:

@Test

void testCounter() throws Exception {

final var sut = new SystemUnderTest();

sut.setCounter(0);

sut.increment();

Assertions.assertEquals(1, sut.getCounter());

}

The only problem with this solution that the system under test does not contain the setter, and the method increment() is private. The code, as it is now, does not compile. We have to provide an implementation of the delegating static inner class named SystemUnderTest.

The following code shows an implementation of this class, which I created manually.

private static class SystemUnderTest {

private javax0.geci.jamal.sample.SystemUnderTest sut = new javax0.geci.jamal.sample.SystemUnderTest();

private void setCounter(int z) throws NoSuchFieldException, IllegalAccessException {

Field f = sut.getClass().getDeclaredField("counter");

f.setAccessible(true);

f.set(sut, z);

}

private int getCounter() throws NoSuchFieldException, IllegalAccessException {

Field f = sut.getClass().getDeclaredField("counter");

f.setAccessible(true);

return (int) f.get(sut);

}

private void increment() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

Method m = sut.getClass().getDeclaredMethod("increment");

m.setAccessible(true);

m.invoke(sut);

}

private int count(int z) {

return sut.count(z);

}

}

It is already an achievement because we could separate the messy reflective access from the test code. The test, this way, is more readable. Since we cannot avoid the reflective code, it will not get better than this as per the readability. The other issue, maintainability, however, can still be improved.

Doing it Automated

Creating the delegating inner class is relatively straightforward. It does not need much innovation. If you specify the task precisely, any cheaply hired junior could create the inner class. It is so simple that even a program can create it. It does not need the human brain.

If you tried to write a Java program from scratch that generates this code, it would be, well, not simple. Fortunately (ha ha ha), we have Java::Geci, and even more, we have the Jamal module. Jav::Geci is a code generation framework that you can use to generate Java code. The framework contains readily available code generators, but it is also open and pluggable, providing a clean API for new code generators. It does all the tasks needed for most of the code generators and lets the code generator program focus on its core business.

Code generation.

For simpler applications, when the code generation is straightforward and does not need a lot of algorithm implementation, the module Jamal can be used. Jamal is a text-based templating language, which can be extended with Java classes implementing macros. The Java::Geci Jamal module includes a code generator that parses the source files and looks for code that has the following structure:

/*!Jamal

TEMPLATE

*/

CODE HERE

//__END__

When it sees one, it evaluates the code that is written on the lines TEMPLATE using Jamal, and then it replaces the lines of CODE HERE with the result. It generates code, and if there was a generated code but is stale, it updates the code.

The code generation runs during the test execution time, which has advantages and disadvantages.

One disadvantage is that the empty code or stale code should also compile. The compilation should not depend on the up-to-date-ness of the generated code. In practice, we usually (well, not usually, rather always) can cope with it.

The advantage is that the code generation can access the Java code structures via reflection. That way, for example, the code generators can get a list of all declared fields or methods and can generate some delegating methods for them.

The Jamal module contains Java classes implementing macros that can do that. The fact that you can express the generation of the unit test delegating inner class as Jamal macros shows the tool’s power. On the other hand, I have to note that this task is somewhere at the edge of the tool’s complexity. Nevertheless, I decided to use this task as a sample because generating setter and getters is boring. I also want to avoid lazy readers asking me why to have another setter/getter generator, as it happened at some conferences where I talked about Java::Geci. Setter and getter generator is not a good example, as it does not show you the advantage. You can do that with the IDE or using Lombok or some other tool. Perhaps after reading this article, you can try and implement the setter/getter generation using Jamal just for fun and to practice.

The previous code snippets were from the class ManualTestSystemUnderTest. This class contains the manually created delegating inner class. I created this class for demonstration purposes. The other testing class, GeneratedTestSystemUnderTest contains the generated sample code. We will look at the code in this file and how Java::Geci generates it automatically.

Before looking at the code, however, I have to make two notes:

◉ The example code uses a simplified version of the macros. These macros do not cover all the possible causes.

◉ On the other hand, the code includes all the macros in the source file. Professional code does not need to have these macros in the source. All they need is an import from a resource file and then the invocation of a single macro. Two lines. The macros generating the delegating inner class are defined in a resource file. It is written once, you do not need to write them all the time. I will show you at the end of this article how it is invoked.

Let’s have a look at the class GeneratedTestSystemUnderTest! This class contains the following Jamal template in a Java comment:

/*!jamal

{%@import res:geci.jim%}\

{%beginCode SystemUnderTest proxy generated%}

private static class SystemUnderTest {

private javax0.geci.jamal.sample.SystemUnderTest sut = new javax0.geci.jamal.sample.SystemUnderTest();

{%!#for ($name,$type,$args) in

({%#methods

{%class javax0.geci.jamal.sample.SystemUnderTest%}

{%selector private %}

{%format/$name|$type|$args%}

%}) =

{%@options skipForEmpty%}

private $type $name({%`@argList $args%}) throws Exception {

Method m = sut.getClass().getDeclaredMethod("$name"{%`#classList ,$args%});

m.setAccessible(true);

m.invoke(sut{%`#callArgs ,$args%});

}

%}

{%!#for ($name,$type,$args) in

({%#methods

{%class javax0.geci.jamal.sample.SystemUnderTest%}

{%selector/ !private & declaringClass -> ( ! canonicalName ~ /java.lang.Object/ )%}

{%format/$name|$type|$args%}

%}) =

{%@options skipForEmpty%}

private $type $name({%`@argList $args%}) {

{%`#ifNotVoid $type return %}sut.$name({%`#callArgs $args%});

}

%}

{%!#for ($name,$type) in

({%#fields

{%class javax0.geci.jamal.sample.SystemUnderTest%}

{%selector/ private %}

{%format/$name|$type%}

%}) =

{%@options skipForEmpty%}

private void {%setter=$name%}($type $name) throws Exception {

Field f = sut.getClass().getDeclaredField("$name");

f.setAccessible(true);

f.set(sut,$name);

}

private $type {%getter/$name/$type%}() throws Exception {

Field f = sut.getClass().getDeclaredField("$name");

f.setAccessible(true);

return ($type)f.get(sut);

}

%}

{%!#for ($name,$type) in

({%#fields

{%class javax0.geci.jamal.sample.SystemUnderTest%}

{%selector/ !private %}

{%format/$name|$type%}

%}) =

{%@options skipForEmpty%}

private void {%setter/$name%}($type $name) {

sut.$name = $name;

}

private $type {%getter/$name/$type%}() {

return sut.$name;

}

%}

}

{%endCode%}

*/

In this code the macro start string is {% and the macro closing string is %}. It is the default setting when Java::Geci starts Jamal to process a source file. This way, the macro enhanced template can freely contain standalone { and } characters, which is very common in Java. Macros implemented as Java code use the @ or the # character in front of the macro name. If there is no such character in front of the macro name, then the macro is user-defined from a @define ... macro.

The text of the template contains three parts:

1. the start of the code,

2. four loops, and

3. the end of the generated code in the template (this is just a closing } character).

The start of the template

{%@import res:geci.jim%}\

{%beginCode SystemUnderTest proxy generated%}

private static class SystemUnderTest {

private javax0.geci.jamal.sample.SystemUnderTest sut = new javax0.geci.jamal.sample.SystemUnderTest();

imports the macro definitions from the resource file geci.jim. The file itself is part of the library. If you have the dependency on the classpath when the code generator and the Jamal processor runs, you can import the definition from this resource file. The macro definitions in this file are simple Jamal macros defined as text. You can have a look at them at the URL

https://github.com/verhas/javageci/blob/1.6.1/javageci-jamal/src/main/resources/geci.jim

The next line uses the beginCode user-defined macro, which is defined in geci.jim as the following:

{%@define beginCode(:x)=//<editor-fold desc=":x">%}

When this macro is used it will result the start of an editor fold that helps to keep the generated code non-intrusive when the file is opened in the IDE. When this macro is evaluated, it will be

//<editor-fold desc="SystemUnderTest proxy generated">

The next two lines start the private static inner class. It is just plain text; there is no macro in it.

Now we get to the four loops that generate proxy codes for

1. Delegating proxy methods for the private methods of the tested class.

2. Delegating proxy methods for the non-private methods declared in the class or inherited, except those inherited from the Object class.

3. Setter and getter methods for the private fields of the tested class.

4. Setter and getter methods for the non-private fields of the tested class.

Since these are very similar, I will discuss here only the first in detail.

{%!#for ($name,$type,$args) in

({%#methods

{%class javax0.geci.jamal.sample.SystemUnderTest%}

{%selector private %}

{%format/$name|$type|$args%}

%}) =

{%@options skipForEmpty%}

private $type $name({%`@argList $args%}) throws Exception {

Method m = sut.getClass().getDeclaredMethod("$name"{%`#classList ,$args%});

m.setAccessible(true);

m.invoke(sut{%`#callArgs ,$args%});

}

%}

The loop is constructed using a for macro, a Java-implemented, built-in macro of Jamal from the core package. This macro is always available for any Jamal processing. This macro iterates through a comma-separated list and repeats its contents for each list element replacing the loop variables with the actual values. There can be more than one loop variable. In such a case, like in our example, the actual value is split up along the | characters. The comma used as a list separator, and the values separator | can be redefined. In the above case, the for loop uses three-loop variables, $name, $type`, and$args. The start with a$` sign has no significance. Any string can be used as a loop variable.

The list of values is between the () characters after the in keyword. This list is the result of the evaluation of the methods built-in macro. This macro is implemented in Java and is part of the Java::Geci Jamal module. It is not a generally available Jamal macro, but when we run the code generation of Java::Geci, this JAR file is on the classpath, and thus this macro is available.

The methods macro lists the methods of a class.

The class name is taken from the user-defined macro $class, which can be defined using the user-defined macro class. The listing also considers a selector expression that can be used to filter out some of the methods. It is also provided in a user-defined macro, and there is also a helper macro in geci.jim to define it, named selector. In the example above, the selector expression is private, which will select only the private methods.

When the list is collected, the macro methods must convert it to a comma-separated list. To do that, it uses a formatting string that can contain placeholders. In our case, the placeholders are $name, $type, and $args. Every element in the list for the for loop will contain these three strings for the listed methods separated by two | characters as indicated by the format string.

The part after the = sign in the for loop is repeated for each method. It will declare a private method that invokes the same method of the tested method. To do that, it uses the help of the Java::Geci Jamal module provided built-in macros argList, classList, and callArgs. These help generating code that declares the arguments, lists the classes of the argument types or lists the arguments for the actual call.

Since this is just an article and not a full-blown documentation of Java::Geci and Jamal, I skip some details. For example, why the macro for uses the # character in front of it instead of @, why there is a backtick character in front of the macros in the loop’s body, and why the for loop uses a ! character. These details control the macro evaluation order. The list of the methods needs to be created before the for loop starts because it requires the method list. On the other hand, the macros in the loop’s body have to be evaluated after the loop generated the text for every listed method.

Also, note that this implementation is for demonstration purposes only. It simplifies the problem and does not cover all the corner cases. For example, it will generate a setter for a final field.

If you want to use this code generation, you can use the macro proxy(KLASS) defined in the resource file res:unittestproxy.jim.

You can have a look at the class UnitTestWithGeneratedUnitTestProxy, which is a tad more complex than the sample and tests these macros. The start of the generated code is the following:

/*!jamal

{%@import res:unittestproxy.jim%}\

{%beginCode SystemUnderTest proxy generated%}

{%proxy javax0.geci.jamal.unittestproxy.TestSystemUnderTest%}

{%endCode%}

*/

It merely imports the res:unittestproxy.jim file, which imports geci.jim and then uses the macro proxy to generate all the needed code covering all the corner cases.

If you want to use the code generator in your code, you have to do two things:

A. Include the dependency in your pom.xml file:

<dependency>

<groupId>com.javax0.geci</groupId>

<artifactId>javageci-jamal</artifactId>

<version>1.6.1</version>

<scope>test</scope>

</dependency>

B. Create a small unit test that runs the code generator:

@Test

@DisplayName("run the Jamal generator")

public void testRunJamalGenerator() throws Exception {

Geci geci = new Geci();

Assertions.assertFalse(

geci.register(new JamalGenerator())

.generate()

, geci.failed()

);

}

The generator runs during the unit test. During the test run, it has access to the structure of the Java code via reflection. The Jamal macros like methods, fields can query the different classes and provide the list of the methods and fields. The test fails if there was any new code generated. It only happens when the code generator runs the first time or when the tested system has changed. In this case, the test fails because the compiled code during the execution is not the final one. In such a case, start Maven again, and the second time the compilation already runs fine. Do not forget to commit the changed code. There is no risk of failing to update the generated code, like in IDE provided code generation that you have to invoke manually.

Takeaway


What you should remember from this article:

◉ Try not to test private methods. If you feel the need, you did something wrong. Probably. Possibly not.

◉ If you test private methods arrange the reflective code into a private static class that delegates the call to the original class. This will remove the implementation of the reflective access from the test and the test remains what it has to be: functionality test.

◉ If you are a lazy person, and as a good programmer you have to be, use a Java::Geci and Jamal to generate these inner classes for your tests.

◉ Master Java::Geci and Jamal and use them to generate code for your other, specific needs.

Source: javacodegeeks.com

Friday, February 19, 2021

Difference between abstract class and interface

Abstract Class, Interface, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Certification, Oracle Java Guides

Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods. Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.

Abstract class Interface 
Abstract class can have abstract and non-abstract methods.  Interface can have only abstract methods. Since Java 8, it can have default and static methods also.
Abstract class doesn't support multiple inheritance.  Interface supports multiple inheritance. 
Abstract class can have final, non-final, static and non-static variables.  Interface has only static and final variables. 
Abstract class can provide the implementation of interface.  Interface can't provide the implementation of abstract class. 
The abstract keyword is used to declare abstract class.  Interface can't provide the implementation of abstract class. 
An abstract class can extend another Java class and implement multiple Java interfaces.  An interface can extend another Java interface only. 
An abstract class can be extended using keyword "extends".  An interface can be implemented using keyword "implements". 
A Java abstract class can have class members like private, protected, etc.  Members of a Java interface are public by default. 
Example:
public abstract class Shape{
public abstract void draw();
Example:
public interface Drawable{
void draw();

Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully abstraction (100%).

Example of abstract class and interface in Java


Let's see a simple example where we are using interface and abstract class both.

//Creating interface that has 4 methods  
interface A{  
void a();//bydefault, public and abstract  
void b();  
void c();  
void d();  
}  
  
//Creating abstract class that provides the implementation of one method of A interface  
abstract class B implements A{  
public void c(){System.out.println("I am C");}  
}  
  
//Creating subclass of abstract class, now we need to provide the implementation of rest of the methods  
class M extends B{  
public void a(){System.out.println("I am a");}  
public void b(){System.out.println("I am b");}  
public void d(){System.out.println("I am d");}  
}  
  
//Creating a test class that calls the methods of A interface  
class Test5{  
public static void main(String args[]){  
A a=new M();  
a.a();  
a.b();  
a.c();  
a.d();  
}}  

Output:

I am a
I am b
I am c
I am d