Swift for Beans – var, let and Type Inference

I have always preferred explicitly typed languages, saving a couple of characters by simply declaring a variable as var or let can quickly end up in a game of “Guess who?” or “what” to be more precise.

Its straight forward enough with immediate assignments or when the expected type is clear.

var name = "Foo"  //clearly String
var street = customer.street //most likely String
var customer = Customer(name: "Foo", ...)

However when dealing with complex domain models or business functions with unclear return type the value of strong typing quickly becomes apparent.

var value = contract.amount  //Int/UInt/Float/Double/String/...?
var customer = contract.customer //String/domain model Customer/...?
var amountDue = billingService.calculate(...)  //Int/UInt/Float/Double/...?

Continue reading Swift for Beans – var, let and Type Inference

Swift for Beans – about null, nil and Optional.orElse(“?!”)

As you may have gathered, I have found an interest in Swift. I have always found it easier to pick up new languages by comparing it to the one I know best, Java.

Please note, this series is intended for experienced Java Developers. I will not go into details of Java or its API. Where sensible I will provide relevant links.

Tony Hoare, inventor of null (aka nil), famously proclaimed it to be his “…billion dollar mistake”. This should not be interpreted as null/nil being evil per se, denoting the absence/not-existence of a value is essential for data processing, but rather the absence of sensible language features to handle null/nil values.

To fully appreciate this you have to jump a couple of sentences further: “… More recent programming languages like Spec# have introduced declarations for non-null references. This is the solution, which I rejected in 1965.”

Unlike Java, Optional is an integral part of Swift language. In Swift variables may not be assigned nil (null), either they have to be initialized with a value or declared as an ? optional.

var nonNill: String = "Foo"  //may not be nil  
var optNil: String?  //optional may contain nil
var optNonNill: String? = "Bar" //Bar wrapped in an optional

Any attempt to assign a non-optional variable with a nil value results in a compilation error.
Continue reading Swift for Beans – about null, nil and Optional.orElse(“?!”)

Swift for Beans – Java Developers view on Swift

swift-ogA large open source community has grown around Swift, since Apple open sourced it along with a Linux Port back in Dezember 2015.

Certain parallels can be drawn between the evolution of Java and Swift. Java was first a portable platform independent client-side technology that slowly found its way to the server side. A similar pattern can now be seen when looking at the Swift ecosystem. Starting out as a client side technology for developing IOS and OS X applications. The release of Swift as an open source community driven language, along with the Linux port, have given rise to an array of frameworks, utility libraries and server projects.

Currently there are three major active web server projects:

For an overview of the Swift ecosystem visit IBM Swift Package Catalog.
Continue reading Swift for Beans – Java Developers view on Swift

Understanding Dependency Injection – Part 3 Contexts

So far this series has covered simple IoC dependency injection as well as bean initialization with @PostConstruct and constructor injection.

In this part we will introduce container managed contextual scopes to Voodoo DI.

A scope defines the life-cycle of a bean, allowing state to be preserved and or shared across multiple interactions. DI frameworks offer a fast variety of build-in and add-on scopes, such as @RequestScoped, @SessionScoped, @ApplicationScoped, etc…

So far Voodoo DI simply maps interfaces, supertypes and the target type directly to the concrete implementations.

//Map Interfaces and Supertypes to concrete implementation.
private final Map types = new ConcurrentHashMap<>();
...
public  T instance(Class clazz) {
    T newInstance = null;
    try {
      Constructor constructor = types.get(clazz).getConstructor(new Class[]{});
      newInstance = constructor.newInstance(new Object[]{});
      processFields(clazz, newInstance);
    } catch (Exception ex) {
      Logger.getLogger(Voodoo.class.getName()).log(Level.SEVERE, null, ex);
      throw new RuntimeException(ex);
    }
    return newInstance;
  }
...

Continue reading Understanding Dependency Injection – Part 3 Contexts

Understanding Dependency Injection – Part 2 PostConstruct and Constructor Injection

In the first part of this series I introduced basic IoC functionality. In this part we will cover @PostConstruct methods and Constructor Injection.

Consider the following scenario:

public class Car {
  @Inject
  private Engine engine;  

  public Car() {
    engine.initialize();  
  }
  ...
}  

Since Car has to be instantiated prior to field injection, the injection point engine is still null during the execution of the constructor, resulting in a NullPointerException.

This problem can be solved either by JSR-330 Dependency Injection for Java constructor injection or JSR 250 Common Annotations for the Java @PostConstruct method annotation.
Continue reading Understanding Dependency Injection – Part 2 PostConstruct and Constructor Injection

Understanding Dependency Injection – Part 1 IoC

Dependency Injection, be it Spring IoC, CDI or Google GUICE is often seen as hard to understand or even referred to as “black magic”.

As with all complex frameworks the actual working basis is fairly simple and straight forward. In this series I am going to demonstrate, in a rather simplified manner, the internal workings of dependency injection frameworks by developing one from scratch, Voodoo DI.

Please note, Voodoo DI is meant SOLELY for educational purposes, if you are looking for production ready DI frameworks please look at CDI, Spring IoC or Google GUICE.

