This document discusses effective practices for dependency injection (DI). It begins with a quick DI refresher and then provides guidelines for DI such as: explicitly defining dependencies, injecting exactly what is needed, preferring constructor injection, avoiding work in constructors, and avoiding direct dependencies on the injector. It also discusses testing code using DI, applying DI to existing code, and techniques for migrating code to use DI such as bottom-up or top-down approaches.
The document describes a program for a multi-client chat client-server application using Java graphical programming. It includes the code for the ChatServer class that handles connections from multiple clients and broadcasts messages. It also includes the code for the ChatClient class that allows a client to connect to the server, send and receive messages, and view an online users list. The program allows for real-time text communication between multiple clients connected to a central server.
The document contains questions and multiple choice answers about C# programming concepts.
Question 6 identifies a problem in a code snippet where a delegate is declared to accept a string parameter, but the methods passed to it do not. The correct code fixes this by removing the string parameter from the methods.
Question 20 asks which code snippet would correctly overload the unary minus operator to negate the values of two integer properties. The correct code negates the property values directly rather than using decrement operators.
Enforce Consistentcy with Clean ArchitectureFlorin Coros
When projects fail for reasons that are primary technical, the reason is often uncontrolled complexity. The complexity goes out of hand when the code lacks structure, when it lacks Clean Architecture. In large software projects where many developers work on the same code base one of the biggest challenges is to get consistency in code, to create development patterns for common problems, so you can control the complexity and size of the system.
In this presentation I will show how we can achieve consistency through structure, rather than relying on discipline only. We will look at some basic building blocks of an application infrastructure which will enforce the way dependencies are created, how dependency injection is used or how separation of the data access concerns is enforced.
Virtual functions allow dynamic binding to occur. This means that the function called is determined at runtime based on the actual object type, rather than static binding which determines the function at compile time. Some key points:
1) A virtual function tells the compiler to create a pointer to the function but not fill it in until called.
2) Classes with virtual functions are called polymorphic classes and allow overriding derived class functions.
3) Virtual functions are useful for polymorphism when subclasses need to provide unique implementations of the same method name.
Vibrant Technologies is headquarted in Mumbai,India.We are the best Java training provider in Navi Mumbai who provides Live Projects to students.We provide Corporate Training also.We are Best Java classes in Mumbai according to our students and corporators
Contact Us On : http://vibranttechnologies.co.in/
SObjectizer is a C++ tool that simplifies building concurrent and event-driven applications. It handles message dispatching between agents (lightweight objects that interact asynchronously) and provides threads for message processing. The document describes SObjectizer's architecture, including its use of agents, messages, signals, and dispatchers. It provides examples of how to define agents and have them exchange messages to demonstrate SObjectizer's core features.
The document provides a tutorial on using Google GIN (GWT INjection) for dependency injection in GWT client-side code. It explains that GIN is built on top of Guice and brings automatic dependency injection to GWT applications. It then outlines the 5 steps to implement GIN: 1) design interfaces, 2) create implementation classes, 3) configure bindings in a module, 4) define a Ginjector interface, and 5) generate and use the Ginjector. The steps are then explained in further detail with examples.
This document provides an introduction and overview of creating and working with entity beans in EJB. It discusses what entity beans are, how they represent data in a persistence store like a database. It then covers how to create the key interfaces, bean class, and deployment descriptor for a sample entity bean that represents a Customer entity with ID, first name, and city attributes. It shows implementing required entity bean methods like ejbCreate, ejbLoad, ejbStore, and ejbFindByPrimaryKey to load, store, and find data in the backing database. Finally, it discusses deploying the entity bean and providing a simple JSP client to call its methods.
The document describes a program for a multi-client chat client-server application using Java graphical programming. It includes the code for the ChatServer class that handles connections from multiple clients and broadcasts messages. It also includes the code for the ChatClient class that allows a client to connect to the server, send and receive messages, and view an online users list. The program allows for real-time text communication between multiple clients connected to a central server.
The document contains questions and multiple choice answers about C# programming concepts.
Question 6 identifies a problem in a code snippet where a delegate is declared to accept a string parameter, but the methods passed to it do not. The correct code fixes this by removing the string parameter from the methods.
Question 20 asks which code snippet would correctly overload the unary minus operator to negate the values of two integer properties. The correct code negates the property values directly rather than using decrement operators.
Enforce Consistentcy with Clean ArchitectureFlorin Coros
When projects fail for reasons that are primary technical, the reason is often uncontrolled complexity. The complexity goes out of hand when the code lacks structure, when it lacks Clean Architecture. In large software projects where many developers work on the same code base one of the biggest challenges is to get consistency in code, to create development patterns for common problems, so you can control the complexity and size of the system.
In this presentation I will show how we can achieve consistency through structure, rather than relying on discipline only. We will look at some basic building blocks of an application infrastructure which will enforce the way dependencies are created, how dependency injection is used or how separation of the data access concerns is enforced.
Virtual functions allow dynamic binding to occur. This means that the function called is determined at runtime based on the actual object type, rather than static binding which determines the function at compile time. Some key points:
1) A virtual function tells the compiler to create a pointer to the function but not fill it in until called.
2) Classes with virtual functions are called polymorphic classes and allow overriding derived class functions.
3) Virtual functions are useful for polymorphism when subclasses need to provide unique implementations of the same method name.
Vibrant Technologies is headquarted in Mumbai,India.We are the best Java training provider in Navi Mumbai who provides Live Projects to students.We provide Corporate Training also.We are Best Java classes in Mumbai according to our students and corporators
Contact Us On : http://vibranttechnologies.co.in/
SObjectizer is a C++ tool that simplifies building concurrent and event-driven applications. It handles message dispatching between agents (lightweight objects that interact asynchronously) and provides threads for message processing. The document describes SObjectizer's architecture, including its use of agents, messages, signals, and dispatchers. It provides examples of how to define agents and have them exchange messages to demonstrate SObjectizer's core features.
The document provides a tutorial on using Google GIN (GWT INjection) for dependency injection in GWT client-side code. It explains that GIN is built on top of Guice and brings automatic dependency injection to GWT applications. It then outlines the 5 steps to implement GIN: 1) design interfaces, 2) create implementation classes, 3) configure bindings in a module, 4) define a Ginjector interface, and 5) generate and use the Ginjector. The steps are then explained in further detail with examples.
This document provides an introduction and overview of creating and working with entity beans in EJB. It discusses what entity beans are, how they represent data in a persistence store like a database. It then covers how to create the key interfaces, bean class, and deployment descriptor for a sample entity bean that represents a Customer entity with ID, first name, and city attributes. It shows implementing required entity bean methods like ejbCreate, ejbLoad, ejbStore, and ejbFindByPrimaryKey to load, store, and find data in the backing database. Finally, it discusses deploying the entity bean and providing a simple JSP client to call its methods.
PVS-Studio analyzer is continuously improving, and the C#-code analysis module is developing most actively: ninety new diagnostic rules were added in 2016. However, the best way to estimate the analyzer's efficiency is to look at the bugs it can catch. It's always interesting, as well as useful, to do recurring checks of large open-source projects at certain intervals and compare their results. Today I will talk about the results of the second analysis of SharpDevelop project.
This document discusses timers in SObjectizer-5.5, including delayed messages which are delivered after a specified delay, periodic messages which are delivered repeatedly with a specified period, and cancellation of timers. It provides examples of how to send delayed and periodic messages using send_delayed(), send_periodic(), and schedule_timer(), and how timers can be cancelled by calling release() on the timer ID or letting the last timer ID go out of scope.
This document provides instructions for setting up and running a bot project using the Bot Builder SDK v4. It discusses downloading necessary software, creating a project in Visual Studio, implementing a welcome message, and managing state using user profiles and state accessors. The document contains code samples for creating a SampleBot class that inherits from IBot and uses state accessors and user profiles to save and retrieve a user's handle name.
Part I of a presentation on Advanced Concepts in JavaScript. Cover topics like: objects, functions, closures, inheritance, new platform features, and much more.
Read more: http://luisatencio.net
The document describes how to write functional test cases for SQL queries and web applications using JUnit in Java. It includes:
1) Creating a connection class to establish a connection to a MySQL database.
2) Defining classes containing methods that implement the functionality to be tested.
3) Writing JUnit test cases that call the functionality methods.
4) Using annotations like @Before, @Test, and @After for test initialization, execution, and teardown.
Club of anonimous developers "Refactoring: Legacy code"Victor_Cr
The document discusses various approaches to refactoring legacy code, including:
1. Migrating from an older build system (TOM) to a newer one (POM) by updating XML configuration files.
2. Introducing inversion of control (IoC) and dependency injection (DI) to reduce tight coupling in the code.
3. Implementing aspect-oriented programming (AOP) to separate cross-cutting concerns like transaction management and exception handling.
4. Updating older libraries to newer versions for performance improvements and richer APIs.
5. Cleaning up messy and difficult to read code through techniques like extracting methods and using regular expressions.
We are happy to invite you to the Speakers’ Corner today, on Thursday May 29, from 18.30 till 19.30 at SkyPoint to meet Thomas Vervik, Head of Development Bipper Communications who will talk on “How to save money on QA - Dependency Injection and automated testing on Android”
Thomas is Head of Development for Bipper Communications, and has been managing the company's team in Kiev since February 2012. Originally a seasoned Java server backend/frontend developer, he has the last two years started mobile development, first with HTML 5 and later Android.
Mobile development has since its birth around 2008 gone from simple apps to more complex enterprise similar software. The increase in size and complexity yields the need for structuring the code differently in order to handle the new complexity. The tools used to handle this complexity has been applied to server side development for years, but mobile development has been lagging behind.
But not anymore. New frameworks built on proven paradigms are emerging, and in this Speakers Corner we will introduce Dependency Injection for Android, the motivation for its use, and one of the implementations - Dagger. Dependency Injection has several advantages, but in this presentation we will focus on how it enables to write proper automated tests.
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014First Tuesday Bergen
We are happy to invite you to the Speakers’ Corner today, on Thursday May 29, from 18.30 till 19.30 at SkyPoint to meet Thomas Vervik, Head of Development Bipper Communications who will talk on “How to save money on QA - Dependency Injection and automated testing on Android”
Thomas is Head of Development for Bipper Communications, and has been managing the company's team in Kiev since February 2012. Originally a seasoned Java server backend/frontend developer, he has the last two years started mobile development, first with HTML 5 and later Android.
Mobile development has since its birth around 2008 gone from simple apps to more complex enterprise similar software. The increase in size and complexity yields the need for structuring the code differently in order to handle the new complexity. The tools used to handle this complexity has been applied to server side development for years, but mobile development has been lagging behind.
But not anymore. New frameworks built on proven paradigms are emerging, and in this Speakers Corner we will introduce Dependency Injection for Android, the motivation for its use, and one of the implementations - Dagger. Dependency Injection has several advantages, but in this presentation we will focus on how it enables to write proper automated tests.
The document provides information about C++ aptitude and object-oriented programming (OOP) concepts. It contains sample C++ code snippets and questions with explanations to test understanding of topics like classes, inheritance, polymorphism, operator overloading, templates, and more.
Implementation of fix messages for fix 5.0 sp2 and fixt1.1 specificationNeeraj Kaushik
This document summarizes how to connect to a FIX 5.0 SP2 and FIXT 1.1 server and implement FIX messages using QuickFix/N, an open source .NET FIX engine. It demonstrates creating a FIX initiator client application that can send and receive messages like MarketDataRequest and the responses MarketDataSnapshot and MarketDataIncrementalRefresh. The key steps shown are configuring the initiator, creating an application class that implements the QuickFix interfaces, setting up the initiator, and implementing message handling callbacks. Code examples are provided.
This document discusses different versions of Spring and new features introduced. Spring 3.0 added support for Servlet 3.0, Java SE 7, and MVC additions. Spring 4.0 fully supports Java 8 features and removes deprecated packages/methods. It also includes Groovy bean definition DSL, core container improvements, general web improvements, and testing improvements. Some key features are lambda expressions, date/time API updates, and optional return types in Java 8 as well as conditionally enabling beans and autowiring improvements.
The document summarizes the key differences between JUnit 4 and JUnit 5 (alpha). Some of the main changes in JUnit 5 include updated annotations like @Test, support for lambda-based assertions using Hamcrest matchers, assumptions and exception testing capabilities, and support for nested and parameterized tests. JUnit 5 also overhauls extension mechanisms and introduces extension points for customization. While still in development, JUnit 5 is moving to an API based on extensions and customization points rather than the runner approach used in JUnit 4.
Le temps est révolu où Java EE ne serait qu’à développer des applications de mise à jour de données, avec JSF / EJB / JPA. Aujourd’hui Java EE s’est assoupli et s’est ouvert sur le monde, avec CDI comme clé de voûte et a repoussé nos limites grâce à des capacités d’extension puissantes et faciles d’utilisation comme JCA.
Dans un premier temps, nous reviendrons rapidement sur la place de CDI dans JavaEE 7 et sur ses mécanismes d’extension. Dans un deuxième temps, nous verrons les techniques de connecteurs JCA et comment ils peuvent aussi constituer une possibilité d’ouverture simple à mettre en œuvre. JCA fournit des techniques pour gérer des connexions sortantes ou entrantes, sur des formats ou protocoles variés.
This document discusses 10 typical problems seen in enterprise Java applications. Problem #6 is having no data access object (DAO) layer, resulting in services directly using persistence mechanisms like JPA or JDBC. This makes code impossible to test without a database, tightly couples services to persistence, and provides no structure for adding data-dependent features like security. The solution is to use a DAO layer to abstract away the persistence, separating this technical concern from the service layer.
Reactive Model-View-ViewModel ArchitectureGyuwon Yi
컨텐츠 중심의 모바일 서비스 응용프로그램을 개발하기 위해 MVVM(Model-View-ViewModel) 패턴과 Rx(Reactive Extensions)를 활용해 설계한 Reactive MVVM 아키텍쳐를 설명합니다. 조금 더 자세한 설명은 블로그 포스트를 참고하세요. https://justhackem.wordpress.com/2015/03/19/rmvvm-architecture/
Poche chiacchiere e tanto codice per cercare rendere la nostra vita di
sviluppatori più divertente.
Parleremo di JAX-RS, le annotazioni, l'MVC che mette a disposizione e
l'integrazione di Jersey con Guice.
Useremo AOP per gestire log, transazioni e con l'aiuto di Infinispan
limiteremo le chamate concorrenti sul nostro cluster.
This document provides an overview of Parsley, an application framework for Flex and Flash applications. Parsley uses an Inversion of Control (IoC) container and messaging framework to enable highly decoupled architectures. It features a flexible IoC container, dependency injection, a messaging framework, and tools for modularity, object lifecycles, localization and extensibility. Parsley implements inversion of control through its IoC container, which manages object lifecycles and dependencies. It supports dependency injection through constructor, setter, and interface injection. Developers configure Parsley by specifying classes and dependencies in MXML, XML, or code attributes.
The document discusses various techniques for unit testing concurrent code, including using JUnit, TestNG, and a custom ThreadWeaver framework to test for threading issues in a FlawedList implementation. It also covers using jcstress for concurrency stress testing and notes that jcstress results may vary between runs and depend on processor architecture memory access semantics.
Creational Pattern of the design pattern.
Introducing 6 type patterns and also including the pros and cons. It's easy to understand what's kind of scenario it should be used.
This document introduces Google Guice, a dependency injection framework. It discusses dependency injection, benefits like separation of concerns and easier testing. It also covers disadvantages like potential maintenance issues. The document explores the Guice API including Injector, Module, Binder and different types of bindings like linked, annotated, instance and constructor bindings. It provides a simple example using traits, classes and annotations to demonstrate dependency injection with Guice. References for more information on Guice and dependency injection are also included.
The document discusses the evolution of Java EE technologies from JavaServer Faces (JSF) to Contexts and Dependency Injection (CDI). It provides code examples demonstrating how common features like controllers, dependency injection, interceptors, and routing were implemented in JSF using annotations like @ManagedBean and @Interceptor and how they evolved to use CDI annotations like @Inject and event observers. The examples show how CDI aligned these features with standard Java practices and provided a more modular, decoupled approach.
This document provides an overview of Google Guice, an open source Java framework for dependency injection. It discusses key Guice concepts like dependency injection, bindings, providers, and scopes. It also covers advanced topics such as aspect-oriented programming with Guice, integration with other frameworks like Spring, and using Guice in servlets. The goal of Guice is to simplify dependency management and increase testability by removing hard-coded dependencies.
PVS-Studio analyzer is continuously improving, and the C#-code analysis module is developing most actively: ninety new diagnostic rules were added in 2016. However, the best way to estimate the analyzer's efficiency is to look at the bugs it can catch. It's always interesting, as well as useful, to do recurring checks of large open-source projects at certain intervals and compare their results. Today I will talk about the results of the second analysis of SharpDevelop project.
This document discusses timers in SObjectizer-5.5, including delayed messages which are delivered after a specified delay, periodic messages which are delivered repeatedly with a specified period, and cancellation of timers. It provides examples of how to send delayed and periodic messages using send_delayed(), send_periodic(), and schedule_timer(), and how timers can be cancelled by calling release() on the timer ID or letting the last timer ID go out of scope.
This document provides instructions for setting up and running a bot project using the Bot Builder SDK v4. It discusses downloading necessary software, creating a project in Visual Studio, implementing a welcome message, and managing state using user profiles and state accessors. The document contains code samples for creating a SampleBot class that inherits from IBot and uses state accessors and user profiles to save and retrieve a user's handle name.
Part I of a presentation on Advanced Concepts in JavaScript. Cover topics like: objects, functions, closures, inheritance, new platform features, and much more.
Read more: http://luisatencio.net
The document describes how to write functional test cases for SQL queries and web applications using JUnit in Java. It includes:
1) Creating a connection class to establish a connection to a MySQL database.
2) Defining classes containing methods that implement the functionality to be tested.
3) Writing JUnit test cases that call the functionality methods.
4) Using annotations like @Before, @Test, and @After for test initialization, execution, and teardown.
Club of anonimous developers "Refactoring: Legacy code"Victor_Cr
The document discusses various approaches to refactoring legacy code, including:
1. Migrating from an older build system (TOM) to a newer one (POM) by updating XML configuration files.
2. Introducing inversion of control (IoC) and dependency injection (DI) to reduce tight coupling in the code.
3. Implementing aspect-oriented programming (AOP) to separate cross-cutting concerns like transaction management and exception handling.
4. Updating older libraries to newer versions for performance improvements and richer APIs.
5. Cleaning up messy and difficult to read code through techniques like extracting methods and using regular expressions.
We are happy to invite you to the Speakers’ Corner today, on Thursday May 29, from 18.30 till 19.30 at SkyPoint to meet Thomas Vervik, Head of Development Bipper Communications who will talk on “How to save money on QA - Dependency Injection and automated testing on Android”
Thomas is Head of Development for Bipper Communications, and has been managing the company's team in Kiev since February 2012. Originally a seasoned Java server backend/frontend developer, he has the last two years started mobile development, first with HTML 5 and later Android.
Mobile development has since its birth around 2008 gone from simple apps to more complex enterprise similar software. The increase in size and complexity yields the need for structuring the code differently in order to handle the new complexity. The tools used to handle this complexity has been applied to server side development for years, but mobile development has been lagging behind.
But not anymore. New frameworks built on proven paradigms are emerging, and in this Speakers Corner we will introduce Dependency Injection for Android, the motivation for its use, and one of the implementations - Dagger. Dependency Injection has several advantages, but in this presentation we will focus on how it enables to write proper automated tests.
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014First Tuesday Bergen
We are happy to invite you to the Speakers’ Corner today, on Thursday May 29, from 18.30 till 19.30 at SkyPoint to meet Thomas Vervik, Head of Development Bipper Communications who will talk on “How to save money on QA - Dependency Injection and automated testing on Android”
Thomas is Head of Development for Bipper Communications, and has been managing the company's team in Kiev since February 2012. Originally a seasoned Java server backend/frontend developer, he has the last two years started mobile development, first with HTML 5 and later Android.
Mobile development has since its birth around 2008 gone from simple apps to more complex enterprise similar software. The increase in size and complexity yields the need for structuring the code differently in order to handle the new complexity. The tools used to handle this complexity has been applied to server side development for years, but mobile development has been lagging behind.
But not anymore. New frameworks built on proven paradigms are emerging, and in this Speakers Corner we will introduce Dependency Injection for Android, the motivation for its use, and one of the implementations - Dagger. Dependency Injection has several advantages, but in this presentation we will focus on how it enables to write proper automated tests.
The document provides information about C++ aptitude and object-oriented programming (OOP) concepts. It contains sample C++ code snippets and questions with explanations to test understanding of topics like classes, inheritance, polymorphism, operator overloading, templates, and more.
Implementation of fix messages for fix 5.0 sp2 and fixt1.1 specificationNeeraj Kaushik
This document summarizes how to connect to a FIX 5.0 SP2 and FIXT 1.1 server and implement FIX messages using QuickFix/N, an open source .NET FIX engine. It demonstrates creating a FIX initiator client application that can send and receive messages like MarketDataRequest and the responses MarketDataSnapshot and MarketDataIncrementalRefresh. The key steps shown are configuring the initiator, creating an application class that implements the QuickFix interfaces, setting up the initiator, and implementing message handling callbacks. Code examples are provided.
This document discusses different versions of Spring and new features introduced. Spring 3.0 added support for Servlet 3.0, Java SE 7, and MVC additions. Spring 4.0 fully supports Java 8 features and removes deprecated packages/methods. It also includes Groovy bean definition DSL, core container improvements, general web improvements, and testing improvements. Some key features are lambda expressions, date/time API updates, and optional return types in Java 8 as well as conditionally enabling beans and autowiring improvements.
The document summarizes the key differences between JUnit 4 and JUnit 5 (alpha). Some of the main changes in JUnit 5 include updated annotations like @Test, support for lambda-based assertions using Hamcrest matchers, assumptions and exception testing capabilities, and support for nested and parameterized tests. JUnit 5 also overhauls extension mechanisms and introduces extension points for customization. While still in development, JUnit 5 is moving to an API based on extensions and customization points rather than the runner approach used in JUnit 4.
Le temps est révolu où Java EE ne serait qu’à développer des applications de mise à jour de données, avec JSF / EJB / JPA. Aujourd’hui Java EE s’est assoupli et s’est ouvert sur le monde, avec CDI comme clé de voûte et a repoussé nos limites grâce à des capacités d’extension puissantes et faciles d’utilisation comme JCA.
Dans un premier temps, nous reviendrons rapidement sur la place de CDI dans JavaEE 7 et sur ses mécanismes d’extension. Dans un deuxième temps, nous verrons les techniques de connecteurs JCA et comment ils peuvent aussi constituer une possibilité d’ouverture simple à mettre en œuvre. JCA fournit des techniques pour gérer des connexions sortantes ou entrantes, sur des formats ou protocoles variés.
This document discusses 10 typical problems seen in enterprise Java applications. Problem #6 is having no data access object (DAO) layer, resulting in services directly using persistence mechanisms like JPA or JDBC. This makes code impossible to test without a database, tightly couples services to persistence, and provides no structure for adding data-dependent features like security. The solution is to use a DAO layer to abstract away the persistence, separating this technical concern from the service layer.
Reactive Model-View-ViewModel ArchitectureGyuwon Yi
컨텐츠 중심의 모바일 서비스 응용프로그램을 개발하기 위해 MVVM(Model-View-ViewModel) 패턴과 Rx(Reactive Extensions)를 활용해 설계한 Reactive MVVM 아키텍쳐를 설명합니다. 조금 더 자세한 설명은 블로그 포스트를 참고하세요. https://justhackem.wordpress.com/2015/03/19/rmvvm-architecture/
Poche chiacchiere e tanto codice per cercare rendere la nostra vita di
sviluppatori più divertente.
Parleremo di JAX-RS, le annotazioni, l'MVC che mette a disposizione e
l'integrazione di Jersey con Guice.
Useremo AOP per gestire log, transazioni e con l'aiuto di Infinispan
limiteremo le chamate concorrenti sul nostro cluster.
This document provides an overview of Parsley, an application framework for Flex and Flash applications. Parsley uses an Inversion of Control (IoC) container and messaging framework to enable highly decoupled architectures. It features a flexible IoC container, dependency injection, a messaging framework, and tools for modularity, object lifecycles, localization and extensibility. Parsley implements inversion of control through its IoC container, which manages object lifecycles and dependencies. It supports dependency injection through constructor, setter, and interface injection. Developers configure Parsley by specifying classes and dependencies in MXML, XML, or code attributes.
The document discusses various techniques for unit testing concurrent code, including using JUnit, TestNG, and a custom ThreadWeaver framework to test for threading issues in a FlawedList implementation. It also covers using jcstress for concurrency stress testing and notes that jcstress results may vary between runs and depend on processor architecture memory access semantics.
Creational Pattern of the design pattern.
Introducing 6 type patterns and also including the pros and cons. It's easy to understand what's kind of scenario it should be used.
This document introduces Google Guice, a dependency injection framework. It discusses dependency injection, benefits like separation of concerns and easier testing. It also covers disadvantages like potential maintenance issues. The document explores the Guice API including Injector, Module, Binder and different types of bindings like linked, annotated, instance and constructor bindings. It provides a simple example using traits, classes and annotations to demonstrate dependency injection with Guice. References for more information on Guice and dependency injection are also included.
The document discusses the evolution of Java EE technologies from JavaServer Faces (JSF) to Contexts and Dependency Injection (CDI). It provides code examples demonstrating how common features like controllers, dependency injection, interceptors, and routing were implemented in JSF using annotations like @ManagedBean and @Interceptor and how they evolved to use CDI annotations like @Inject and event observers. The examples show how CDI aligned these features with standard Java practices and provided a more modular, decoupled approach.
This document provides an overview of Google Guice, an open source Java framework for dependency injection. It discusses key Guice concepts like dependency injection, bindings, providers, and scopes. It also covers advanced topics such as aspect-oriented programming with Guice, integration with other frameworks like Spring, and using Guice in servlets. The goal of Guice is to simplify dependency management and increase testability by removing hard-coded dependencies.
This document provides an overview of Contexts and Dependency Injection (CDI) in Java EE 6. It discusses what CDI is, its key features like type-safe dependency injection and automatic contextual lifecycle management. It covers different types of injection like field, method parameter, and constructor injection. It also discusses qualifiers and scopes that allow controlling which implementations are injected in different contexts. The document provides examples of request scoped and application scoped beans and how they are used. It lists some CDI implementation options and supported application containers. It also provides resources to learn more about CDI.
Daggerate your code - Write your own annotation processorBartosz Kosarzycki
The document discusses annotation processing in Java, including libraries that are useful for annotation processing like Google AutoService and Square JavaPoet. It provides an overview of the basic structure of an annotation processor class and explains how to access elements from the source code being processed. It also covers how to generate new source code files using JavaPoet and write them out using the Filer. Debugging annotation processors is discussed.
Thomas braun dependency-injection_with_robo_guice-presentation-finalDroidcon Berlin
The document discusses dependency injection (DI) using RoboGuice in Android applications. DI makes code more concise, modular, and easier to test by allowing classes to declare dependencies without knowing how they are satisfied. RoboGuice uses annotations to inject dependencies into activities and services. It allows for loose coupling, high cohesion, and centralized configuration through bindings. DI improves testability by increasing controllability, observability, and isolation of units under test.
This document provides an overview of Google Web Toolkit (GWT), including its architecture, key features, and how to implement common tasks. GWT is a development toolkit that allows web applications to be written in Java and compiled into JavaScript for better cross-browser compatibility. It discusses topics like building user interfaces with widgets, event handling, styling with CSS, making remote procedure calls, and accessing native JavaScript methods. Examples and demos are provided to illustrate concepts like creating custom widgets, handling events, and making asynchronous server calls. Resources for learning more about GWT are also listed.
CDI provides standards-based and typesafe dependency injection in Java EE 6. It integrates well with other Java EE 6 technologies like EJB, JPA, JSF, and JAX-WS. Portable extensions facilitate a richer programming model. Weld is the reference implementation of CDI and is integrated into application servers like GlassFish and JBoss.
This document provides an overview of the Guice and Gin dependency injection frameworks. It discusses key features of Guice like annotation-based configuration, scopes, and type-safe injection. It compares Guice to Spring, noting Guice's simpler configuration. It also covers using Guice and Gin in web applications and GWT clients. Additional topics include the Warp utilities, configuration options like @Named, and limitations of Gin for GWT apps.
The document discusses testing in Android applications. It recommends moving as much logic as possible to the Java Virtual Machine (JVM) to allow for easier unit testing. This includes business logic, models, and network code using Retrofit. It also suggests using Espresso for UI testing on Android and monkeyrunner for basic OS interaction testing. The document acknowledges testing on Android can be painful due to speed and fragmentation issues, and proposes compromises like helping quality assurance engineers with tools like the Bee library.
This document provides an overview of the Guice and Gin dependency injection frameworks. It discusses key features and differences between the two, including how Guice supports both server-side and client-side Java applications while Gin is tailored specifically for GWT client-side apps. Examples are given of basic usage and configuration for common tasks like singleton scopes and dependency injection.
Czym się różnie JMS od AMQP? Co to jest queue? Co to jest topic? Jak zlecać zadania w przyszłości używając kolejek? Jak się do tego podpiąć z Javy? Na te i inne pytania postaram się odpowiedzieć na mojej prezentacji.
This document discusses building maintainable Android apps using Model-View-Presenter (MVP) architecture and Dagger 2 for dependency injection. It recommends separating an app into modules for each concern, like views, presenters, models, and dependencies. It also describes how to set up Dagger components and modules to inject dependencies into activities and presenters while allowing for testing with mocks. Subcomponents are used to scope dependencies for individual activities. The MVP pattern helps avoid tight coupling between components for better testability and maintenance.
https://www.youtube.com/watch?v=9fn5s8_CYJI
Dagger is a complex tool, we can all agree on that. It's also the most performant and scalable dependency injector we have available -- no wonder it's the official recommendation from Google when it comes to dependency injection for Android apps. And yet, we keep looking for simpler alternatives (usually service locators) just so we don't have to deal with it.
Even thought Dagger is complex, it doesn't have to be complicated. It's possible to keep things simple and still take advantage of what it offers at its core. There are many ways to setup Dagger, and believe it or not, some of them are quite simple. The goal of this talk is to present a simplistic approach to Dagger, where we can take advantage of dependency injection with minimal boilerplate and optimum performance. On top of that, we'll be looking in details on best practices and how to ensure you're taking the most out of Dagger.
Join me if you've had unpleasant experiences with Dagger -- or even if you're happy with your current setup -- so we can take a fresh look on how we can work with it. And if you haven't worked with Dagger before, this is the perfect opportunity to get off on the right foot!
https://androidmakers.fr/schedule/?sessionId=YYF-6635
JVM Mechanics: When Does the JVM JIT & Deoptimize?Doug Hawkins
HotSpot promises to do the "right" thing for us by identifying our hot code and compiling "just-in-time", but how does HotSpot make those decisions?
This presentation aims to detail how HotSpot makes those decisions and how it corrects its mistakes through a series of demos that you run yourself.
Architecting your GWT applications with GWT-Platform - Lesson 02rhemsolutions
This document discusses architecting a GWT application with the GWT-Platform framework. It recommends using a Model-View-Presenter architecture and describes some MVP frameworks for GWT including gwt-platform. It provides an overview of how to structure an app with GWT-Platform and GXT3 including using places, tokens, presenters and dependency injection with GIN. It also covers styling the app with ClientBundle and includes sample code for creating a default presenter.
Stopping the Rot - Putting Legacy C++ Under TestSeb Rose
The document discusses introducing unit testing to legacy C++ code. It covers choosing a testing framework, writing initial tests and mocks, and various refactoring techniques like wrapping dependencies, extracting components, and adding non-intrusive C seams to facilitate testing. The goal is to incrementally make the code more testable while maintaining functionality through practices like test-driven development.
This document summarizes the key aspects of building maintainable Android applications using MVP architecture and Dagger 2 for dependency injection. It discusses using MVP to separate concerns into Model, View, and Presenter classes and interfaces. It explains how Dagger 2 can be used to inject dependencies into classes while avoiding direct dependencies between classes. It provides examples of implementing MVP with Dagger 2 modules and components to inject dependencies into activities and presenters. It also discusses using subcomponents to scope dependencies to specific features and mocks for testing.
Binding business data to vaadin componentsPeter Lehto
There are two main differences between setPropertyDataSource() and setContainerDataSource() for Vaadin components:
1. Data source type - setPropertyDataSource() binds the component to a single property, while setContainerDataSource() binds it to a full Container which can contain multiple items and properties.
2. Data binding - setPropertyDataSource() binds the component value to a specific property of the current item. setContainerDataSource() does not directly bind the component, it just sets the container as the available options but does not automatically select any value. The component does not know which property in the container to use as the value.
So in summary:
- setPropertyDataSource() binds a single component to a specific property
The document discusses SOLID principles of object-oriented design. It provides examples of code that demonstrate poor adherence to SOLID and ways the code can be refactored to better follow SOLID. Specifically, it shows how to apply the single responsibility principle, open/closed principle, Liskov substitution principle, interface segregation principle and dependency inversion principle to structure code for flexibility, reusability and maintainability.
2. This talk
1. Quick DI refresher
2. Guidelines for effective DI
3. Composing applications using DI
4. Testing code using DI
5. Applying DI to existing code
4. DI = Dependency Injection
Declare what you need, not how to get it
PaymentProcessor(
CreditCardService creditCardService) {
this.creditCardService = creditCardService;
this.riskAssessor =
new RiskAssessorImpl(...);
}
5. DI = Dependency Injection
+ Loose coupling, facilitate reuse and testing
- Complexity, runtime failures
Many frameworks with many tools
Important to establish good conventions
6. DI Framework
● Providers
● Bindings
● @Inject
● Module [= collection of Bindings]
● Injector [= collection of Modules]
○ injector.getInstance(type)
● Scopes
8. Explicit > Implicit
● Ensure explicit bindings for all injected types
○ bind(RequestFilter.class);
● Implicit bindings dangerous
○ Removing an explicit binding
○ Pulling in undesired explicit binding
9. Inject exactly what you need
Bad:
PaymentProcessor(User user) {
this.account = user.getAccount();
}
Better:
PaymentProcessor(Account account) {
this.account = account;
}
10. Prefer constructor injection
● private final fields
● Immutability, thread-safety
● Objects valid post-construction
● Match developer expectations
11. Avoid work in constructors
● Separation of concerns, facilitates testing,
"standard" constructor
● In Guice: runtime ProvisionException
easily propagates up to top level
● Initialize after constructing object graph
12. If you must do work in a constructor
interface DataStoreProvider<T> extends CheckedProvider<T> {
T get() throws DataStoreException;
}
Guice-specific
13. If you must do work in a constructor
(cont'd)
@CheckedProvides(DataStoreProvider.class)
Contacts provideContacts(UserId userId, DataStore dataStore)
throws DataStoreException {
return dataStore.readUserContacts(userId);
}
@Override protected void configure() {
install(ThrowingProviderBinder.forModule(this));
}
Guice-specific
14. If you must do work in a constructor
(cont'd)
@Inject ContactsFormatter(
DataStoreProvider<Contacts> contactsProvider) {
this.contactsProvider = contactsProvider;
}
String formatContacts() throws DataStoreException {
Contacts contacts = contactsProvider.get(); // throws
...
}
Guice-specific
15. If you must do work in a constructor
(cont'd)
Problems
● More complex, verbose bindings
● More setup work for tests
● Business logic creep
● Viral
Guice-specific
16. Avoid direct deps on Injector
● No longer declaring specific deps
● Injector allows dep on anything
● Easy to start using Injector, hard to stop
17. Avoid binding very general types
Bad
bindConstant().to(8080);
@Inject int port;
Better
bindConstant().annotatedWith(ForHttp.class)
.to(8080);
@Inject @ForHttp int port;
18. Avoid parameterized binding
annotations
At first it seems convenient...
@Named("http") int httpPort;
...but then you do
@Named("HTTP") int httpPort;
No help from the IDE, more runtime errors.
Harder to track down injection sites.
19. Using parameterized binding
annotations safely
Consistently use constants (enums!) for parameters:
@ForPort(Ports.HTTP) int httpPort;
@FeatureEnabled(Features.X) boolean xEnabled;
20. Keep modules fast and side-effect
free
Make it easy to compose modules
Avoid
● bind().toInstance(...)
● requestStaticInjection(...)
● Serial eager initialization of objects
Guice-specific
21. Prefer Null Objects over @Nullable
@Provides AbuseService provideAbuseService(
@ForAbuse String abuseServiceAddress) {
if (abuseServiceAddress.isEmpty()) { return null; }
return new AbuseServiceImpl(abuseServiceAddress);
}
class AbuseChecker {
@Inject AbuseChecker(
@Nullable AbuseService abuseService) { ... }
void doAbuseCheck(...) {
if (abuseService != null) { ... )
}
Bind StubAbuseService instead of null. Simplify
AbuseChecker.
23. Scoping as an alternative to context
public interface PipelineVisitor() {
void visit(TypeToVisit typeToVisit);
}
public class Pipeline() {
private final PipelineVisitor[] visitors = {
new Visitor1(), new Visitor2(), ...
}
public void visit(TypeToVisit typeToVisit) {
...
}
}
24. Requirements creep in, you add
more parameters...
public interface PipelineVisitor() {
void visit(TypeToVisit typeToVisit, User user);
}
public interface PipelineVisitor() {
void visit(TypeToVisit typeToVisit,
User user, Logger logger);
}
public interface PipelineVisitor() {
void visit(TypeToVisit typeToVisit,
User user, Logger logger, RequestParams params);
}
and so on...
25. Ah yes, the Context to the rescue
public interface PipelineVisitor() {
void visit(PipelineContext context);
}
public Class PipelineContext {
TypeToVisit typeToVisit;
User user;
Logging logging;
... and many more ...
}
26. and adapts the Pipeline itself.
public class Pipeline() {
private final PipelineVisitor[] visitors = { ... };
OutputType visit(TypeToVisit in, User user, Logging
log)
{
OutputType out = new OutputType();
PipelineContext context =
new PipelineContext(in, user, log);
for (PipelineVisitor visitor : visitors) {
visitor.visit(context);
}
}
}
what about testing, isolation,...
27. First : remove the context
public interface Visitor {
void visit(TypeToVisit in);
}
public class LoggerVisitor {
private final Logger logger;
@Inject public LoggerVisitor(Logger logger) {...}
void visit(InputType in, Output out) {
logger.log(Level.INFO, "Visiting " + in);
}
public class UserDependentVisitor {
private final User user;
...
}
28. Second : use a Multi-Binder
class VisitorsModule extend AbstractModule {
@Override protected void configure() {
Multibinder<PipelineVisitor> visitorBinder =
Multibinder.newSetBinder(
binder(), PipelineVisitor.class);
visitorBinder.addBinding().to(LoggerVisitor.class);
visitorBinder.addBinding()
.to(UserDependentVisitor.class);
}
Now we can inject a Set<Visitor>
29. Inject into Pipeline
public class Pipeline() {
private final Set<Provider<PipelineVisitor.class>>
visitors
@Inject
Pipeline(Set<Provider<PipelineVisitor.class>> visitors) {
this.visitors = visitors;
}
public void visit(TypeToVisit in) {
for (Provider<PipelineVisitor.class> visitor :
visitors)
{
visitor.get().visit(in);
...
30. Testing Visitors and Pipeline
public void testVisitor() {
Visitor v = new FirstVisitor(...);
v.visit(in);
assert(...)
}
public void testPipeline() {
Visitor v = Mockito.mock(Visitor.class);
Pipeline p = new Pipeline(Sets.of(Providers.of(v)));
TypeToVisit in = new TypeToVisit(...);
p.visit(in);
Mockito.verify(v).visit(eq(in),
any(Output.class));
}
32. Modular Java!
Use a Service-Based Architecture
● All services defined as an interface
● Implementations package-private
● Package-level Module binds
No need for OSGi unless you need:
● Runtime extensibility
● Runtime versioning
33. Modular Java: Declare API and Impl
API: (interfaces, enums, binding annotations)
public interface SpamChecker {
void checkIsSpam(...);
}
Implementation: (package private)
class SpamCheckerImpl implements SpamChecker {
void checkIsSpam(...) { ... }
}
34. Modular Java: Colocate bindings
In the same package as SpamChecker*:
public class SpamCheckerModule extends AbstractModule {
@Override
public void configure() {
bind(SpamCheckerImpl.class).in(Singleton.class);
bind(SpamChecker.class).to(SpamCheckerImpl.class);
}
}
To use in your app, install SpamCheckerModule
and then inject SpamChecker as needed.
35. Modular Java: Document deps
Document what your module requires:
class SpamCheckerModule ... {
@Override protected void configure() {
requireBinding(Clock.class);
requireBinding(CryptoService.class);
...
}
}
36. Modular Java: Package it all up
1. Maven
a. All public interfaces in -api.jar module
b. All implementations and modules in -impl.jar
c. api module should only be used for compiling
dependent modules, impl module should be used for
assembling the application
2. OSGi
a. Export interfaces and Module only
b. Avoid versioning at runtime
38. Unit testing a class using DI
public class SubjectUnderTest {
@Inject
SubjectUnderTest(Service1 s1, Service2 s2) {
// Assign to fields
}
String doSomething() { ... }
}
39. Unit testing a class using DI (cont'd)
Service1 mock1 = Mockito.mock(Service1.class);
Service2 mock2 = Mockito.mock(Service2.class);
SubjectUnderTest sut = new SubjectUnderTest(
mock1, mock2);
// configure mock
Mockito.when(mock1).service(eq("param"))
.thenReturn("some return value);
// test your service
sut.doSomething();
// verify the results...
40. Testing bindings
Module.override to overcome problematic
bindings for testing:
Module testModule = Modules
.override(new AcmeModule())
.with(new AbstractModule() {
@Override protected void configure() {
bind(AuthChecker.class)
.toInstance(new StubAuthChecker());
}
});
Avoid overriding too many bindings
41. System tests
System (end-to-end) tests a must with DI
Discover runtime failures in tests or your users
will discover them for you
43. Migrating to DI
Rewiring an existing code base to use DI will
take time
Don't need to use everywhere (but consistency
is good)
44. Techniques for migrating to DI
Approaches
● Bottom-up, separate injectors for subparts
● Top-down, single injector pushed down
Often need to compromise on ideal patterns
● Multiple Injectors
● Directly reference Injector
● Constructors do work
45. Things that make DI difficult: deep
inheritance
class BaseService { }
class MobileService extends BaseService { }
class AndroidService extends MobileService {
@Inject AndroidService(Foo foo, Bar bar) {
super(foo, bar);
}
What if BaseService needs to start depending
on Baz? Prefer composition.
46. Things that make DI difficult: static
methods
class SomeClass {
static void process(Foo foo, Bar bar) {
processFoo(foo); ...
}
static void processFoo(Foo foo) { ... }
}
I want to bind Foo and start injecting it
elsewhere. How do I get to Guice?
50. Avoid @ImplementedBy
@ImplementedBy(MySqlUserStore.class)
interface UserStore { ... }
● Guice-ism, provided for convenience
● Interface should not have compile-time dep
on specific implementation!
● Can be overridden by explicit bindings
Guice-specific
51. Constructor injection promotes
thread-safe code
@ThreadSafe
class Greeter {
private final Greetings greetings;
private final User user;
@Inject
Greeter(Greetings greetings, User user) {
this.greetings = greetings;
this.user = user;
}
String getGreeting(GreetingId greetingId) { ... }
}
52. Minimize Custom Scopes
● Adds complexity
● Scopes mismatches
○ e.g. request scoped type into singleton scoped type
● More (wrong) choices for developers
○ Should I put this in scopeA, scopeB, scopeC, ...?
53. Testing providers
If your module contains non-trivial provider
methods, unit test them
class FooModuleTest {
void testBarWhenBarFlagDisabled() {
assertNull(
new FooModule().provideBar(
false /* bar flag */);
}
void testBarWhenBarFlagEnabled() { ... }
}