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.
1. Rxjs provides a better way of handling asynchronous code through observables which are streams of values over time. Observables allow for cancellable, retryable operations and easy composition of different asynchronous sources.
2. Common Rxjs operators like map, filter, and flatMap allow transforming and combining observable streams. Operators make observables quite powerful for tasks like async logic, event handling, and API requests.
3. In Angular, observables are used extensively for tasks like HTTP requests, routing, and component communication. Key aspects are using async pipes for subscriptions and unsubscribing during lifecycle hooks. Rxjs greatly simplifies many common asynchronous patterns in Angular applications.
Rxjs provides a paradigm for dealing with asynchronous operations in a way that resembles synchronous code. It uses Observables to represent asynchronous data streams over time that can be composed using operators. This allows handling of events, asynchronous code, and other reactive sources in a declarative way. Key points are:
- Observables represent asynchronous data streams that can be subscribed to.
- Operators allow manipulating and transforming streams through methods like map, filter, switchMap.
- Schedulers allow controlling virtual time for testing asynchronous behavior.
- Promises represent single values while Observables represent continuous streams, making Observables more powerful for reactive programming.
- Cascading asynchronous calls can be modeled elegantly using switch
The web is evolving, we got it. One of the clear consequences is the complexity of our web apps (formerly known as ‘websites’). The conciseness of functional programming and its fundamentals got our attention, but we knew we could do better. And now we have the Reactive programming model, a functional and declarative way of dealing with big amounts of data.
In the center of it we have Observables: objects responsible to keep your application alive, reacting to any mutation your data may have, through any period of time. We’ll take a look on the concepts and also on the lib that implements it in Angular’s core: RxJS. Using the provided operators, we have great power on our hands, doing anything imaginable in a concise, declarative and easy-to-maintain way.
Watch out: observables are here to stay!
Utilizing Kotlin Flows in an Android application
Vijay will be revealing to you the kind of challenges we face while working with asynchronous data streams and how Kotlin Flows solves them.
Learn the latest tips, tricks, and tools for Android Development from our international team of Android Developers in Bangkok!
This document summarizes the new features and goals of RxJS version 5, which aims to improve the modularity, performance, debugging, and extensibility of the RxJS library. Key changes include making RxJS fully modular, improving performance by reducing allocations and call stack sizes, enhancing debugging with simpler operator implementations, and allowing better extensibility through subclassing Observables and maintaining Subject bi-directionality. Simpler unit tests using marble diagrams are also highlighted.
The document contains 6 programming tasks involving object-oriented concepts like classes, operators overloading, constructors etc. in C++. The tasks include modifying existing classes to add new functionality like operator overloading for arithmetic, relational and logical operators. New classes are also designed from scratch implementing various features like constructors, member functions and operator overloading. Main functions are written to test the classes.
This document contains code for a file sharing application that allows users to upload files to Amazon S3 storage and send download links to recipients via email. It includes code for connecting to MongoDB and S3 databases, handling file uploads with Multer, generating signed URLs with AWS, sending emails with Nodemailer, and building APIs with Express. The React code handles form inputs, file previews, and confirming upload status.
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.
1. Rxjs provides a better way of handling asynchronous code through observables which are streams of values over time. Observables allow for cancellable, retryable operations and easy composition of different asynchronous sources.
2. Common Rxjs operators like map, filter, and flatMap allow transforming and combining observable streams. Operators make observables quite powerful for tasks like async logic, event handling, and API requests.
3. In Angular, observables are used extensively for tasks like HTTP requests, routing, and component communication. Key aspects are using async pipes for subscriptions and unsubscribing during lifecycle hooks. Rxjs greatly simplifies many common asynchronous patterns in Angular applications.
Rxjs provides a paradigm for dealing with asynchronous operations in a way that resembles synchronous code. It uses Observables to represent asynchronous data streams over time that can be composed using operators. This allows handling of events, asynchronous code, and other reactive sources in a declarative way. Key points are:
- Observables represent asynchronous data streams that can be subscribed to.
- Operators allow manipulating and transforming streams through methods like map, filter, switchMap.
- Schedulers allow controlling virtual time for testing asynchronous behavior.
- Promises represent single values while Observables represent continuous streams, making Observables more powerful for reactive programming.
- Cascading asynchronous calls can be modeled elegantly using switch
The web is evolving, we got it. One of the clear consequences is the complexity of our web apps (formerly known as ‘websites’). The conciseness of functional programming and its fundamentals got our attention, but we knew we could do better. And now we have the Reactive programming model, a functional and declarative way of dealing with big amounts of data.
In the center of it we have Observables: objects responsible to keep your application alive, reacting to any mutation your data may have, through any period of time. We’ll take a look on the concepts and also on the lib that implements it in Angular’s core: RxJS. Using the provided operators, we have great power on our hands, doing anything imaginable in a concise, declarative and easy-to-maintain way.
Watch out: observables are here to stay!
Utilizing Kotlin Flows in an Android application
Vijay will be revealing to you the kind of challenges we face while working with asynchronous data streams and how Kotlin Flows solves them.
Learn the latest tips, tricks, and tools for Android Development from our international team of Android Developers in Bangkok!
This document summarizes the new features and goals of RxJS version 5, which aims to improve the modularity, performance, debugging, and extensibility of the RxJS library. Key changes include making RxJS fully modular, improving performance by reducing allocations and call stack sizes, enhancing debugging with simpler operator implementations, and allowing better extensibility through subclassing Observables and maintaining Subject bi-directionality. Simpler unit tests using marble diagrams are also highlighted.
The document contains 6 programming tasks involving object-oriented concepts like classes, operators overloading, constructors etc. in C++. The tasks include modifying existing classes to add new functionality like operator overloading for arithmetic, relational and logical operators. New classes are also designed from scratch implementing various features like constructors, member functions and operator overloading. Main functions are written to test the classes.
This document contains code for a file sharing application that allows users to upload files to Amazon S3 storage and send download links to recipients via email. It includes code for connecting to MongoDB and S3 databases, handling file uploads with Multer, generating signed URLs with AWS, sending emails with Nodemailer, and building APIs with Express. The React code handles form inputs, file previews, and confirming upload status.
Dpilot is a cloud based file transfer application that allows its user to upload data on cloud server and the receiver on the other hand can downlaod the data from the server. The Downlaod information is send to the receiver via mail service.
Other Features include:-
Secure Login system
Easy data Access
Lightening Fast Uploads and Downloads
Connect with your Facebook Or Gmail Account for easy access
The Ring programming language version 1.9 book - Part 90 of 210Mahmoud Samir Fayed
This document provides documentation on low-level functions in Ring that give access to the Ring virtual machine and runtime system. It describes functions for garbage collection, pointers, memory allocation, querying lists of functions, classes, packages, and more. It also covers functions for tracing, debugging, and interacting with the Ring VM.
Higher Order Components and Render PropsNitish Phanse
The document discusses higher order components (HOCs) in React. It begins by introducing HOCs as functions that take a component and return a new component. Various examples of HOCs are provided, including for purposes like code splitting, server side rendering, data tracking, and component logging. Key tips are provided, such as avoiding HOCs inside render and that refs are not passed through. The document also discusses how render props can be used as an alternative pattern to HOCs in some cases, and provides examples of common use cases like async data fetching and geolocation. It concludes by explaining that HOCs can also be created using a render prop approach.
Developing Applications with Microsoft Virtual Earthgoodfriday
This document discusses Microsoft's Virtual Earth mapping services. It provides an overview of the different Virtual Earth applications and APIs, including the AJAX API, MapPoint Web Service, and Live Search Maps. It also describes some key features of the Virtual Earth services like maps, geocoding, routing, and 3D environments. The document includes code samples for creating basic maps using the JavaScript API and adding shapes like polygons to the map. It also provides information on licensing and accessing the Virtual Earth APIs and services.
The document discusses the benefits of using RxJS observables over promises and events for managing asynchronous and reactive code in Angular applications. It explains key concepts like observers, subscriptions, operators, cold vs hot observables, and using RxJS with services and components. Example code is provided for creating observable data services to share data between components, composing asynchronous logic with operators, and best practices for managing subscriptions and preventing memory leaks. Overall, the document promotes a reactive programming style with RxJS for building maintainable and testable Angular applications.
Have ever heard that JavaScript is event-oriented? And that Node.js has a mainloop? Have you ever had issues with setTimeout, setInterval, setImmediate, nextTick order? This talk should help you with understanding deeply Node.js and Web event loop phases!
The document defines several protocols for algebraic structures like AdditiveGroup, Ring, and Field to represent types that can be added, multiplied, and have identities and inverses. It provides extensions for types like Int and Rational to conform to these protocols by implementing the required operations. The document also defines a EuclideanRing protocol to represent types that support Euclidean division and uses it to implement the gcd algorithm for polynomial types.
This document discusses Swift and transformations. It begins by introducing typed transforms in Swift using protocols like AngleProtocol. It defines operations like addition and subtraction for angle types that conform to AngleProtocol. It also defines conversions between radians and degrees. Next, it discusses 2D points using a Point2DProtocol. It implements operations like addition and subtraction for point types. It then discusses affine transforms for points using a CGAffineTransform type. It shows how to apply transforms to points and concatenate multiple transforms. Finally, it provides an example of drawing a house shape to a graphics context after applying various coordinate space transforms.
FS2 (previously called Scalaz-Stream) is a library that facilitates purely functional API to encode stream processing in a modular and composable manner.
Due to its functional abstraction around "streams" of data, FS2 enables isolating and delaying the side-effects until the streams are fully composed and assembled into its final execution context.
The main objectives of this talk are to get started with FS2, particularly with its functional approach to stream processing, and to dive into details of its semantics.
Intro to Reactive Thinking and RxJava 2JollyRogers5
Reactive Extensions (Rx) was first introduced by Microsoft in 2009 and has since been ported to most platforms and languages. It provides a way to model asynchronous data streams and events using Observables in a way that makes it easier to compose asynchronous and event-based programs. Some key advantages include simplifying asynchronous operations, surfacing errors sooner, and reducing bugs from state variables. However, the API is large so there is a steep learning curve. RxJava is an implementation of Rx for the JVM that allows pushing data instead of pulling it without worrying about threads. Common operators like map, filter, and flatMap allow transforming and combining Observable streams.
The Ring programming language version 1.3 book - Part 25 of 88Mahmoud Samir Fayed
This chapter summarizes various functions available in the Ring standard library (stdlib) for input/output, file handling, string manipulation, and mathematical operations. Some of the functions described include puts() and print() for output, getstring() and getnumber() for input, apppath() and justfilepath() for file paths, split() and splitmany() for string splitting, newlist() for multidimensional lists, capitalized() for capitalization, and mathematical functions like factorial(), fibonacci(), gcd(), and isprime() for prime checking. Many examples are provided to demonstrate the usage of these stdlib functions.
Quest 1 define a class batsman with the following specificationsrajkumari873
The document defines several Java classes with private and public members to model different real-world entities. This includes classes for batsmen (with code, name, stats, and average calculation), tests (with code, description, candidates, and center calculation), flights (with number, destination, distance, and fuel calculation), books (with number, title, price, purchase calculation), reports (with admission, name, marks, and average calculation), students (with admission, name, subjects, and total calculation), and telephone bills (with readings, calls, name, charges and calculation). Public member functions allow entering and displaying data, while private functions perform calculations.
The document provides tips on Java concurrency. It discusses using synchronized, volatile and java.util.concurrent classes like AtomicInteger for thread-safe operations on shared resources like account balances. Synchronized uses locks for mutual exclusion but volatile only ensures visibility, so atomic classes use Compare-And-Swap (CAS) operations for thread-safe updates without blocking.
The document discusses promises in asynchronous programming. It defines promises as containers that hold the result or error of an asynchronous operation. It describes common promise operators like then, catch, and race. It notes that promises allow for declarative code flow and easy handling of multiple errors in chained asynchronous operations. However, promises can add overhead and have misleading diagnostic messages for compile errors. It recommends promises for services, chained async operations, and operations with many possible errors.
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
JavaScript is single threaded, so understanding the async patterns available in the language is critical to creating maintainable NodeJS applications with good performance. In order to master “thinking in async”, we’ll explore the async patterns available in node and JavaScript including standard callbacks, promises, thunks/tasks, the new async/await, the upcoming asynchronous iteration features, streams, CSP and ES Observables.
The Ring programming language version 1.5.2 book - Part 75 of 181Mahmoud Samir Fayed
This document describes various functions in the Ring programming language for getting runtime information and controlling program execution. It provides functions to get lists of functions, classes, packages, memory scopes, call stacks, files, and more. It also describes functions for tracing program execution, handling errors, and evaluating code in different scopes. Examples are given to demonstrate how to use these functions.
You may have heard about reactive programming. Maybe even checked out RxSwift. But if you're not using it in your daily development, you're really missing out! Rx decimates the boilerplate code you'd have to write to do the same things in the traditional, imperative manner. And, in this day and age where the answer to supporting multiple platforms has given rise to using "lowest common denominator" cross-platform development technologies, Rx shifts the focus back to developers who want to stay true to their platform of choice, by unifying the patterns and operators used to write app code on any platform. Come see how reactive programming with RxSwift will change your life and make you richer than your wildest dreams.
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.
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.
Dpilot is a cloud based file transfer application that allows its user to upload data on cloud server and the receiver on the other hand can downlaod the data from the server. The Downlaod information is send to the receiver via mail service.
Other Features include:-
Secure Login system
Easy data Access
Lightening Fast Uploads and Downloads
Connect with your Facebook Or Gmail Account for easy access
The Ring programming language version 1.9 book - Part 90 of 210Mahmoud Samir Fayed
This document provides documentation on low-level functions in Ring that give access to the Ring virtual machine and runtime system. It describes functions for garbage collection, pointers, memory allocation, querying lists of functions, classes, packages, and more. It also covers functions for tracing, debugging, and interacting with the Ring VM.
Higher Order Components and Render PropsNitish Phanse
The document discusses higher order components (HOCs) in React. It begins by introducing HOCs as functions that take a component and return a new component. Various examples of HOCs are provided, including for purposes like code splitting, server side rendering, data tracking, and component logging. Key tips are provided, such as avoiding HOCs inside render and that refs are not passed through. The document also discusses how render props can be used as an alternative pattern to HOCs in some cases, and provides examples of common use cases like async data fetching and geolocation. It concludes by explaining that HOCs can also be created using a render prop approach.
Developing Applications with Microsoft Virtual Earthgoodfriday
This document discusses Microsoft's Virtual Earth mapping services. It provides an overview of the different Virtual Earth applications and APIs, including the AJAX API, MapPoint Web Service, and Live Search Maps. It also describes some key features of the Virtual Earth services like maps, geocoding, routing, and 3D environments. The document includes code samples for creating basic maps using the JavaScript API and adding shapes like polygons to the map. It also provides information on licensing and accessing the Virtual Earth APIs and services.
The document discusses the benefits of using RxJS observables over promises and events for managing asynchronous and reactive code in Angular applications. It explains key concepts like observers, subscriptions, operators, cold vs hot observables, and using RxJS with services and components. Example code is provided for creating observable data services to share data between components, composing asynchronous logic with operators, and best practices for managing subscriptions and preventing memory leaks. Overall, the document promotes a reactive programming style with RxJS for building maintainable and testable Angular applications.
Have ever heard that JavaScript is event-oriented? And that Node.js has a mainloop? Have you ever had issues with setTimeout, setInterval, setImmediate, nextTick order? This talk should help you with understanding deeply Node.js and Web event loop phases!
The document defines several protocols for algebraic structures like AdditiveGroup, Ring, and Field to represent types that can be added, multiplied, and have identities and inverses. It provides extensions for types like Int and Rational to conform to these protocols by implementing the required operations. The document also defines a EuclideanRing protocol to represent types that support Euclidean division and uses it to implement the gcd algorithm for polynomial types.
This document discusses Swift and transformations. It begins by introducing typed transforms in Swift using protocols like AngleProtocol. It defines operations like addition and subtraction for angle types that conform to AngleProtocol. It also defines conversions between radians and degrees. Next, it discusses 2D points using a Point2DProtocol. It implements operations like addition and subtraction for point types. It then discusses affine transforms for points using a CGAffineTransform type. It shows how to apply transforms to points and concatenate multiple transforms. Finally, it provides an example of drawing a house shape to a graphics context after applying various coordinate space transforms.
FS2 (previously called Scalaz-Stream) is a library that facilitates purely functional API to encode stream processing in a modular and composable manner.
Due to its functional abstraction around "streams" of data, FS2 enables isolating and delaying the side-effects until the streams are fully composed and assembled into its final execution context.
The main objectives of this talk are to get started with FS2, particularly with its functional approach to stream processing, and to dive into details of its semantics.
Intro to Reactive Thinking and RxJava 2JollyRogers5
Reactive Extensions (Rx) was first introduced by Microsoft in 2009 and has since been ported to most platforms and languages. It provides a way to model asynchronous data streams and events using Observables in a way that makes it easier to compose asynchronous and event-based programs. Some key advantages include simplifying asynchronous operations, surfacing errors sooner, and reducing bugs from state variables. However, the API is large so there is a steep learning curve. RxJava is an implementation of Rx for the JVM that allows pushing data instead of pulling it without worrying about threads. Common operators like map, filter, and flatMap allow transforming and combining Observable streams.
The Ring programming language version 1.3 book - Part 25 of 88Mahmoud Samir Fayed
This chapter summarizes various functions available in the Ring standard library (stdlib) for input/output, file handling, string manipulation, and mathematical operations. Some of the functions described include puts() and print() for output, getstring() and getnumber() for input, apppath() and justfilepath() for file paths, split() and splitmany() for string splitting, newlist() for multidimensional lists, capitalized() for capitalization, and mathematical functions like factorial(), fibonacci(), gcd(), and isprime() for prime checking. Many examples are provided to demonstrate the usage of these stdlib functions.
Quest 1 define a class batsman with the following specificationsrajkumari873
The document defines several Java classes with private and public members to model different real-world entities. This includes classes for batsmen (with code, name, stats, and average calculation), tests (with code, description, candidates, and center calculation), flights (with number, destination, distance, and fuel calculation), books (with number, title, price, purchase calculation), reports (with admission, name, marks, and average calculation), students (with admission, name, subjects, and total calculation), and telephone bills (with readings, calls, name, charges and calculation). Public member functions allow entering and displaying data, while private functions perform calculations.
The document provides tips on Java concurrency. It discusses using synchronized, volatile and java.util.concurrent classes like AtomicInteger for thread-safe operations on shared resources like account balances. Synchronized uses locks for mutual exclusion but volatile only ensures visibility, so atomic classes use Compare-And-Swap (CAS) operations for thread-safe updates without blocking.
The document discusses promises in asynchronous programming. It defines promises as containers that hold the result or error of an asynchronous operation. It describes common promise operators like then, catch, and race. It notes that promises allow for declarative code flow and easy handling of multiple errors in chained asynchronous operations. However, promises can add overhead and have misleading diagnostic messages for compile errors. It recommends promises for services, chained async operations, and operations with many possible errors.
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
JavaScript is single threaded, so understanding the async patterns available in the language is critical to creating maintainable NodeJS applications with good performance. In order to master “thinking in async”, we’ll explore the async patterns available in node and JavaScript including standard callbacks, promises, thunks/tasks, the new async/await, the upcoming asynchronous iteration features, streams, CSP and ES Observables.
The Ring programming language version 1.5.2 book - Part 75 of 181Mahmoud Samir Fayed
This document describes various functions in the Ring programming language for getting runtime information and controlling program execution. It provides functions to get lists of functions, classes, packages, memory scopes, call stacks, files, and more. It also describes functions for tracing program execution, handling errors, and evaluating code in different scopes. Examples are given to demonstrate how to use these functions.
You may have heard about reactive programming. Maybe even checked out RxSwift. But if you're not using it in your daily development, you're really missing out! Rx decimates the boilerplate code you'd have to write to do the same things in the traditional, imperative manner. And, in this day and age where the answer to supporting multiple platforms has given rise to using "lowest common denominator" cross-platform development technologies, Rx shifts the focus back to developers who want to stay true to their platform of choice, by unifying the patterns and operators used to write app code on any platform. Come see how reactive programming with RxSwift will change your life and make you richer than your wildest dreams.
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.
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.
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!
1. The code sample provided defines a simple Java class called HelloWorld with a main method that prints "Epic Fail".
2. The class contains a single public static void main method that takes an array of String arguments.
3. Within the main method it prints the text "Epic Fail" without any other processing or output.
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018Codemotion
Kotlin is a programming language developed by JetBrains that targets multiple platforms including the JVM, JavaScript, and native binaries. A year ago it has been adopted as an officially supported language for Android development. Kotlin offers clean and concise syntax, interoperability, both object-oriented and functional code constructs, and a lot of other cool features with little or no overhead. Let's find out together why developers love this language and how it helps them to be productive and have fun!
Generators in ECMAScript provide a way to write iterator functions using the yield keyword. This allows for writing functions that can be iterated over manually or used to create infinite streams. Generators also enable asynchronous programming using coroutines instead of callbacks. They allow for cooperative multitasking by starting multiple generator functions as "threads" that yield values in a nondeterministic order. Array comprehensions are also proposed as a shorthand for transforming arrays using generators.
Web2Day 2017 - Concilier DomainDriveDesign et API RESTNicolas Faugout
Talk au Tech2Day concernant l'approche RDD pour RestDrivenDomain qui nous permet chez Lucca de développer des domaines métiers exposés directement via des API REST.
Migrating from Flux to Redux. Why and how.Astrails
When I started to work with React back in Apr-2015 there were many libraries to manage the application flow. I decided to start with classical FB's Flux implementation to understand what's missed there. Eventually react-redux and redux solved most of issues I had with Flux. This talk is about practical aspects of migration from Flux to Redux.
This document provides an overview of Metro style apps and the C++ language features for building them. It compares the architecture and frameworks of Metro style apps to desktop apps. It then summarizes key C++ language features for Metro style development including reference types, memory management, pointers, events, generics and libraries. The document promotes C++ for building high performance Metro style apps and provides examples of key language concepts.
These are the slides of my talk at iOSCon 2017: https://skillsmatter.com/skillscasts/9549-architecting-alive-apps
Our apps are ever more alive. They interact with the rest of the world talking to backends and receiving notifications from them. They get their input from us and from other sensors. They are even aware of the location of the device they run in, or its position. But, in our IoT world, they may also detect presence in a room, get the temperature of it, or change the color of its lights.
Sadly enough, many of the apps available today with those capabilities have some architectural limitations:
Many of them are written in a way that is really dependent on a specific hardware.
Some restrict their use cases to whatever is provided by the hardware devices.
And almost all of them expect having a connection with the real device as the only way to test if they work properly.
However, we can also use an advanced architecture, like the Clean Architecture, to create a beautiful, scalable, testable, and robust application. Join Jorge and he will share with you how you can do it!
This is a "Code or it didn't happen" (TM) talk.
Taming Core Data by Arek Holko, MacoscopeMacoscope
The document discusses best practices for working with Core Data in iOS applications. It covers 9 steps: 1) setting up Core Data, 2) accessing the managed object context, 3) creating NSManagedObject subclasses, 4) creating fetch requests, 5) integrating networking, 6) using NSFetchedResultsController, 7) protocolizing models, 8) using immutable models, and 9) modularizing the code. The overall message is that Core Data code should be organized cleanly using small, single-purpose classes and protocols to improve testability, separation of concerns, and code reuse.
RxJava и Android. Плюсы, минусы, подводные камниStfalcon Meetups
Ярослав Герьятович
Android Engineer в компании Attendify . Спикер на UA Mobile'14 . Идеолог функционального и реактивного подхода в проектировании Android приложений.
The document discusses several common Java anti-patterns, including:
1) Approving a task by rejecting it in a method called "approve".
2) Avoiding the use of helper libraries to simplify tasks like file name parsing.
3) Using reflection when direct method calls would suffice.
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.
The document discusses using F# for programming. It provides examples of defining functions, using F# Interactive to test functions, and applying functions to arrays and collections using techniques like map, mapi and the pipe operator. It also discusses using type providers to access structured data from sources like Freebase to incorporate locations of airports into code with Intellisense support.
Kotlin is a concise, safe, and statically typed programming language that compiles to JVM bytecode and JavaScript. It focuses on interoperability with Java and solves many Java pitfalls. Kotlin removes verbosity like semicolons and replaces "extends" and "implement" with a colon. Functions are defined with the "fun" keyword and return types follow. Properties are treated like fields. Kotlin avoids null references through null safety features like the safe call operator and non-null assertion operator. When expressions replace switch statements. Extension functions can extend existing classes without subclassing.
The document describes an Android application that allows users to get the average position of a set of points. It uses OpenStreetMaps to display maps, collects location data from users, sends this data to a PostgreSQL database, calculates the average position from the records, and displays this on the map. The code connects the Android application to a dynamic web server and database to handle the processing and data storage.
This document discusses .NET garbage collection and provides examples to demonstrate how it works. It explains how the garbage collector manages memory on the managed heap, including generations and optimizations. It also demonstrates potential memory leaks and how to avoid them through proper cleanup of managed and unmanaged resources. Sample code is provided to show how to optimize performance by using the 'using' statement to dispose of objects automatically.
The document discusses async JavaScript features that are coming in ES7, including generators, promises, and async/await syntax. Generators allow functions to return multiple values and can be used to iterate over data asynchronously. Promises provide a better model for handling errors in async code compared to callbacks. Async/await syntax makes async code look more like synchronous blocking code for improved readability. These features can be used today via transpilation with Babel.
This document provides an overview of Retrofit, an open source library for Android and Java that allows making REST API calls in a simple and efficient manner. It discusses how to initialize Retrofit with an endpoint URL and adapter, define API methods using annotations, handle requests and responses both synchronously and asynchronously, and convert JSON responses to Java objects using Gson. Code samples are provided throughout to demonstrate common Retrofit tasks like making GET requests, handling API parameters and headers, and subscribing to asynchronous Observable responses.
Similar to SOLID principles in practice: the Clean Architecture - Devfest Emila Romagna (20)
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.
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!
Kotlin Delegates in practice - Kotlin community confFabio 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.
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.
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.
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
This document summarizes Fabio Collini's experience at Google I/O 2018, including sessions on artificial intelligence applications in medicine, self-driving cars, Google Assistant, and Google services, as well as demonstrations of Google Duplex, Google Maps, Google Lens, Android P, Kotlin, and Flutter. It notes there were more than 7000 attendees and mentions office hours and speeches.
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
This document provides an introduction to Retrofit 2 and RxJava 2. It discusses how Retrofit allows turning a REST API into a Java interface and how RxJava implements reactive programming with observable sequences. It demonstrates making synchronous and asynchronous HTTP requests with Retrofit and handling the "callback hell" problem with RxJava. Operators like map, flatMap, zip and concatMap are shown to transform and combine observables. The document emphasizes that RxJava contains over 400 methods and discusses additional RxJava concepts like error handling and threading.
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 document discusses Android Data Binding and the Model-View-ViewModel (MVVM) pattern. It covers the basics of data binding, using custom attributes with data binding, creating reusable UI components with data binding, implementing two-way data binding, and using data binding with RxJava and the MVVM pattern. The speaker presents code examples for setting up data binding in layout XML files and Java code, and binding data to views while ensuring automatic updates when the data changes.
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.
The document discusses a CodeLab on Android Wear. It includes an agenda for the CodeLab that covers creating a new project, adding libraries, layouts for smartwatches, communication with smartphones, and multi-fragment layouts. It provides code examples for creating WatchViewStubs, communicating between the mobile and wear modules using Teleport, and implementing a GridViewPager with fragments. The CodeLab aims to demonstrate building a simple survey app with Android Wear, including syncing data and updating the UI in response to changes.
Testable Android Apps using data binding and MVVMFabio Collini
The document discusses testing Android apps using data binding and MVVM. It covers setting up the MVVM architecture with a Note taking app example. It discusses using the Model-View-ViewModel pattern with data binding in Android. It also discusses how to write JVM unit tests for the ViewModel and mock dependencies by using stubs and spies.
This document provides an introduction to Retrofit and RxJava. It discusses:
1. How Retrofit turns REST APIs into Java interfaces and handles JSON conversion.
2. What RxJava is and how it allows for composing asynchronous and event-based programs using observable sequences.
3. Examples of making HTTP requests with Retrofit, including defining services, making synchronous and asynchronous requests, and using callbacks and RxJava.
4. Key RxJava concepts like Observables, operators like map, flatMap, and zip, and threading.
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).
Top 9 Trends in Cybersecurity for 2024.pptxdevvsandy
Security and risk management (SRM) leaders face disruptions on technological, organizational, and human fronts. Preparation and pragmatic execution are key for dealing with these disruptions and providing the right cybersecurity program.
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfVALiNTRY360
Salesforce Healthcare CRM, implemented by VALiNTRY360, revolutionizes patient management by enhancing patient engagement, streamlining administrative processes, and improving care coordination. Its advanced analytics, robust security, and seamless integration with telehealth services ensure that healthcare providers can deliver personalized, efficient, and secure patient care. By automating routine tasks and providing actionable insights, Salesforce Healthcare CRM enables healthcare providers to focus on delivering high-quality care, leading to better patient outcomes and higher satisfaction. VALiNTRY360's expertise ensures a tailored solution that meets the unique needs of any healthcare practice, from small clinics to large hospital systems.
For more info visit us https://valintry360.com/solutions/health-life-sciences
How Can Hiring A Mobile App Development Company Help Your Business Grow?ToXSL Technologies
ToXSL Technologies is an award-winning Mobile App Development Company in Dubai that helps businesses reshape their digital possibilities with custom app services. As a top app development company in Dubai, we offer highly engaging iOS & Android app solutions. https://rb.gy/necdnt
E-commerce Development Services- Hornet DynamicsHornet Dynamics
For any business hoping to succeed in the digital age, having a strong online presence is crucial. We offer Ecommerce Development Services that are customized according to your business requirements and client preferences, enabling you to create a dynamic, safe, and user-friendly online store.
Measures in SQL (SIGMOD 2024, Santiago, Chile)Julian Hyde
SQL has attained widespread adoption, but Business Intelligence tools still use their own higher level languages based upon a multidimensional paradigm. Composable calculations are what is missing from SQL, and we propose a new kind of column, called a measure, that attaches a calculation to a table. Like regular tables, tables with measures are composable and closed when used in queries.
SQL-with-measures has the power, conciseness and reusability of multidimensional languages but retains SQL semantics. Measure invocations can be expanded in place to simple, clear SQL.
To define the evaluation semantics for measures, we introduce context-sensitive expressions (a way to evaluate multidimensional expressions that is consistent with existing SQL semantics), a concept called evaluation context, and several operations for setting and modifying the evaluation context.
A talk at SIGMOD, June 9–15, 2024, Santiago, Chile
Authors: Julian Hyde (Google) and John Fremlin (Google)
https://doi.org/10.1145/3626246.3653374
Artificia Intellicence and XPath Extension FunctionsOctavian Nadolu
The purpose of this presentation is to provide an overview of how you can use AI from XSLT, XQuery, Schematron, or XML Refactoring operations, the potential benefits of using AI, and some of the challenges we face.
Microservice Teams - How the cloud changes the way we workSven Peters
A lot of technical challenges and complexity come with building a cloud-native and distributed architecture. The way we develop backend software has fundamentally changed in the last ten years. Managing a microservices architecture demands a lot of us to ensure observability and operational resiliency. But did you also change the way you run your development teams?
Sven will talk about Atlassian’s journey from a monolith to a multi-tenanted architecture and how it affected the way the engineering teams work. You will learn how we shifted to service ownership, moved to more autonomous teams (and its challenges), and established platform and enablement teams.
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...XfilesPro
Wondering how X-Sign gained popularity in a quick time span? This eSign functionality of XfilesPro DocuPrime has many advancements to offer for Salesforce users. Explore them now!
Most important New features of Oracle 23c for DBAs and Developers. You can get more idea from my youtube channel video from https://youtu.be/XvL5WtaC20A
Malibou Pitch Deck For Its €3M Seed Roundsjcobrien
French start-up Malibou raised a €3 million Seed Round to develop its payroll and human resources
management platform for VSEs and SMEs. The financing round was led by investors Breega, Y Combinator, and FCVC.
6. class WeatherUseCase(
private val locationManager: LocationManager,
private val repository: TemperatureRepository) {
suspend fun getCityData(): String = coroutineScope {
try {
val location = locationManager.getLastLocation()
val cities = async { locationManager.getCities(location) }
val temperature = repository.getTemperature(
location.lat, location.lon)
val city = cities.await().getOrElse(0) { "No city found" }
"$city n $temperature"
} catch (e: Exception) {
"Error retrieving data: ${e.message}"
}1
}2
}3
7. Coroutines
class WeatherUseCase(
private val locationManager: LocationManager,
private val repository: TemperatureRepository) {
suspend fun getCityData(): String = coroutineScope {
try {
val location = locationManager.getLastLocation()
val cities = async { locationManager.getCities(location) }
val temperature = repository.getTemperature(
location.lat, location.lon)
val city = cities.await().getOrElse(0) { "No city found" }
"$city n $temperature"
} catch (e: Exception) {
"Error retrieving data: ${e.message}"
}1
}2
}3
8. Dependency Injection
class WeatherUseCase(
private val locationManager: LocationManager,
private val repository: TemperatureRepository) {
suspend fun getCityData(): String = coroutineScope {
try {
val location = locationManager.getLastLocation()
val cities = async { locationManager.getCities(location) }
val temperature = repository.getTemperature(
location.lat, location.lon)
val city = cities.await().getOrElse(0) { "No city found" }
"$city n $temperature"
} catch (e: Exception) {
"Error retrieving data: ${e.message}"
}1
}2
}3
9. class WeatherUseCaseTest {
val locationManager: LocationManager = mockk()
val repository: TemperatureRepository = mockk()
val useCase = WeatherUseCase(locationManager, repository)
@Test
fun retrieveCityData() {
coEvery { locationManager.getLastLocation() } returns LOCATION
coEvery { locationManager.getCities(LOCATION) } returns
listOf(City("Firenze", "IT"))
coEvery { repository.getTemperature(LAT, LON) } returns
Temperature(10, 8, 20)
val cityData = runBlocking { useCase.getCityData() }
assert(cityData).isEqualTo("Firenze (IT) n 10º min 8º max 20º")
}1
}2
10. interface LocationManager {
suspend fun getLastLocation(): Location
suspend fun getCities(location: Location): List<City>
}6
class WeatherUseCase(
private val locationManager: LocationManager,
private val repository: TemperatureRepository) {
suspend fun getCityData(): String = coroutineScope {
try {
val location = locationManager.getLastLocation()
val cities = async { locationManager.getCities(location) }
val temperature = repository.getTemperature(
location.lat, location.lon)
val city = cities.await().getOrElse(0) { "No city found" }
"$city n $temperature"
} catch (e: Exception) {
"Error retrieving data: ${e.message}"
}1
}2
}3
interface TemperatureRepository {
suspend fun getTemperature(lat: Double, lon: Double): Temperature
}7
11. interface LocationManager {
suspend fun getLastLocation(): Location
suspend fun getCities(location: Location): List<City>
}6
class AndroidLocationManager(context: Context) : LocationManager {
private val fusedLocationClient: FusedLocationProviderClient =
LocationServices.getFusedLocationProviderClient(context)
private val geocoder = Geocoder(context, Locale.getDefault())
override suspend fun getLastLocation(): Location = suspendCoroutine {
//...
}E
override suspend fun getCities(location: Location): List<City> = suspendCoroutine {
//...
}E
}E
interface TemperatureRepository {
suspend fun getTemperature(lat: Double, lon: Double): Temperature
}7
class OpenWeatherTemperatureRepository(
private val api: WeatherApi
) : TemperatureRepository {
override suspend fun getTemperature(lat: Double, lon: Double): Temperature {
val forecastDeferred = api.forecast(lat, lon)
val weather = api.currentWeather(lat, lon).await()
val temperatures = forecastDeferred.await().list.map { it.main }
return Temperature(
weather.main.temp.toInt(),
temperatures.map { it.temp_min }.min()?.toInt(),
temperatures.map { it.temp_max }.max()?.toInt()
)D
}E
}F
12. class AndroidLocationManager(context: Context) : LocationManager {
private val fusedLocationClient: FusedLocationProviderClient =
LocationServices.getFusedLocationProviderClient(context)
private val geocoder = Geocoder(context, Locale.getDefault())
override suspend fun getLastLocation(): Location = suspendCoroutine {
//...
}E
override suspend fun getCities(location: Location): List<City> = suspendCoroutine {
//...
}E
}E
20. interface TemperatureRepository {
suspend fun getTemperature(lat: Double, lon: Double): Temperature
}7
interface LocationManager {
suspend fun getLastLocation(): Location
suspend fun getCities(location: Location): List<City>
}6
class AndroidLocationManager(context: Context) : LocationManager {
private val fusedLocationClient: FusedLocationProviderClient =
LocationServices.getFusedLocationProviderClient(context)
private val geocoder = Geocoder(context, Locale.getDefault())
override suspend fun getLastLocation(): Location = suspendCoroutine {
//...
}E
override suspend fun getCities(location: Location): List<City> = suspendCoroutine {
//...
}E
}E
class WeatherUseCase(
private val locationManager: LocationManager,
private val repository: TemperatureRepository) {
suspend fun getCityData(): String = coroutineScope {
try {
val location = locationManager.getLastLocation()
val cities = async { locationManager.getCities(location) }
val temperature = repository.getTemperature(
location.lat, location.lon)
val city = cities.await().getOrElse(0) { "No city found" }
"$city n $temperature"
} catch (e: Exception) {
"Error retrieving data: ${e.message}"
}1
}2
}3
interface WeatherApi {
@GET("weather?appid=$OPEN_WEATHER_APP_ID&units=metric")
fun currentWeather(@Query("lat") lat: Double, @Query("lon") lon: Double):
Deferred<TemperatureWrapper>
@GET("forecast?appid=$OPEN_WEATHER_APP_ID&units=metric")
fun forecast(@Query("lat") lat: Double, @Query("lon") lon: Double):
Deferred<Forecast>
}Z
class OpenWeatherTemperatureRepository(
private val api: WeatherApi
) : TemperatureRepository {
override suspend fun getTemperature(lat: Double, lon: Double): Temperature {
val forecastDeferred = api.forecast(lat, lon)
val weather = api.currentWeather(lat, lon).await()
val temperatures = forecastDeferred.await().list.map { it.main }
return Temperature(
weather.main.temp.toInt(),
temperatures.map { it.temp_min }.min()?.toInt(),
temperatures.map { it.temp_max }.max()?.toInt()
)D
}E
}F
21. class WeatherUseCase(
private val locationManager: LocationManager,
private val repository: TemperatureRepository) {
suspend fun getCityData(): String = coroutineScope {
try {
val location = locationManager.getLastLocation()
val cities = async { locationManager.getCities(location) }
val temperature = repository.getTemperature(
location.lat, location.lon)
val city = cities.await().getOrElse(0) { "No city found" }
"$city n $temperature"
} catch (e: Exception) {
"Error retrieving data: ${e.message}"
}1
}2
}3
class WeatherViewModel(app: Application) : AndroidViewModel(app) {
private val api = RetrofitFactory.createService<WeatherApi>()
private val weatherRepository = OpenWeatherTemperatureRepository(api)
private val positionManager = AndroidLocationManager(app)
private val useCase = WeatherUseCase(positionManager, weatherRepository)
val state = MutableLiveData<String>()
fun load() {
viewModelScope.launch {
val result = useCase.getCityData()
state.value = result
}O
}O
}O
class MainActivity : AppCompatActivity() {
//...
}
interface LocationManager {
suspend fun getLastLocation(): Location
suspend fun getCities(location: Location): List<City>
}6
class AndroidLocationManager(context: Context) : LocationManager {
private val fusedLocationClient: FusedLocationProviderClient =
LocationServices.getFusedLocationProviderClient(context)
private val geocoder = Geocoder(context, Locale.getDefault())
override suspend fun getLastLocation(): Location = suspendCoroutine {
//...
}E
override suspend fun getCities(location: Location): List<City> = suspendCoroutine {
//...
}E
}E
interface TemperatureRepository {
suspend fun getTemperature(lat: Double, lon: Double): Temperature
}7
interface WeatherApi {
@GET("weather?appid=$OPEN_WEATHER_APP_ID&units=metric")
fun currentWeather(@Query("lat") lat: Double, @Query("lon") lon: Double):
Deferred<TemperatureWrapper>
@GET("forecast?appid=$OPEN_WEATHER_APP_ID&units=metric")
fun forecast(@Query("lat") lat: Double, @Query("lon") lon: Double):
Deferred<Forecast>
}Z
class OpenWeatherTemperatureRepository(
private val api: WeatherApi
) : TemperatureRepository {
override suspend fun getTemperature(lat: Double, lon: Double): Temperature {
val forecastDeferred = api.forecast(lat, lon)
val weather = api.currentWeather(lat, lon).await()
val temperatures = forecastDeferred.await().list.map { it.main }
return Temperature(
weather.main.temp.toInt(),
temperatures.map { it.temp_min }.min()?.toInt(),
temperatures.map { it.temp_max }.max()?.toInt()
)D
}E
}F
22. class WeatherViewModel(app: Application) : AndroidViewModel(app) {
private val api = RetrofitFactory.createService<WeatherApi>()
private val weatherRepository = OpenWeatherTemperatureRepository(api)
private val positionManager = AndroidLocationManager(app)
private val useCase = WeatherUseCase(positionManager, weatherRepository)
val state = MutableLiveData<String>()
fun load() {
viewModelScope.launch {
val result = useCase.getCityData()
state.value = result
}O
}O
}O
23. app
api
domain
weather
location
interface WeatherApi {
@GET("weather?appid=$OPEN_WEATHER_APP_ID&units=metric")
fun currentWeather(@Query("lat") lat: Double, @Query("lon") lon: Double):
Deferred<TemperatureWrapper>
@GET("forecast?appid=$OPEN_WEATHER_APP_ID&units=metric")
fun forecast(@Query("lat") lat: Double, @Query("lon") lon: Double):
Deferred<Forecast>
}Z
class WeatherUseCase(
private val locationManager: LocationManager,
private val repository: TemperatureRepository) {
suspend fun getCityData(): String = coroutineScope {
try {
val location = locationManager.getLastLocation()
val cities = async { locationManager.getCities(location) }
val temperature = repository.getTemperature(
location.lat, location.lon)
val city = cities.await().getOrElse(0) { "No city found" }
"$city n $temperature"
} catch (e: Exception) {
"Error retrieving data: ${e.message}"
}1
}2
}3
class MainActivity : AppCompatActivity() {
//...
}
interface LocationManager {
suspend fun getLastLocation(): Location
suspend fun getCities(location: Location): List<City>
}6
class AndroidLocationManager(context: Context) : LocationManager {
private val fusedLocationClient: FusedLocationProviderClient =
LocationServices.getFusedLocationProviderClient(context)
private val geocoder = Geocoder(context, Locale.getDefault())
override suspend fun getLastLocation(): Location = suspendCoroutine {
//...
}E
override suspend fun getCities(location: Location): List<City> = suspendCoroutine {
//...
}E
}E
interface TemperatureRepository {
suspend fun getTemperature(lat: Double, lon: Double): Temperature
}7
class OpenWeatherTemperatureRepository(
private val api: WeatherApi
) : TemperatureRepository {
override suspend fun getTemperature(lat: Double, lon: Double): Temperature {
val forecastDeferred = api.forecast(lat, lon)
val weather = api.currentWeather(lat, lon).await()
val temperatures = forecastDeferred.await().list.map { it.main }
return Temperature(
weather.main.temp.toInt(),
temperatures.map { it.temp_min }.min()?.toInt(),
temperatures.map { it.temp_max }.max()?.toInt()
)D
}E
}F
class WeatherViewModel(app: Application) : AndroidViewModel(app) {
private val api = RetrofitFactory.createService<WeatherApi>()
private val weatherRepository = OpenWeatherTemperatureRepository(api)
private val positionManager = AndroidLocationManager(app)
private val useCase = WeatherUseCase(positionManager, weatherRepository)
val state = MutableLiveData<String>()
fun load() {
viewModelScope.launch {
val result = useCase.getCityData()
state.value = result
}O
}O
}O
25. Robert C. Martin Copyright (c) 2000 by Robert C. Martin. All Rights Reserved.
www.objectmentor.com 1
Design Principles and
Design Patterns
Robert C. Martin
www.objectmentor.com
What is software architecture? The answer is multitiered. At the highest level, there
are the architecture patterns that define the overall shape and structure of software
applications1
. Down a level is the architecture that is specifically related to the pur-
pose of the software application. Yet another level down resides the architecture of
the modules and their interconnections. This is the domain of design patterns2
, pack-
akges, components, and classes. It is this level that we will concern ourselves with in
this chapter.
Our scope in this chapter is quite limitted. There is much more to be said about the
principles and patterns that are exposed here. Interested readers are referred to
[Martin99].
Architecture and Dependencies
What goes wrong with software? The design of many software applications begins as
a vital image in the minds of its designers. At this stage it is clean, elegant, and com-
pelling. It has a simple beauty that makes the designers and implementers itch to see it
working. Some of these applications manage to maintain this purity of design through
the initial development and into the first release.
But then something begins to happen. The software starts to rot. At first it isn’t so
bad. An ugly wart here, a clumsy hack there, but the beauty of the design still shows
through. Yet, over time as the rotting continues, the ugly festering sores and boils
accumulate until they dominate the design of the application. The program becomes a
festering mass of code that the developers find increasingly hard to maintain. Eventu-
1. [Shaw96]
2. [GOF96]
36. open class Rectangle(
open var width: Int,
open var height: Int
) {
fun area() = width * height
}
class Square(size: Int) : Rectangle(size, size) {
override var width: Int = size
set(value) {
field = value
if (height != value)
height = value
}
override var height: Int = size
set(value) {
field = value
if (width != value)
width = value
}
}
66. Links
Demo Project
github.com/fabioCollini/CleanWeather
2000 - Robert C. Martin - Design Principles and Design Patterns
www.cvc.uab.es/shared/teach/a21291/temes/object_oriented_design/
materials_adicionals/principles_and_patterns.pdf
2005 - Robert C. Martin - The Principles of OOD
butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod
2012 - Robert C. Martin - The Clean Architecture
8thlight.com/blog/uncle-bob/2012/08/13/the-clean-architecture.html