In this series I am going to concentrate on the annotation driven approach based on JSR-330 Dependency Injection for Java annotations used by all major DI frameworks.

JSR-330 Dependency Injection for Java specifies a common set of annotations that are used by Spring, Guice and CDI.

  • @Inject – defines injection points on fields, methods and constructors.
  • @Qualifier – A qualifier may annotate an injectable field or parameter and, combined with the type, identify the implementation to inject.
  • @Named – Similar to @Qualifier, it allows the identification of the correct implementation based on name and type.
  • @Singleton – Singleton scope, only one instance is created by the DI framework.
  • @Scoped – Used to define new scope annotations. The DI Framework may use these to define new contexts (e.g. @RequestScoped).

Continue reading Understanding Dependency Injection – Part 1 IoC

CDI Passivation Uncovered

Frequently there is confusion about passivation of contextual instances with CDI, especially when non-passivating scopes such as request scoped are injected in passivatable once.

The specification defines passivation (serialization) capabilities, allowing the container to free memory by transferring idle objects to secondary storage when required.

The temporary transfer of the state of an idle object held in memory to some form of secondary storage is called passivation.
The transfer of the passivated state back into memory is called activation.

CDI-Spec 1.2 – Chapter 6.6.1

CDI’s session and conversation scopes are the only build-in passivation capable scopes. Request and application scopes are not passivating capable. If a bean is defined with a passivating scope, it and all applied interceptors and decorators must be serializable (see CDI 1.2 Specification – 6.6.1. Passivation capable beans).

Passivation of Normal Scoped injections

When working with passivation capable scopes such as @SessionScoped, it is still possible to inject references to non-passivating scopes such as @ApplicationScoped. Application scoped beans are not passivation capable, however the injected dependencies are.

[java]
@SessionScoped
public class MySession implements Serializable {
@Inject
private MyAppData myAppData;

}

@ApplicationScoped
public class MyAppData {

}
[/java]
Continue reading CDI Passivation Uncovered

Pushing ahead on Concurrency for Java EE 8

JSR-236 has only been a half-hearted attempt at bringing asynchronous operations to the wider Java EE context, leaving many gaps or even specification bugs depending on how you see it. As of now the Concurrency Utilities for Java EE specification remains closed for Java EE 8.

One of the more painful omissions being the rather ambiguously defined CDI context propagation.

2.3.2.1 Tasks and Contexts and Dependency Injection (CDI)
CDI beans can be used as tasks. Such tasks could make use of injection if they are themselves components or
are created dynamically using various CDI APIs. However, application developers should be aware of the
following when using CDI beans as tasks:

  • Tasks that are submitted to a managed instance of ExecutorService may still be running after the
    lifecycle of the submitting component. Therefore, CDI beans with a scope of @RequestScoped,
    @SessionScoped, or @ConversationScoped are not recommended to use as tasks as it cannot be guaranteed
    that the tasks will complete before the CDI context is destroyed.
  • CDI beans with a scope of @ApplicationScoped or @Dependent can be used as tasks. However, it is still
    possible that the task could be running beyond the lifecycle of the submitting component, such as when
    the component is destroyed.
  • The transitive closure of CDI beans that are injected into tasks should follow the above guidelines
    regarding their scopes.

JSR-236 Concurrency Utilities for Java EE Version 1.0 FR

This specification leaves a lot of room for interpretation. The current consensus is that the spawning thread’s request, session and conversation contexts are not propagated to the asynchronous process. Furthermore the request context is not even activated for the asynchronous operation (see discussion “inheritance of CDI scopes” for more details).
Continue reading Pushing ahead on Concurrency for Java EE 8

Building extensible Java EE Applications – Part 2

The first part covered adapting and packaging extensible Java EE applications.

Introducing Plug-ins

This part will demonstrate how Java EE application can be extended via plug-ins.

To do so we will have to define Service provider interface(s) (SPI).

[java]
public interface CorePlugin {
public String getName();

}
[/java]

The applications SPI should be provided in a separate JAR decoupling plug-ins from the core application and avoid cyclic dependency issues (see the previous post for more details).
Continue reading Building extensible Java EE Applications – Part 2

Building extensible Java EE Applications – Part 1

With the advent of Java EE 6 it has become easier to build extensible applications. In this first post we will briefly explore how core components of standard applications can be customized with CDI @Specializes/@Decorator and more interestingly packaging the customized applications.

Specializes

Specialization in Java EE allows for simple customization of existing beans via inheritance. If a @Specializes bean is found on the classpath it will be injected instead of the original.

The specializing bean has to extend the original bean, it inherits all qualifiers and its name, if defined with @Named.

[java]
@RequestScoped
public class CoreService {
public void doStuff() {
System.out.println("Default implementation is doing Stuff.");
}
}

@Specializes
public class MySpezializedService extends CoreService {
@Override
public void doStuff() {
System.out.println("Spezialized implementation is doing Stuff.");
}
}
[/java]

MySpezializedService will be injected instead of MyDefaultService in any place where MyDefaultService has been defined for injection.
Continue reading Building extensible Java EE Applications – Part 1