The lazy delegate is probably the most famous Kotlin delegate, it’s easy to use and can be really useful. However delegation is a concept that can be used in many other ways in Kotlin. A delegate can be declared at two levels:
* a delegated property allows changing the way the property is managed
* an interface can be implemented delegating the methods to another object
In this talk we’ll see many practical examples to show how to leverage standard delegates and how to create new ones to improve the quality of our code and to avoid duplication.
Kotlin delegates in practice - Kotlin Everywhere StockholmFabio Collini
The lazy delegate is probably the most famous Kotlin delegate, it’s easy to use and can be really useful. However delegation is a concept that can be used in many other ways in Kotlin. A delegate can be declared at two levels:
* a delegated property allows changing the way the property is managed
* an interface can be implemented delegating the methods to another object
In this talk we’ll see many practical examples to show how to leverage standard delegates and how to create new ones to improve the quality of our code and to avoid duplication.
Compose is stable, it's time to integrate it into our apps! But it can be harder than expected and there are some questions to answer. Can the same architecture of a View-based app be reused or should we change it? Should the Compose code be aware of the architecture at all? And should the non UI code be changed to start using Compose? What can be replaced with a Composable, only the layouts or also something else?
Probably the best answer to all these questions is “it depends”, in this talk we’ll see some reasons and how to leverage Compose and the other tools to create a good architecture. Compose is more than just a UI framework and it can seem appealing to use it in a big portion of an app, a good architecture can be useful to limit this portion and use it only when necessary.
Using Kotlin coroutines it’s really easy to execute a task in a background thread and update the UI based on the result. Just enter the coroutine world using the launch method and then change thread using withContext. It’s even simpler if the task is an http call (thanks to coroutines support in retrofit) or a database query (thanks to Room). The final code is the same we’d use to execute synchronous code. But coroutines are more than just a tool to switch thread, we can use them to execute tasks in parallel. The code is still really easy to read but sometimes it can be difficult to write: we need to pay attention to many aspects (like nested scopes, exceptions and dispatchers). In this talk we’ll see how to leverage the coroutines library to manage parallelism, from the basic concepts to some advanced example.
Modularizing a project is never easy, a lot of files to move and the dependencies between them is not always what we expect. Then the Dagger configuration used in a single module project often doesn't scale well to a multi module project. Hilt is opinionated about the configuration to use (we don't need to argue anymore about using component dependencies or subcomponents!) and this configuration works perfectly even in a multi module project. In this talk we'll see first an introduction to Hilt and a comparison with Dagger to understand why it's easier to configure. Then we'll see how to leverage it in a multi module project (both in a standard layered architecture and in a Clean Architecture that uses the Dependency Inversion) to improve build speed and code testability. Spoiler alert: using sample apps that include a single feature in the app helps a lot!
Workshop Apps with ReactNative III:
- React Native short Recap
- The Native Side
- Building Native Modules (iOS & Android)
- Building Native Components (iOS & Android)
Presentado por ingenieros Alberto Irurueta y Enrique Oriol
Value types are at the core of Swift (seriously, mostly everything in the Swift standard library is a value type). But how do you avoid subclassing? That’s where the power of Protocol-Oriented programming comes in. Learn how to structure your code to never subclass (almost) again! Practical everyday examples and ideas for your own code base will be included.
Kotlin delegates in practice - Kotlin Everywhere StockholmFabio Collini
The lazy delegate is probably the most famous Kotlin delegate, it’s easy to use and can be really useful. However delegation is a concept that can be used in many other ways in Kotlin. A delegate can be declared at two levels:
* a delegated property allows changing the way the property is managed
* an interface can be implemented delegating the methods to another object
In this talk we’ll see many practical examples to show how to leverage standard delegates and how to create new ones to improve the quality of our code and to avoid duplication.
Compose is stable, it's time to integrate it into our apps! But it can be harder than expected and there are some questions to answer. Can the same architecture of a View-based app be reused or should we change it? Should the Compose code be aware of the architecture at all? And should the non UI code be changed to start using Compose? What can be replaced with a Composable, only the layouts or also something else?
Probably the best answer to all these questions is “it depends”, in this talk we’ll see some reasons and how to leverage Compose and the other tools to create a good architecture. Compose is more than just a UI framework and it can seem appealing to use it in a big portion of an app, a good architecture can be useful to limit this portion and use it only when necessary.
Using Kotlin coroutines it’s really easy to execute a task in a background thread and update the UI based on the result. Just enter the coroutine world using the launch method and then change thread using withContext. It’s even simpler if the task is an http call (thanks to coroutines support in retrofit) or a database query (thanks to Room). The final code is the same we’d use to execute synchronous code. But coroutines are more than just a tool to switch thread, we can use them to execute tasks in parallel. The code is still really easy to read but sometimes it can be difficult to write: we need to pay attention to many aspects (like nested scopes, exceptions and dispatchers). In this talk we’ll see how to leverage the coroutines library to manage parallelism, from the basic concepts to some advanced example.
Modularizing a project is never easy, a lot of files to move and the dependencies between them is not always what we expect. Then the Dagger configuration used in a single module project often doesn't scale well to a multi module project. Hilt is opinionated about the configuration to use (we don't need to argue anymore about using component dependencies or subcomponents!) and this configuration works perfectly even in a multi module project. In this talk we'll see first an introduction to Hilt and a comparison with Dagger to understand why it's easier to configure. Then we'll see how to leverage it in a multi module project (both in a standard layered architecture and in a Clean Architecture that uses the Dependency Inversion) to improve build speed and code testability. Spoiler alert: using sample apps that include a single feature in the app helps a lot!
Workshop Apps with ReactNative III:
- React Native short Recap
- The Native Side
- Building Native Modules (iOS & Android)
- Building Native Components (iOS & Android)
Presentado por ingenieros Alberto Irurueta y Enrique Oriol
Value types are at the core of Swift (seriously, mostly everything in the Swift standard library is a value type). But how do you avoid subclassing? That’s where the power of Protocol-Oriented programming comes in. Learn how to structure your code to never subclass (almost) again! Practical everyday examples and ideas for your own code base will be included.
Workshop Apps with ReactNative II:
- React Native short Recap
- Navigation in React Native Apps
- Tabs & Other Architectural Components
- Lists & Other Presentational Components
- OpenSource Important Components
Presentado por ingenieros Raúl Delgado y Marc Torrent
From object oriented to functional domain modelingCodemotion
"From object oriented to functional domain modeling" by Mario Fusco
Malgrado l'introduzione delle lambda, la gran parte degli sviluppatori Java non è ancora abituata agli idiomi della programmazione funzionale e quindi non è pronta a sfruttare a pieno le potenzialità di Java 8. In particolare non è ancora comune vedere dati e funzioni usate insieme quando si modella un dominio di business. Lo scopo del talk è mostrare come alcuni principi di programmazione funzionale quali l'impiego di oggetti e strutture dati immutabili, l'uso di funzioni senza side-effect e il loro reuso mediante composizione, possono anche essere validi strumenti di domain modelling.
Daggerate your code - Write your own annotation processorBartosz Kosarzycki
Length: 30 min
Annotations have become a trendy topic in the Android community. Almost all automation & boiler-plate code elimination is done through annotations - starting from DTOs description (google.GSON), REST libraries (Retrofit) to dependency injection (google.Dagger2). But what if you want to eliminate boiler-plate code in your custom project? Or maybe you're writing a library for other Android-developers and you want to easily initialize that library with annotations.
This presentation walks you through the basic theory behind annotation processing and tells you how to write the most elemental annotation processor. Starting from annotation-search in the source code, source-code analysis and lastly source-code generation. The latter is done with the use of Square's JavaPoet library.
Taming Core Data by Arek Holko, MacoscopeMacoscope
Core Data is a framework that you use to manage the model layer objects in your application. A framework that you use to build the persistence layer in your application.
Workshop JavaScript Testing. Frameworks. Client vs Server Testing. Jasmine. Chai. Nock. Sinon. Spec Runners: Karma. TDD. Code coverage. Building a testable JS app.
Presentado por ing: Raúl Delgado y Mario García
I am a student of Jahangirnagar University Dept. of CSE. This was my presentation on OOP Final Lab project. My project was Creating a Scientific Calculator. The presentation slide was made through google slide on ubuntu. So, there might be some difficulties in the slide.
"Reactive Programming with JavaScript" by Giorgio Natili
JavaScript is an asynchronous and almost single-thread language. Learning how to manage its asynchronous nature is perhaps the most important part of becoming an effective JavaScript programmer. Reactive programming tools in JavaScript provide a powerful way of “wrapping” the asynchronous callbacks into a more readable and maintainable code base. In this talk, I'll highlight the pros and cons of different reactive programming approaches and practices by demonstrating how to use Redux and Angular 2.x as the building blocks of a scalable architecture for your web app.
Workshop Apps with ReactNative II:
- React Native short Recap
- Navigation in React Native Apps
- Tabs & Other Architectural Components
- Lists & Other Presentational Components
- OpenSource Important Components
Presentado por ingenieros Raúl Delgado y Marc Torrent
From object oriented to functional domain modelingCodemotion
"From object oriented to functional domain modeling" by Mario Fusco
Malgrado l'introduzione delle lambda, la gran parte degli sviluppatori Java non è ancora abituata agli idiomi della programmazione funzionale e quindi non è pronta a sfruttare a pieno le potenzialità di Java 8. In particolare non è ancora comune vedere dati e funzioni usate insieme quando si modella un dominio di business. Lo scopo del talk è mostrare come alcuni principi di programmazione funzionale quali l'impiego di oggetti e strutture dati immutabili, l'uso di funzioni senza side-effect e il loro reuso mediante composizione, possono anche essere validi strumenti di domain modelling.
Daggerate your code - Write your own annotation processorBartosz Kosarzycki
Length: 30 min
Annotations have become a trendy topic in the Android community. Almost all automation & boiler-plate code elimination is done through annotations - starting from DTOs description (google.GSON), REST libraries (Retrofit) to dependency injection (google.Dagger2). But what if you want to eliminate boiler-plate code in your custom project? Or maybe you're writing a library for other Android-developers and you want to easily initialize that library with annotations.
This presentation walks you through the basic theory behind annotation processing and tells you how to write the most elemental annotation processor. Starting from annotation-search in the source code, source-code analysis and lastly source-code generation. The latter is done with the use of Square's JavaPoet library.
Taming Core Data by Arek Holko, MacoscopeMacoscope
Core Data is a framework that you use to manage the model layer objects in your application. A framework that you use to build the persistence layer in your application.
Workshop JavaScript Testing. Frameworks. Client vs Server Testing. Jasmine. Chai. Nock. Sinon. Spec Runners: Karma. TDD. Code coverage. Building a testable JS app.
Presentado por ing: Raúl Delgado y Mario García
I am a student of Jahangirnagar University Dept. of CSE. This was my presentation on OOP Final Lab project. My project was Creating a Scientific Calculator. The presentation slide was made through google slide on ubuntu. So, there might be some difficulties in the slide.
"Reactive Programming with JavaScript" by Giorgio Natili
JavaScript is an asynchronous and almost single-thread language. Learning how to manage its asynchronous nature is perhaps the most important part of becoming an effective JavaScript programmer. Reactive programming tools in JavaScript provide a powerful way of “wrapping” the asynchronous callbacks into a more readable and maintainable code base. In this talk, I'll highlight the pros and cons of different reactive programming approaches and practices by demonstrating how to use Redux and Angular 2.x as the building blocks of a scalable architecture for your web app.
While Google is adding Kotlin as an official Android language, we're also expanding our research on this language. It’s developed by JetBrains, and the fact that these are the people behind a suite of IDEs, such as IntelliJ and ReSharper, really shines through in Kotlin. It’s pragmatic and concise and makes coding a satisfying and efficient experience.
Although Kotlin compiles to both JavaScript and soon machine code, I’ll focus on its prime environment, the JVM.
Please see my presentation to learn more!
SpringOne Platform 2017
Sébastien Deleuze, Pivotal
"In this new talk, I will explain why Spring <3 Kotlin and how you can leverage Spring official support for Kotlin (in Framework, Boot, Data) to build your next Spring project more efficiently and with more pleasure.
I will describe gradually how you can transform your Spring Boot 1.0 Java + Javascript project with into a Spring Boot 2.0 pure Kotlin project running on top of the new WebFlux functional web framework."
EmptyCollectionException-java -- - Represents the situation in which.docxBlakeSGMHemmingss
EmptyCollectionException.java
/*
* Represents the situation in which a collection is empty.
*/
public class EmptyCollectionException extends RuntimeException
{
/* General class level objects */
/*
* Sets up this exception with an appropriate message.
* @param collection the name of the collection
*/
public EmptyCollectionException(String collection)
{
super("The " + collection + " is empty.");
}
}
PriorityNode.java
/*
* Represents a node in a linked list.
*/
public class PriorityNode<T>
{
/* General class level objects */
private PriorityNode<T> _next;
private T _element;
private int _priority;
private final int _MAX_PRIORITY = 100;
/*
* Creates an empty node with a given priority.
*/
public PriorityNode(T elem, int priority)
{
// TODO To be completed as a Programming Project
}
/*
* Creates a node storing the specified element with a default priority.
*
* @param elem element to be stored
*/
public PriorityNode(T elem)
{
// TODO To be completed as a Programming Project
}
/*
* Returns the node that follows this one.
*
* @return reference to next node
*/
public PriorityNode<T> getNext()
{
// TODO To be completed as a Programming Project
}
/*
* Sets the node that follows this one.
*
* @param node node to follow this one
*/
public void setNext(PriorityNode<T> node)
{
// TODO To be completed as a Programming Project
}
/*
* Returns the element stored in this node.
*
* @return element stored at the node
*/
public T getElement()
{
// TODO To be completed as a Programming Project
}
/*
* Returns the priority of this node.
*
* @return element priority the node
*/
public int getPriority()
{
// TODO To be completed as a Programming Project
}
/*
* Sets the element stored in this node.
*
* @param elem element to be stored at this node
*/
public void setElement(T elem)
{
// TODO To be completed as a Programming Project
}
/*
* optional toString() override.
*/
//public String toString()
//{
// // TODO To be completed as a Programming Project
//}
}
PriorityQueue.java
/*
* LinkedQueue represents a linked implementation of a queue.
*/
public class PriorityQueue<T> implements PriorityQueueADT<T>
{
/* General class level objects */
private int _count;
private PriorityNode<T> _head, _tail;
/*
* Constructor - Creates an empty queue.
*/
public PriorityQueue()
{
_count = 0;
_head = _tail = null;
}
/*
* Adds one element to the rear of this queue.
* Higher priorities are inserted closer to the front of the queue
* Items with the same priority are processed in normal queue order
*
* @param element the element to be added to the rear of the queue
* @param priority relative priority of the queue item
*/
public void enqueue(T element, int priority)
{
// TODO To be completed as a Programming Project
// add in-order insertion of the PriorityNode based on getPriority() value
// the higher the priority is the closer to head it gets
// equivalent priority is normal .
1. Suppose you want to implement an ADT in which you can insert valu.pdfforwardcom41
1. Suppose you want to implement an ADT in which you can insert values and retrieve or
remove the item with smallest value. (This ADT is called a priority queue). If forced to choose
between an array implementation and a linked list implementation, which would you choose and
why?
2. Write a recursive function that reads a list of integers from the console and prints them in
reverse order. The function should read until a negative number is encountered. You may only
use one local variable of type int. (So arrays or other aggregate data types are allowed.)
Example: 4 5 6 7 8 9 10 -1
10 9 8 7 6 5 4
3. Repeat question 2 using a local stack rather than recursion.
Solution
import java.util.Scanner;
class Value
{
String name;
int priority;
/** Constructor **/
public Value(String name, int priority)
{
this.name = name;
this.priority = priority;
}
/** toString() **/
public String toString()
{
return \"Value Name : \"+ name +\"\ Priority : \"+ priority;
}
}
/** Class PQ **/
class PQ
{
private Value[] SortedArray;
private int Size, Limit;
/** Constructor **/
public PQ(int Limit)
{
this.Limit = Limit + 1;
SortedArray = new Value[this.Limit];
Size = 0;
}
/** function to clear **/
public void clear()
{
SortedArray = new Value[Limit];
Size = 0;
}
/** function to check if empty **/
public boolean isEmpty()
{
return Size == 0;
}
/** function to check if full **/
public boolean isFull()
{
return Size == Limit - 1;
}
/** function to get Size **/
public int size()
{
return Size;
}
/** function to insert task **/
public void insert(String name, int priority)
{
Value Temp = new Value(name, priority);
SortedArray[++Size] = Temp;
int pos = Size;
while (pos != 1 && Temp.priority > SortedArray[pos/2].priority)
{
SortedArray[pos] = SortedArray[pos/2];
pos /=2;
}
SortedArray[pos] = Temp;
}
/** function to remove task **/
public Value remove()
{
int p, c;
Value item, temp;
if (isEmpty() )
{
System.out.println(\"array is empty\");
return null;
}
temp = SortedArray[1];
item = SortedArray[Size--];
p = 1;
c = 2;
while (c <= Size)
{
if (c < Size && SortedArray[c].priority >SortedArray[c + 1].priority)
c++;
if (temp.priority <=SortedArray[c].priority)
break;
SortedArray[p] = SortedArray[c];
p = c;
c *= 2;
}
SortedArray[p] = temp;
return item;
}
}
public class PQTest
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
PQ pq = new PQ(4 );
pq.insert(\"A\",1);
pq.insert(\"B\",2);
pq.insert(\"C\",10);
pq.insert(\"D\",94);
System.out.println(\"Value A(32),B(2),C(1),D(94) inserted\ \");
System.out.println(\"Value removed \"+pq.remove());
}
}
====================================================
Output:
akshay@akshay-Inspiron-3537:~/Chegg$ javac PQTest.java
akshay@akshay-Inspiron-3537:~/Chegg$ java PQTest
Value A(32),B(2),C(1),D(94) inserted
Value removed Value Name : A
Priority : 1
==========================================================
import java.util.*;
public class reverse {
public static void main(String[] args) {
Stack stack = new Stack();
System.
Dependency injection is a powerful technique allowing different parts of a system to collaborate with each other. Injection is the passing of a dependency (such as a service or database connection) to an object that would use it. This way, the object need not change because the outside service changed. This often also allows the object to be more easily tested by injecting a mock or stub service as the dependency.
For each task, submit your source java code file.(1) Objective Im.pdfdhavalbl38
For each task, submit your source java code file.
(1) Objective: Implement Link List
Write a class that maintains the scores for a game application. Implement the addition and
removal function to update the database. The gamescore.txt contains player’ name and score data
record fields separated by comma. For Removal function, uses the name field to select record to
remove the game score record.
Download – List.java, LList.java, Dlink.java, GameEntry.java, gamescore.txt
(a)Read gamescore.txt to initialize the Linked list in sorted order. (1 point)
(b)Provide Remove and Add function for user to update the sorted linked list. (1 point)
(2)Add a reverse function to the LList.java class to reverse the order of the linked list. (2 points).
---------------------------------------------------------------------------------------------------------------------
-----------------------------------------
//gamescore.txt
Mike,1105
Rob,750
Paul,720
Anna,660
Rose,590
Jack,510
--------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------
//DLink.java
/** Source code example for \"A Practical Introduction to Data
Structures and Algorithm Analysis, 3rd Edition (Java)\"
by Clifford A. Shaffer
Copyright 2008-2011 by Clifford A. Shaffer
*/
/** Doubly linked list node */
class DLink {
private E element; // Value for this node
private DLink next; // Pointer to next node in list
private DLink prev; // Pointer to previous node
/** Constructors */
DLink(E it, DLink p, DLink n)
{ element = it; prev = p; next = n; }
DLink(DLink p, DLink n) { prev = p; next = n; }
/** Get and set methods for the data members */
DLink next() { return next; }
DLink setNext(DLink nextval)
{ return next = nextval; }
DLink prev() { return prev; }
DLink setPrev(DLink prevval)
{ return prev = prevval; }
E element() { return element; }
E setElement(E it) { return element = it; }
}
--------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------
//GameEntry.java
public class GameEntry {
protected String name;
protected int score;
public GameEntry(String n, int s) {
name = n;
score = s;
}
public String getName() {return name;}
public int getScore() {return score;}
public String toString() {
return \"(\"+name+\",\"+score+\")\";
}
}
--------------------------------------------------------------------------------------------------------------------
----------------------------------
//List.java
/** Source code example for \"A Practical Introduction to Data
Structures and Algorithm Analysis, 3rd Edition (Java)\"
by Clifford A. Shaffer
Copyright 2008-2011 by Clifford A. Shaffer
*/
/** List ADT */
public interface List {
/** Remove all contents from the list, so it is once again
empty. Client is responsible for reclaiming storage
used by the list elements. */
p.
자프링(자바 + 스프링) 외길 12년차 서버 개발자가 코프링(코틀린 + 스프링)을 만난 후 코틀린의 특징과 스프링의 코틀린 지원을 알아가며 코프링 월드에서 살아남은 이야기…
코드 저장소: https://github.com/arawn/kotlin-support-in-spring
In this lab, we will write an application to store a deck of cards i.pdfcontact41
In this lab, we will write an application to store a deck of cards in a linked list, and then write
methods to sort and shuffle the deck.
Copy your completed LinkedList class from Lab 4 into the LinkedList.java file below.
Complete all methods of the Card class as described by the Javadoc comments. The class
contains both a suit and a rank. A suit is one of the categories into which the cards of a deck are
divided. The rank is the relative importance of the card within its suit.
Note that the Card constructor must convert any rank and suit letters to uppercase.
For the equals() method, be sure to follow the steps outlined in Lesson 4. How to implement the
compareTo() method is also covered in Lesson 4.
Note that you are not allowed to add any additional methods or member variables to this class or
you will not receive credit for this assignment.
Complete all methods of the CardApp class in the CardApp.java file as described by the Javadoc
comments.
You may add as many methods as you would like to this file, but are not allowed to add any
additional member variables.
The CardApp program must prompt for and allow the user to enter the name of any input file as
shown in the Example output below.
Implement the shuffle() method as specified in the comments for shuffle(). After you have
shuffled the deck of cards, write the result into a file named shuffled.txt.
Implement the sort() method using bubble sort from Lesson 4. First sort by suit in alphabetical
order and then by rank from 2 to A. The pseudocode for bubble sort is as follows:
After you have sorted the deck of cards, write the result to a file named sorted.txt.
The CardApp.java file also contains the main() method of the application. Use Develop mode to
test your CardApp code along with your Card and LinkedList code.
All input and output files must contain a list of cards, with each card stored on its own line. See
the example files cards1.txt and cards2.txt for example file formats.
[[[cards1.txt]]]
2H
3H
4H
5H
6H
7H
8H
9H
10H
JH
[[[cards2.txt]]]
AS
2S
3S
4S
5S
6S
7S
8S
9S
10S
JS
QS
KS
AC
2C
3C
4C
5C
6C
7C
8C
9C
10C
JC
QC
KC
AH
2H
3H
4H
5H
6H
7H
8H
9H
10H
JH
QH
KH
AD
2D
3D
4D
5D
6D
7D
8D
9D
10D
JD
QD
KD
[[[CardApp.java]]]
/**
* CardApp.java
* @author Your name
* @author Partner's name
* CIS 22C, Applied Lab 1
*/
public class CardApp {
private LinkedList list;
/**
* User interface prompts user, reads and writes files.
*/
public static void main(String[] args) {
}
/**
* Default constructor to initialize the deck
*/
public CardApp() {
}
/**
* Inserts a new Card into the deck
* @param card a playing Card
*/
public void addCard(Card card) {
}
/**
* Shuffles cards following this algorithm:
* First swaps first and last card
* Next, swaps every even card with the card 3
* nodes away from that card. Stops when it
* reaches the 3rd to last node
* Then, swaps ALL cards with the card that is
* 2 nodes away from it, starting at the 2nd card
* and stopping stopping at the 3rd to last node
*/
public vo.
Using Dagger in a Clean Architecture projectFabio Collini
Clean Architecture and app modularization are often used together to achieve a better code structure and a faster build time. But how can we use Dagger in an app structured in that way? Can we use subcomponents (with or without Dagger Android) or are component dependencies enough?
In this talk we’ll see how to leverage Dagger to organize the dependencies in a multi-module project with particular attention to testing and decoupling. The examples will be both in a standard layered architecture and in a Clean Architecture where the Dependency Inversion increases the overall structure but can complicate the Dagger code.
Solid principles in practice the clean architecture - Droidcon ItalyFabio Collini
The Clean Architecture has been formalized by Robert C. Martin in 2012, it's quite new even if it's based on the SOLID principles (presented for the first time in early 2000). The biggest benefit that we get using this architecture is the code testability, indeed it separates the application code from the code connected to external factor (that usually is more difficult to test).
In this talk we'll see a practical example of how to apply the SOLID principle, in particular, the dependency inversion.
SOLID principles in practice: the Clean Architecture - Devfest Emila RomagnaFabio Collini
The Clean Architecture has been formalized by Robert C. Martin in 2012, it's quite new even if it's based on the SOLID principles (presented for the first time in early 2000). The biggest benefit that we get using this architecture is the code testability, indeed it separates the application code from the code connected to external factor (that usually is more difficult to test).
In this talk we'll see a practical example of how to apply the SOLID principle, in particular, the dependency inversion.
SOLID principles in practice: the Clean ArchitectureFabio Collini
The Clean Architecture has been formalized by Robert C. Martin in 2012, it's quite new even if it's based on the SOLID principles (presented for the first time in early 2000). The biggest benefit that we get using this architecture is the code testability, indeed it separates the application code from the code connected to external factor (that usually is more difficult to test).
In this talk we'll see a practical example of how to apply the SOLID principle, in particular, the dependency inversion.
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf MilanFabio Collini
Kotlin is a first-class language for Android development since Google I/O 2017. And it’s here to stay!
Thanks to Android Studio it’s really easy to introduce Kotlin in an existing project, the configuration is trivial and then we can convert Java classes to Kotlin using a Alt+Shift+Cmd+K. But the new syntax is the just beginning, using Kotlin we can improve our code making it more readable and simpler to write.
In this talk we’ll see how to use some Kotlin features (for example data classes, collections, coroutines and delegates) to simplify Android development comparing the code with the equivalent “modern” Java code. It’s not fair to compare Kotlin code with plain Java 6 code so the Java examples will use lambdas and some external libraries like RxJava and AutoValue.
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinFabio Collini
It’s never easy to write async code but luckily there are many libraries to manage asynchronicity without adding too much complexity. In the last years RxJava and the other ReactiveX libraries have been very popular but lately there is a new way to manage async code in Kotlin: the coroutines. In this talk we’ll pros and cons of there two approaches and how to leverage them to simplify asynchronous code on Android.
Do they solve the same problem? Can we use them together? Which one can be used to write functional code? How can we use them effectively in Android development?
Spoiler alert: They are both great!
In this talk we’ll see how to solve common problems using RxJava or Coroutines, starting from basic concepts (for example the Retrofit support and how to cancel a task) to some more advanced (like threading, error management and how to combine multiple tasks).
All example of the talk are available on this repository:
https://github.com/fabioCollini/RxJavaVsCoroutines
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFabio Collini
Kotlin is a first-class language for Android development since Google I/O 2017. And it’s here to stay!
Thanks to Android Studio it’s really easy to introduce Kotlin in an existing project, the configuration is trivial and then we can convert Java classes to Kotlin using a Alt+Shift+Cmd+K. But the new syntax is the just beginning, using Kotlin we can improve our code making it more readable and simpler to write.
In this talk we’ll see how to use some Kotlin features (for example data classes, collections, coroutines and delegates) to simplify Android development comparing the code with the equivalent “modern” Java code. It’s not fair to compare Kotlin code with plain Java 6 code so the Java examples will use lambdas and some external libraries like RxJava and AutoValue.
From java to kotlin beyond alt+shift+cmd+kFabio Collini
Kotlin is a first-class language for Android development since Google I/O 2017. And it’s here to stay! Thanks to Android Studio it’s really easy to introduce Kotlin in an existing project, the configuration is trivial and then we can convert Java classes to Kotlin using a Alt+Shift+Cmd+K. But the new syntax is the just beginning, using Kotlin we can improve our code making it more readable and simpler to write. In this talk we’ll see how to use some Kotlin features (for example data classes, collections, coroutines and delegates) to simplify Android development comparing the code with the equivalent “modern” Java code. It’s not fair to compare Kotlin code with plain Java 6 code so the Java examples will use lambdas and some external libraries like RxJava and AutoValue.
Testing Android apps based on Dagger and RxJava Droidcon UKFabio Collini
Writing reliable tests is not easy for many reasons, especially when asynchronous code is involved. Some libraries can be used to create a testable architecture (for example Dagger and RxJava) and to simplify testing (Mockito, AssertJ and DaggerMock). In this talk you'll learn how to write JVM and Espresso tests with particular attention on how to replace real objects with mocks and how to test asynchronous RxJava code. In this talk, you will also explore:
how to take advantage of Mockito and other libraries to write good JVM and Espresso tests in both Java and Kotlin
how to use DaggerMock (an open source library available on github to avoid boilerplate code in tests
how to test asynchronous RxJava code using a JVM test
Testing Android apps based on Dagger and RxJavaFabio Collini
In this talk, you will learn:
how to take advantage of Mockito and other libraries to write good JVM and Espresso tests
how to use DaggerMock (an open source library available on github https://github.com/fabioCollini/DaggerMock) to avoid boilerplate code in tests
how to test asynchronous RxJava code using a JVM test
Writing reliable tests is not easy for many reasons, especially when asynchronous code is involved. Some libraries can be used to create a testable architecture (for example Dagger and RxJava) and to simplify testing (Mockito, AssertJ and DaggerMock). In this talk we’ll see how to write JVM and Espresso tests with particular attention on how to replace real objects with mocks and how to test asynchronous RxJava code.
Android Data Binding in action using MVVM pattern - droidconUKFabio Collini
The Data Binding framework was one of Google’s announcements at I/O 2015, it’s a big change in the code organization of an Android app. Some developers are sceptical about this framework but, if used in the “right way”, it’s very powerful and it allows to remove a lot of redundant boilerplate code from activities and fragments.
In this talk we’ll start from the Data Binding basic concepts and then we’ll see how to use it to improve the architecture of a typical Android application applying the Model View ViewModel pattern. Using this pattern you need to write less code to create an app that can be easily tested using JVM and instrumentation tests.
Data Binding in Action using MVVM patternFabio Collini
The Data Binding framework was one of Google’s announcements at I/O 2015, it’s a big change in the code organization of an Android app. Some developers are sceptical about this framework but, if used in the “right way”, it’s very powerful and it allows to remove a lot of redundant boilerplate code from activities and fragments.
In this talk we’ll start from the Data Binding basic concepts and then we’ll see how to use it to improve the architecture of a typical Android application applying the Model View ViewModel pattern. Using this pattern you need to write less code to create an app that can be easily tested using JVM and instrumentation tests.
What’s the best testing framework on Android? Espresso or Robotium? Robolectric or a plain JUnit test?
The reason why many developers don’t write tests is not due to the testing libraries but because of the low testability of the Android code.
In this talk we’ll see, thanks to a practical example, how to use Dependency Injection (using Dagger) and the Model View Presenter pattern to write a testable Android application.
The benefits of Clean Code are obvious: stable programs, better maintainability, finding bugs faster and easier upgrading of software. A lot of advices have been already written about Java clean code (first of all in Robert C. Martin book), what about Android? Are the same advices valid? Or the way we write code must be different because it's a mobile platform? Are there any best practices about resources and the other Android stuff? In this talk we'll see some practical examples of how take advantage of Java and Android framework to write clean code and keep a project manageable.
Librerie su Android: come non reinventare la ruota @ whymca 2012 Fabio Collini
Nei progetti J2EE siamo abituati a usare decine di librerie esterne, sia per classi di utilità sia per framework per strutturare meglio il codice. Come è messo Android da questo punto di vista? Nell'ultimo anno sono nati molti progetti interessanti (quasi tutti open source) che stanno portando un gran numero di librerie che permettono di non reinventare tutte le volte la ruota. In questo talk vedremo le principali librerie utilizzabili in un progetto Android evidenziando pregi e difetti di ognuna. Tramite una applicazione di esempio di librerie che permettono di evitare problemi di frammentazione (Android Compatibility Library e ActionBarSherlock), di quelle che mettono a disposizione nuovi componenti (GreedDroid, ViewPagerIndicator) e di quelle che cambiano radicalmente il modo di sviluppare una app (aQuery, Spring Mobile, AndroidAnnotations).
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamtakuyayamamoto1800
In this slide, we show the simulation example and the way to compile this solver.
In this solver, the Helmholtz equation can be solved by helmholtzFoam. Also, the Helmholtz equation with uniformly dispersed bubbles can be simulated by helmholtzBubbleFoam.
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...Juraj Vysvader
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I didn't get rich from it but it did have 63K downloads (powered possible tens of thousands of websites).
First Steps with Globus Compute Multi-User EndpointsGlobus
In this presentation we will share our experiences around getting started with the Globus Compute multi-user endpoint. Working with the Pharmacology group at the University of Auckland, we have previously written an application using Globus Compute that can offload computationally expensive steps in the researcher's workflows, which they wish to manage from their familiar Windows environments, onto the NeSI (New Zealand eScience Infrastructure) cluster. Some of the challenges we have encountered were that each researcher had to set up and manage their own single-user globus compute endpoint and that the workloads had varying resource requirements (CPUs, memory and wall time) between different runs. We hope that the multi-user endpoint will help to address these challenges and share an update on our progress here.
Into the Box Keynote Day 2: Unveiling amazing updates and announcements for modern CFML developers! Get ready for exciting releases and updates on Ortus tools and products. Stay tuned for cutting-edge innovations designed to boost your productivity.
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus
As part of the DOE Integrated Research Infrastructure (IRI) program, NERSC at Lawrence Berkeley National Lab and ALCF at Argonne National Lab are working closely with General Atomics on accelerating the computing requirements of the DIII-D experiment. As part of the work the team is investigating ways to speedup the time to solution for many different parts of the DIII-D workflow including how they run jobs on HPC systems. One of these routes is looking at Globus Compute as a way to replace the current method for managing tasks and we describe a brief proof of concept showing how Globus Compute could help to schedule jobs and be a tool to connect compute at different facilities.
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar
The European Union Agency for Law Enforcement Cooperation (Europol) has suffered an alleged data breach after a notorious threat actor claimed to have exfiltrated data from its systems. Infamous data leaker IntelBroker posted on the even more infamous BreachForums hacking forum, saying that Europol suffered a data breach this month.
The alleged breach affected Europol agencies CCSE, EC3, Europol Platform for Experts, Law Enforcement Forum, and SIRIUS. Infiltration of these entities can disrupt ongoing investigations and compromise sensitive intelligence shared among international law enforcement agencies.
However, this is neither the first nor the last activity of IntekBroker. We have compiled for you what happened in the last few days. To track such hacker activities on dark web sources like hacker forums, private Telegram channels, and other hidden platforms where cyber threats often originate, you can check SOCRadar’s Dark Web News.
Stay Informed on Threat Actors’ Activity on the Dark Web with SOCRadar!
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...informapgpstrackings
Keep tabs on your field staff effortlessly with Informap Technology Centre LLC. Real-time tracking, task assignment, and smart features for efficient management. Request a live demo today!
For more details, visit us : https://informapuae.com/field-staff-tracking/
How Recreation Management Software Can Streamline Your Operations.pptxwottaspaceseo
Recreation management software streamlines operations by automating key tasks such as scheduling, registration, and payment processing, reducing manual workload and errors. It provides centralized management of facilities, classes, and events, ensuring efficient resource allocation and facility usage. The software offers user-friendly online portals for easy access to bookings and program information, enhancing customer experience. Real-time reporting and data analytics deliver insights into attendance and preferences, aiding in strategic decision-making. Additionally, effective communication tools keep participants and staff informed with timely updates. Overall, recreation management software enhances efficiency, improves service delivery, and boosts customer satisfaction.
Developing Distributed High-performance Computing Capabilities of an Open Sci...Globus
COVID-19 had an unprecedented impact on scientific collaboration. The pandemic and its broad response from the scientific community has forged new relationships among public health practitioners, mathematical modelers, and scientific computing specialists, while revealing critical gaps in exploiting advanced computing systems to support urgent decision making. Informed by our team’s work in applying high-performance computing in support of public health decision makers during the COVID-19 pandemic, we present how Globus technologies are enabling the development of an open science platform for robust epidemic analysis, with the goal of collaborative, secure, distributed, on-demand, and fast time-to-solution analyses to support public health.
Your Digital Assistant.
Making complex approach simple. Straightforward process saves time. No more waiting to connect with people that matter to you. Safety first is not a cliché - Securely protect information in cloud storage to prevent any third party from accessing data.
Would you rather make your visitors feel burdened by making them wait? Or choose VizMan for a stress-free experience? VizMan is an automated visitor management system that works for any industries not limited to factories, societies, government institutes, and warehouses. A new age contactless way of logging information of visitors, employees, packages, and vehicles. VizMan is a digital logbook so it deters unnecessary use of paper or space since there is no requirement of bundles of registers that is left to collect dust in a corner of a room. Visitor’s essential details, helps in scheduling meetings for visitors and employees, and assists in supervising the attendance of the employees. With VizMan, visitors don’t need to wait for hours in long queues. VizMan handles visitors with the value they deserve because we know time is important to you.
Feasible Features
One Subscription, Four Modules – Admin, Employee, Receptionist, and Gatekeeper ensures confidentiality and prevents data from being manipulated
User Friendly – can be easily used on Android, iOS, and Web Interface
Multiple Accessibility – Log in through any device from any place at any time
One app for all industries – a Visitor Management System that works for any organisation.
Stress-free Sign-up
Visitor is registered and checked-in by the Receptionist
Host gets a notification, where they opt to Approve the meeting
Host notifies the Receptionist of the end of the meeting
Visitor is checked-out by the Receptionist
Host enters notes and remarks of the meeting
Customizable Components
Scheduling Meetings – Host can invite visitors for meetings and also approve, reject and reschedule meetings
Single/Bulk invites – Invitations can be sent individually to a visitor or collectively to many visitors
VIP Visitors – Additional security of data for VIP visitors to avoid misuse of information
Courier Management – Keeps a check on deliveries like commodities being delivered in and out of establishments
Alerts & Notifications – Get notified on SMS, email, and application
Parking Management – Manage availability of parking space
Individual log-in – Every user has their own log-in id
Visitor/Meeting Analytics – Evaluate notes and remarks of the meeting stored in the system
Visitor Management System is a secure and user friendly database manager that records, filters, tracks the visitors to your organization.
"Secure Your Premises with VizMan (VMS) – Get It Now"
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
Advanced Flow Concepts Every Developer Should KnowPeter Caitens
Tim Combridge from Sensible Giraffe and Salesforce Ben presents some important tips that all developers should know when dealing with Flows in Salesforce.
Globus Connect Server Deep Dive - GlobusWorld 2024Globus
We explore the Globus Connect Server (GCS) architecture and experiment with advanced configuration options and use cases. This content is targeted at system administrators who are familiar with GCS and currently operate—or are planning to operate—broader deployments at their institution.
Cyaniclab : Software Development Agency Portfolio.pdfCyanic lab
CyanicLab, an offshore custom software development company based in Sweden,India, Finland, is your go-to partner for startup development and innovative web design solutions. Our expert team specializes in crafting cutting-edge software tailored to meet the unique needs of startups and established enterprises alike. From conceptualization to execution, we offer comprehensive services including web and mobile app development, UI/UX design, and ongoing software maintenance. Ready to elevate your business? Contact CyanicLab today and let us propel your vision to success with our top-notch IT solutions.
Accelerate Enterprise Software Engineering with PlatformlessWSO2
Key takeaways:
Challenges of building platforms and the benefits of platformless.
Key principles of platformless, including API-first, cloud-native middleware, platform engineering, and developer experience.
How Choreo enables the platformless experience.
How key concepts like application architecture, domain-driven design, zero trust, and cell-based architecture are inherently a part of Choreo.
Demo of an end-to-end app built and deployed on Choreo.
Experience our free, in-depth three-part Tendenci Platform Corporate Membership Management workshop series! In Session 1 on May 14th, 2024, we began with an Introduction and Setup, mastering the configuration of your Corporate Membership Module settings to establish membership types, applications, and more. Then, on May 16th, 2024, in Session 2, we focused on binding individual members to a Corporate Membership and Corporate Reps, teaching you how to add individual members and assign Corporate Representatives to manage dues, renewals, and associated members. Finally, on May 28th, 2024, in Session 3, we covered questions and concerns, addressing any queries or issues you may have.
For more Tendenci AMS events, check out www.tendenci.com/events
2. “”
“The ratio of time spent reading (code)
versus writing is well over 10 to 1
(therefore) making it easy to read
makes it easier to write
Robert C. Martin
3. “”
“The Principle of Least Astonishment states that
the result of performing some operation should be
obvious, consistent, and predictable, based upon
the name of the operation and other clues
https://wiki.c2.com/?PrincipleOfLeastAstonishment
4. Kotlin code is readable
Data classes
Extension functions
Sealed classes
Coroutines
Delegates
…
6. public class MyEquivalentJavaClass {
private final String property = slowMethod();
public String getProperty() {
return property;
}5
}6
class MyClass {
val property = slowMethod()
}1
7. public class MyEquivalentJavaClass {
private String property = slowMethod();
public String getProperty() {
return property;
}
public void setProperty(String var1) {
this.property = var1;
}5
}6
class MyClass {
var property = slowMethod()
}1
9. public class MyEquivalentJavaClass {
public String getProperty() {
return slowMethod();
}5
}6
class MyClass {
val property get() = slowMethod()
}1
10. class MyClass {
val property = slowMethod()
}1
fun main() {
val obj = MyClass()
println(obj.property)A
println(obj.property)B
}2
11. class MyClass {
val property = slowMethod()
}1
fun main() {
println("starting")
val obj = MyClass()
println("obj created")
println(obj.property)A
println(obj.property)B
println("end")
}2
starting
slowMethod invoked
obj created
end
12. class MyClass {
val property get() = slowMethod()
}1
fun main() {
println("starting")
val obj = MyClass()
println("obj created")
println(obj.property)A
println(obj.property)B
println("end")
}2
starting
obj created
slowMethod invoked
slowMethod invoked
end
13. class MyClass {
val property by lazy {
slowMethod()
}3
}1
fun main() {
println("starting")
val obj = MyClass()
println("obj created")
println(obj.property)A
println(obj.property)B
println("end")
}2
starting
obj created
slowMethod invoked
end
16. public class MyEquivalentJavaClass {
private SimpleLazy lazy = new SimpleLazy(::slowMethod);
public String getProperty() {
return lazy.getValue();
}
}
17. internal object UNINITIALIZED_VALUE
class SimpleLazy<T>(private val initializer: () -> T) {
private var value: Any? = UNINITIALIZED_VALUE
fun getValue(): T {
if (value == UNINITIALIZED_VALUE) {
value = initializer()
}4
return value as T
}3
}2
18. /**
* Specifies how a Lazy instance synchronizes initialization among multiple threads.
*/
public enum class LazyThreadSafetyMode {
/**
* Locks are used to ensure that only a single thread can initialize the Lazy instance.
*/
SYNCHRONIZED,
/**
* Initializer function can be called several times on concurrent access to
* uninitialized Lazy instance value,
* but only the first returned value will be used as the value of Lazy instance.
*/
PUBLICATION,
/**
* No locks are used to synchronize an access to the Lazy instance value;
* if the instance is accessed from multiple threads, its behavior is undefined.
*
* This mode should not be used unless the Lazy instance is guaranteed never to
* be initialized from more than one thread.
*/
NONE
}
Default value
20. class MyClass {
suspend val property by lazy {
slowMethod()
}1
}2
suspend fun slowMethod() = withContext(IO) {
//...
}3
Modifier 'suspend' is not applicable to 'member property with delegate'
Suspend function 'slowMethod' should be called only from a coroutine or another suspend function
21.
22. class MyFragment : Fragment() {
private val appName by lazy { getString(R.string.app_name) }1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
println("Starting $appName...")
}2
}3
Lazy
23. class MyFragment : Fragment() {
private lateinit var appName: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
appName = getString(R.string.app_name)
println("Starting $appName...")
}4
}5
lateinit
24. class MyFragment : Fragment() {
private lateinit var appName: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
appName = getString(R.string.app_name)
println("Starting $appName...")
}4
}5
lateinit
class MyFragment : Fragment() {
private val appName by lazy { getString(R.string.app_name) }1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
println("Starting $appName...")
}2
}3
Lazy
25. class MyFragment : Fragment() {
private lateinit var appName: String
private lateinit var title: String
private lateinit var summary: String
private lateinit var text: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
appName = getString(R.string.app_name)
title = getString(R.string.title)
summary = getString(R.string.summary)
text = "$appNamen$titlen$summary"
println(text)
}4
}5
lateinit class MyFragment2 : Fragment() {
private val appName by lazy { getString(R.string.app_name) }
private val title by lazy { getString(R.string.title) }
private val summary by lazy { getString(R.string.summary) }
private val text by lazy { "$appNamen$titlen$summary" }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
println(text)
}2
}3
Lazy
28. /**
* Base interface that can be used for implementing property delegates of read-only properties.
*1
* This is provided only for convenience; you don't have to extend this interface
* as long as your property delegate has methods with the same signatures.
*2
* @param R the type of object which owns the delegated property.
* @param T the type of the property value.
*/
interface ReadOnlyProperty<in R, out T> {
/**
* Returns the value of the property for the given object.
* @param thisRef the object for which the value is requested.
* @param property the metadata for the property.
* @return the property value.
*/
operator fun getValue(thisRef: R, property: KProperty<*>): T
}3
29. class LogDelegate<T>(initialValue: T) : ReadOnlyProperty<Any, T> {
private var value: T = initialValue
override fun getValue(thisRef: Any, property: KProperty<*>): T {
println("get invoked on $thisRef.${property.name}")
return value
}1
}2
30. class LogDelegate<T>(initialValue: T) : ReadOnlyProperty<Any, T> {
private var value: T = initialValue
override fun getValue(thisRef: Any, property: KProperty<*>): T {
println("get invoked on $thisRef.${property.name}")
return value
}1
}2
class MyClass {
val property by LogDelegate("ABC")
}3
31. class LogDelegate<T>(initialValue: T) : ReadOnlyProperty<Any, T> {
private var value: T = initialValue
override fun getValue(thisRef: Any, property: KProperty<*>): T {
println("get invoked on $thisRef.${property.name}")
return value
}1
}2
class MyClass {
val property by LogDelegate("ABC")
}3
fun main() {
val obj = MyClass()
println(obj.property)
}4
get invoked on MyClass@87aac27.property
ABC
32. /**
* Base interface that can be used for implementing property delegates of read-write properties.
*
* This is provided only for convenience; you don't have to extend this interface
* as long as your property delegate has methods with the same signatures.
*
* @param R the type of object which owns the delegated property.
* @param T the type of the property value.
*/
interface ReadWriteProperty<in R, T> {
/**
* Returns the value of the property for the given object.
* @param thisRef the object for which the value is requested.
* @param property the metadata for the property.
* @return the property value.
*/
operator fun getValue(thisRef: R, property: KProperty<*>): T
/**
* Sets the value of the property for the given object.
* @param thisRef the object for which the value is requested.
* @param property the metadata for the property.
* @param value the value to set.
*/
operator fun setValue(thisRef: R, property: KProperty<*>, value: T)
}
33. class LogDelegate<T>(initialValue: T) : ReadWriteProperty<Any, T> {
private var value: T = initialValue
override fun getValue(thisRef: Any, property: KProperty<*>): T {
println("get invoked on $thisRef.${property.name}")
return value
}1
override fun setValue(thisRef: Any, property: KProperty<*>, value: T) {
println("set invoked on $thisRef.${property.name} with value $value")
this.value = value
}5
}2
class MyClass {
var property by LogDelegate("ABC")
}3
fun main() {
val obj = MyClass()
println(obj.property)
obj.property = "DEF"
println(obj.property)
}4
get invoked on MyClass@e9e54c2.property
ABC
set invoked on MyClass@e9e54c2.property with value DEF
get invoked on MyClass@e9e54c2.property
DEF
44. class TokenHolder(private val prefs: SharedPreferences) {
val token: String?
get() = prefs.getString(TOKEN,0null)1
val count: Int
get() = prefs.getInt(COUNT, 0)
fun saveToken(newToken: String) {
prefs.edit {
putString(TOKEN, newToken)
putInt(COUNT, count + 1)
}1
}2
companion object {
private const val TOKEN = "token"
private const val COUNT = "count"
}3
}4
45. class TokenHolder(private val prefs: SharedPreferences) {
var token by prefs.string(TOKEN)1
private3set
val count: Int
get() = prefs.getInt(COUNT, 0)
fun saveToken(newToken: String) {
prefs.edit {
putString(TOKEN, newToken)
putInt(COUNT, count + 1)
}1
}2
companion object {
private const val TOKEN = "token"
private const val COUNT = "count"
}3
}4
46. class TokenHolder(private val prefs: SharedPreferences) {
var token by prefs.string(TOKEN)1
private set
val count: Int
get() = prefs.getInt(COUNT, 0)
fun saveToken(newToken: String) {
token = newToken
prefs.edit {
putInt(COUNT, count + 1)
}1
}2
companion object {
private const val TOKEN = "token"
private const val COUNT = "count"
}3
}4
47. class TokenHolder(private val prefs: SharedPreferences) {
var token by prefs.string("token")1
private set
val count: Int
get() = prefs.getInt(COUNT, 0)2
fun saveToken(newToken: String) {
token = newToken
prefs.edit {
putInt(COUNT, count + 1)
}1
}2
companion object {
private const val COUNT = "count"
}3
}4
48. class TokenHolder(private val prefs: SharedPreferences) {
var token by prefs.string("token")
private set
var count by prefs.int(COUNT)2
private set
fun saveToken(newToken: String) {
token = newToken
prefs.edit {
putInt(COUNT, count + 1)
}1
}2
companion object {
private const val COUNT = "count"
}3
}4
49. class TokenHolder(private val prefs: SharedPreferences) {
var token by prefs.string("token")
private set
var count by prefs.int(COUNT)2
private set
fun saveToken(newToken: String) {
token = newToken
count++
}2
companion object {
private const val COUNT = "count"
}3
}4
50. class TokenHolder(private val prefs: SharedPreferences) {
var token by prefs.string("token")
private set
var count by prefs.int("count")2
private set
fun saveToken(newToken: String) {
token = newToken
count++
}2
}4
51. class TokenHolder(prefs: SharedPreferences) {
var token by prefs.string("token")
private set
var count by prefs.int("count")
private set
fun saveToken(newToken: String) {
token = newToken
count++
}2
}4
prefs.edit {
putInt("count", prefs.getInt("count", 0) + 1)
}
52. class DemoFragment : Fragment() {
private val component by lazy {
//...
}
private val viewModel by viewModelProvider {
component.myViewModel()
}
//...
}
https://proandroiddev.com/kotlin-delegates-in-android-development-part-2-2c15c11ff438
53. class DemoFragment : Fragment() {
private var param1: Int by argument()
private var param2: String by argument()
companion object {
fun newInstance(param1: Int, param2: String): DemoFragment =
DemoFragment().apply {
this.param1 = param1
this.param2 = param2
}
}
}
https://proandroiddev.com/kotlin-delegates-in-android-1ab0a715762d
55. object AnalyticsLib {
fun trackEvent(event: Map<String, Any?>) {
println(event)
}1
}2
fun main() {
val event = mapOf(
"name" to "myEvent",
"value" to 123
)3
AnalyticsLib.trackEvent(event)
}4
56. fun main() {
val event = mapOf(
"name" to "myEvent",
"value" to 123
)3
AnalyticsLib.trackEvent(event)
}4
57. const val NAME = "name"
const val VALUE = "value"
fun main() {
val event = mapOf(
NAME to "myEvent",
VALUE to 123
)3
AnalyticsLib.trackEvent(event)
}4
58. const val NAME = "name"
const val VALUE = "value"
fun main() {
val event = mapOf(
NAME to "myEvent",
VALUE to "this should be an Int :("
)3
AnalyticsLib.trackEvent(event)
}4
59. class MyEvent {
val map: MutableMap<String, Any?> = mutableMapOf()
var name: String by map
var value: Int by map
}1
fun main() {
val event = MyEvent().apply {
name = "myEvent"
value = 123
}2
AnalyticsLib.trackEvent(event.map)
}3
60. data class MyEvent(val name: String, val value: Int) {
val map = mapOf(
"name" to name,
"value" to value
)
}1
fun main() {
val event = MyEvent(
name = "myEvent",
value = 123
)2
AnalyticsLib.trackEvent(event.map)
}3
61. object AbTestLib {
fun readValues() = mapOf<String, Any?>(
"featureEnabled" to true,
"delay" to 1000
)1
}2
62. object AbTestLib {
fun readValues() = mapOf<String, Any?>(
"featureEnabled" to true,
"delay" to 1000
)1
}2
fun main() {
val values = AbTestLib.readValues()
println(values["featureEnabled"] as Boolean)
println(values["delay"] as Int)
}3
true
1000
63. data class AbValues(private val map: Map<String, Any?>) {
val featureEnabled: Boolean by map
val delay: Int by map
}1
fun main() {
val values = AbValues(AbTestLib.readValues())
println(values.featureEnabled)
println(values.delay)
}2
64. data class AbValues(private val map: Map<String, Any?>) {
val featureEnabled: Boolean by map
val delay: Int by map
}1
fun main() {
val values = AbValues(
mapOf<String, Any?>(
"featureEnabled" to "true",
"delay" to "1000"
)
)
println(values.featureEnabled)
println(values.delay)
}2
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean
65. class User {
var name: String by Delegates.observable("<no name>") { prop, old, new ->
println("$old -> $new")
}
}
class User {
var name: String by Delegates.vetoable("<no name>") { prop, old, new ->
new.startsWith("f")
}
}
ObservableVetoable
66. class MyClass {
var myIntVar: Int by notNull()
fun onCreate() {
myIntVar = calculateValue()
}
}
notNull
69. Composition
class Class1 {
fun doSomething() = 123
}
class Class2 {
private val wrapped = Class1()
fun doSomething() = wrapped.doSomething()
}
70. Delegation
interface Interface1 {
fun doSomething(): Int
}4
class Class1 : Interface1 {
override fun doSomething() = 123
}5
class Class2(private val wrapped: Class1 = Class1())
: Interface1 by wrapped
71. Delegation
interface Interface1 {
fun doSomething(): Int
}4
class Class1 : Interface1 {
override fun doSomething() = 123
}5
class Class2 : Interface1 by Class1()
11
72. Delegation
interface Interface1 {
fun doSomething(): Int
}4
class Class1 : Interface1 {
override fun doSomething() = 123
}5
class Class2 : Interface1 by Class1()
fun main() {
val obj = Class2()
println(obj.doSomething())
}m
Composition
class Class1 {
fun doSomething() = 123
}2
class Class2 {
private val wrapped = Class1()
fun doSomething() =
wrapped.doSomething()
}3
Inheritance
open class Class1 {
fun doSomething() = 123
}1
class Class2 : Class1()
73. interface HasMargin {
val marginBottom: Int
val marginTop: Int
val marginLeft: Int
val marginRight: Int
}1
class Style(
val backgroundColor: Int,
override val marginBottom: Int,
override val marginTop: Int,
override val marginLeft: Int,
override val marginRight: Int
) : HasMargin
class View(style: Style) : HasMargin by style {
fun draw() {
//...
}
}
74. [
{
"type": "student",
"name": "studentName",
"surname": "studentSurname",
"age": 20,
"university": "universityName"
},
{
//...
}
]
data class PersonJson(
val type: String,
val name: String,
val surname: String,
val age: Int,
val university: String?,
val company: String?
)
75. abstract class Person(
val name: String,
val surname: String,
val age: Int
)
class Student(
name: String,
surname: String,
age: Int,
val university: String
) : Person(name, surname, age)
class Worker(
name: String,
surname: String,
age: Int,
val company: String
) : Person(name, surname, age)
76. fun main() {
val json: List<PersonJson> = listOf(/* ... */)
val people = json.map {
if (it.type == "student")
Student(
it.name,
it.surname,
it.age,
it.university!!
)
else
Worker(
it.name,
it.surname,
it.age,
it.company!!
)
}
println(people.joinToString { "${it.name} ${it.surname}" })
}
77. abstract class Person(
val_name: String,
val_surname: String,
val_age: Int
)
class Student(
name: String,
surname: String,
age: Int,
val university: String
) : Person(name, surname, age)_
class Worker(
name: String,
surname: String,
age: Int,
val company: String
) : Person(name, surname, age)_
78. abstract class Person {
abstract val_name: String
abstract val_surname: String
abstract val_age: Int
}1
data class Student(
override val name: String,
override val surname: String,
override val age: Int,
val university: String
) : Person()_
data class Worker(
override val name: String,
override val surname: String,
override val age: Int,
val company: String
) : Person()_
79. interface Person {
val name: String
val surname: String
val age: Int
}1
data class Student(
override val name: String,
override val surname: String,
override val age: Int,
val university: String
) : Person
data class Worker(
override val name: String,
override val surname: String,
override val age: Int,
val company: String
) : Person
81. interface Person {
val name: String
val surname: String
val age: Int
}1
data class PersonData(
override val name: String,
override val surname: String,
override val age: Int
) : Person
82. data class Student(
override val name: String,
override val surname: String,
override val age: Int,
val university: String
) : Person
data class Worker(
override val name: String,
override val surname: String,
override val age: Int,
val company: String
) : Person
83. data class Student(
override val name: String,
override val surname: String,
override val age: Int,
val university: String
) : Person
data class Worker(
override val name: String,
override val surname: String,
override val age: Int,
val company: String
) : Person
data class Student(
val data: PersonData,
val university: String
) : Person by data
data class Worker(
val data: PersonData,
val company: String
) : Person by data
84. fun main() {
val json: List<PersonJson> = listOf(/* ... */)
val people = json.map {
val data = PersonData(
it.name,
it.surname,
it.age
)
if (it.type == "student")
Student(data, it.university!!)
else
Worker(data, it.company!!)
}
println(people.joinToString { "${it.name} ${it.surname}" })
}
85. interface Person {
val name: String
val surname: String
val age: Int
}
data class Student(
override val name: String,
override val surname: String,
override val age: Int,
val university: String
) : Person
data class Worker(
override val name: String,
override val surname: String,
override val age: Int,
val company: String
) : Person
fun main() {
val json: List<PersonJson> = listOf(/* ... */)
val people = json.map {
if (it.type == "student")
Student(
it.name,
it.surname,
it.age,
it.university!!
)
else
Worker(
it.name,
it.surname,
it.age,
it.company!!
)
}
println(people.joinToString { "${it.name} ${it.surname}" })
}
interface Person {
val name: String
val surname: String
val age: Int
}
data class PersonData(
override val name: String,
override val surname: String,
override val age: Int
) : Person
data class Student(
val data: PersonData,
val university: String
) : Person by data
data class Worker(
val data: PersonData,
val company: String
) : Person by data
fun main() {
val json: List<PersonJson> = listOf(/* ... */)
val people = json.map {
val data = PersonData(
it.name,
it.surname,
it.age
)
if (it.type == "student")
Student(data, it.university!!)
else
Worker(data, it.company!!)
}
println(people.joinToString { "${it.name} ${it.surname}" })
}
DelegationInheritance
86. interface Person {
val name: String
val surname: String
val age: Int
val address: String
val city: String
val zipCode: String
val nation: String
val telephoneNumber1: String
val telephoneNumber2: String
val telephoneNumber3: String
}
data class Student(
override val name: String,
override val surname: String,
override val age: Int,
val university: String,
override val address: String,
override val city: String,
override val zipCode: String,
override val nation: String,
override val telephoneNumber1: String,
override val telephoneNumber2: String,
override val telephoneNumber3: String
) : Person
data class Worker(
override val name: String,
override val surname: String,
override val age: Int,
val company: String,
override val address: String,
override val city: String,
override val zipCode: String,
override val nation: String,
override val telephoneNumber1: String,
override val telephoneNumber2: String,
override val telephoneNumber3: String
) : Person
data class Unemployed(
override val name: String,
override val surname: String,
override val age: Int,
override val address: String,
override val city: String,
override val zipCode: String,
override val nation: String,
override val telephoneNumber1: String,
override val telephoneNumber2: String,
override val telephoneNumber3: String
) : Person
fun main() {
val json: List<PersonJson> = listOf(/* ... */)
val people = json.map {
if (it.type == "student")
Student(
it.name,
it.surname,
it.age,
it.university!!,
it.address,
it.city,
it.zipCode,
it.nation,
it.telephoneNumber1,
it.telephoneNumber2,
it.telephoneNumber3
)
else if (it.type == "worker")
Worker(
it.name,
it.surname,
it.age,
it.company!!,
it.address,
it.city,
it.zipCode,
it.nation,
it.telephoneNumber1,
it.telephoneNumber2,
it.telephoneNumber3
)
else
Unemployed(
it.name,
it.surname,
it.age,
it.address,
it.city,
it.zipCode,
it.nation,
it.telephoneNumber1,
it.telephoneNumber2,
it.telephoneNumber3
)
}
println(people.joinToString { "${it.name} ${it.surname}" })
}
interface Person {
val name: String
val surname: String
val age: Int
val address: String
val city: String
val zipCode: String
val nation: String
val telephoneNumber1: String
val telephoneNumber2: String
val telephoneNumber3: String
}
data class PersonData(
override val name: String,
override val surname: String,
override val age: Int,
override val address: String,
override val city: String,
override val zipCode: String,
override val nation: String,
override val telephoneNumber1: String,
override val telephoneNumber2: String,
override val telephoneNumber3: String
) : Person
data class Student(
val data: PersonData,
val university: String
) : Person by data
data class Worker(
val data: PersonData,
val company: String
) : Person by data
data class Unemployed(
val data: PersonData
) : Person by data
fun main() {
val json: List<PersonJson> = listOf(/* ... */)
val people = json.map {
val data = PersonData(
it.name,
it.surname,
it.age,
it.address,
it.city,
it.zipCode,
it.nation,
it.telephoneNumber1,
it.telephoneNumber2,
it.telephoneNumber3
)
if (it.type == "student")
Student(data, it.university!!)
else if (it.type == "worker")
Worker(data, it.company!!)
else
Unemployed(data)
}
println(people.joinToString { "${it.name} ${it.surname}" })
}
DelegationInheritance
87. Wrappingup
“”
“The ratio of time spent reading (code)
versus writing is well over 10 to 1
(therefore) making it easy to read
makes it easier to write
Robert C. Martin
88. Wrappingup
“”
“The Principle of Least Astonishment states that
the result of performing some operation should be
obvious, consistent, and predictable, based upon
the name of the operation and other clues
https://wiki.c2.com/?PrincipleOfLeastAstonishment
90. Links&contacts
Simpler Kotlin class hierarchies using class delegation
proandroiddev.com/simpler-kotlin-class-hierarchies-using-class-delegation-35464106fed5
Kotlin delegates in Android development — Part 1
medium.com/hackernoon/kotlin-delegates-in-android-development-part-1-50346cf4aed7
Kotlin delegates in Android development — Part 2
proandroiddev.com/kotlin-delegates-in-android-development-part-2-2c15c11ff438
@fabioCollini
linkedin.com/in/fabiocollini
github.com/fabioCollini
medium.com/@fabioCollini