The document discusses functional programming in C# and how it can help control complexity. It defines functional programming as treating computations as mathematical functions without changing state. The document provides examples of copying photo files using both object-oriented and functional approaches in C#. The functional approach uses function composition and immutable data to avoid state changes and control flow, making the focus on specifying transformations rather than algorithms.
Learn how to leverage functional concepts of Partial Application and Function Composition for Dependency Injection in C#. This is to achieve Simplicity.
This is a Introduction to Object Oriented (OO) Concepts, Java Programming Language and leveraging Eclipse (IBM WebSphere) to develop Java applications.
This is based on JDK 1.4 concepts/features. A newer version maybe provided at a future date.
“Program to an interface, not an implementation” they[1] say …
But when IMyInterface foo = new IMyInterface() is not valid code … how are you supposed to achieve that ? The answer is Dependency Injection.
In this talk, we’ll talk about Dependency injection, what it is and what it is not. We’ll see how it is a valuable set of practices and patterns that help design maintainable software built on top of the SOLID object-oriented principles.
We’ll see how, when used properly, it delivers many benefits such as extensibility and testability … We’ll also cover some anti-patterns, ways of using Dependency Injection that can lead to code that is painful to understand and maintain
This talk is not about DI/IOC containers per se, but focuses on the core concepts of Dependency Injection. Those concepts are essential to understand how to use those “magic-looking” tools (if they are needed at all …)
This talk is not only for .NET developers. It will contain code examples written in C#, but should be understandable by developers with knowledge in other statically-typed object-oriented languages such as Java, Vb.NET, C++ …
Mahika Tutorials sharing Java Spring Framework Tutorials. You can visit our YouTube Page for Video Session also : https://www.youtube.com/c/mahikatutorials
Learn how to leverage functional concepts of Partial Application and Function Composition for Dependency Injection in C#. This is to achieve Simplicity.
This is a Introduction to Object Oriented (OO) Concepts, Java Programming Language and leveraging Eclipse (IBM WebSphere) to develop Java applications.
This is based on JDK 1.4 concepts/features. A newer version maybe provided at a future date.
“Program to an interface, not an implementation” they[1] say …
But when IMyInterface foo = new IMyInterface() is not valid code … how are you supposed to achieve that ? The answer is Dependency Injection.
In this talk, we’ll talk about Dependency injection, what it is and what it is not. We’ll see how it is a valuable set of practices and patterns that help design maintainable software built on top of the SOLID object-oriented principles.
We’ll see how, when used properly, it delivers many benefits such as extensibility and testability … We’ll also cover some anti-patterns, ways of using Dependency Injection that can lead to code that is painful to understand and maintain
This talk is not about DI/IOC containers per se, but focuses on the core concepts of Dependency Injection. Those concepts are essential to understand how to use those “magic-looking” tools (if they are needed at all …)
This talk is not only for .NET developers. It will contain code examples written in C#, but should be understandable by developers with knowledge in other statically-typed object-oriented languages such as Java, Vb.NET, C++ …
Mahika Tutorials sharing Java Spring Framework Tutorials. You can visit our YouTube Page for Video Session also : https://www.youtube.com/c/mahikatutorials
In building large scale web applications MVC seems like a good solution in the initial design phase. However after having built a few large apps that have multiple entry points (web, cli, api etc) you start to find that MVC breaks down. Start using Domain Driven Design.
Domain-driven design (DDD) is an approach to software development for complex needs by connecting the implementation to an evolving model.[1] The premise of domain-driven design is the following:
Placing the project's primary focus on the core domain and domain logic.
Basing complex designs on a model of the domain.
Initiating a creative collaboration between technical and domain experts to iteratively refine a conceptual model that addresses particular domain problems.
Have more questions?
Twitter: @wajrcs
Web: http://waqaralamgir.tk
Dependency injection is a technique to get rid of tightly coupled code.This session will give an idea about using DI in one's project with various patterns like constructor injection,setter injection and interface injection and demo of DI using Unity container.
FxContainer is the ONLY IoC Container written in JavaFX and specifically developed to be used in JavaFX applications. It is powerful, lightweight and 75K in footprint and open source.
Project website: https://fxobjects.dev.java.net
This has been presented in association with Robosepians for Java concepts. Basic concepts of Java including features, conditional statements, loop statements, arrays, string, primitive datatypes, essentials of Java including oops concepts, classes, objects, polymorphism, advance topics including packages, exception handling, multihtreading and network programming have been discussed.
Domain Driven Design and Hexagonal Architecture with RailsDeclan Whelan
You know that Domain Driven Design, Hexagonal Architecture, and the Single Responsibility Principle are important but it’s hard to know how to best apply them to Rails applications. Following the path of least-resistance will get you in trouble. In this session you will learn a way out of the “fat model, skinny controller” hell. You will leave with a roadmap to guide your design based on concepts from Domain Driven Design and Hexagonal Architecture.
A talk from Washington Canvas User Group about using the Common Cartridge and QTI formats to import content into Canvas. Code up at https://github.com/drlippman/canvas-scripts
An overview of how to consume 3rd party C++ libraries with CMake.
Methods covered include: find_package, pkg-config and writing a custom CMake Find Module.
In building large scale web applications MVC seems like a good solution in the initial design phase. However after having built a few large apps that have multiple entry points (web, cli, api etc) you start to find that MVC breaks down. Start using Domain Driven Design.
Domain-driven design (DDD) is an approach to software development for complex needs by connecting the implementation to an evolving model.[1] The premise of domain-driven design is the following:
Placing the project's primary focus on the core domain and domain logic.
Basing complex designs on a model of the domain.
Initiating a creative collaboration between technical and domain experts to iteratively refine a conceptual model that addresses particular domain problems.
Have more questions?
Twitter: @wajrcs
Web: http://waqaralamgir.tk
Dependency injection is a technique to get rid of tightly coupled code.This session will give an idea about using DI in one's project with various patterns like constructor injection,setter injection and interface injection and demo of DI using Unity container.
FxContainer is the ONLY IoC Container written in JavaFX and specifically developed to be used in JavaFX applications. It is powerful, lightweight and 75K in footprint and open source.
Project website: https://fxobjects.dev.java.net
This has been presented in association with Robosepians for Java concepts. Basic concepts of Java including features, conditional statements, loop statements, arrays, string, primitive datatypes, essentials of Java including oops concepts, classes, objects, polymorphism, advance topics including packages, exception handling, multihtreading and network programming have been discussed.
Domain Driven Design and Hexagonal Architecture with RailsDeclan Whelan
You know that Domain Driven Design, Hexagonal Architecture, and the Single Responsibility Principle are important but it’s hard to know how to best apply them to Rails applications. Following the path of least-resistance will get you in trouble. In this session you will learn a way out of the “fat model, skinny controller” hell. You will leave with a roadmap to guide your design based on concepts from Domain Driven Design and Hexagonal Architecture.
A talk from Washington Canvas User Group about using the Common Cartridge and QTI formats to import content into Canvas. Code up at https://github.com/drlippman/canvas-scripts
An overview of how to consume 3rd party C++ libraries with CMake.
Methods covered include: find_package, pkg-config and writing a custom CMake Find Module.
Mobile applications Development - Lecture 13
Local/Session Storage
WebSQL
IndexedDB
File System Access
This presentation has been developed in the context of the Mobile Applications Development course at the Computer Science Department of the University of L’Aquila (Italy).
http://www.di.univaq.it/malavolta
Tor Hovland: Taking a swim in the big data lakeAnalyticsConf
Are you curious about the possibilities enabled by Microsoft Azure and Cortana Analytics? Come and see how to handle data input from a large number of “Internet of Things” devices, how to work with all the data, how to scale big computations, how to make predictions, and how to build applications on top of it. There will be demos!
Rafał Korszuń: Security in Design of Cloud ApplicationsAnalyticsConf
W jaki sposób projektowanie aplikacji wpływa na bezpieczeństwo? Zasady projektowania aplikacji krytycznych ze względu na charakter przetrzymywanych danych. Omówienie ciekawszych przypadków wdrożenia lub nie securyty designu.
Tomasz Kopacz: Architektura i service fabric - jak budować aplikacje w paas v2AnalyticsConf
Service Fabric zmienia sposób myślenia o architekturze rozwiązań. Skalowanie warstwy UI jest proste. Ale - w przypadku logiki biznesowej, dotychczas można było albo budować szybko działające aplikacje typu "monolit" albo - skalowalne, n-warstwowe aplikacje oparte o kolejki (i podobne mechanizmy). Tu - dzięki zupełnie innemu podejściu do problemu - można te światy połączyć. Sesja dosyć techniczna!
Grzegorz Rycaj: Zdebuguj swoja prezentacjeAnalyticsConf
Każdy z nas staje czasem przed zadaniem pokazania światu swojego rozwiązania. No właśnie – jak zachęcić słuchacza do zainteresowania się naszym dziełem? Co sprawi, że zostaniemy obdarzeni zaufaniem oraz jakich najpopularniejszych błędów się wystrzegać? Na te i inne pytania odpowiem podczas mojej sesji!
Związany z technologiami Microsoft od początku kariery zawodowej, najpierw jako programista .NET, później architekt hurtowni danych. Zarządzał zespołami wdrażającymi rozwiązania oparte o MS BI m.in. w Grupie Energa, LOTOS, czy EuroStyl. Nastawiony na tworzenie rozwiązań praktycznych, zautomatyzowanych, prostych. MCSE: Business Intelligence
Sesja zapoznawcza na temat narzędzia Microsoftu do analizy danych – PowerBI. Koncepcja działania. Obsługiwane platformy. Wymagania. Źródła danych. Pulpit nawigacyjny i dashboardy oraz dostępne wizualizacje.
Paweł Kucharski: Oswajamy Słonia czyli po co nam HadoopAnalyticsConf
Wprowadzenie do Apache Hadoop i ekosystemu projektów z nim powiązanych w oparciu o nasze doświadczenia przechodzenia na Hadoop'a z tradycynego SQLa. Opowiem czym jest Hadoop i czym rózni się od relacyjnych baz danych, dlaczego zdecydowaliśmy się na Hadoop'a, co zyskalismy i jakie problemy napotkalismy pracując z Hadoop'em.
Michał Żyliński: Cortana dla niewtajemniczonychAnalyticsConf
Praktyczne wprowadzenie do nowoczesnych narzędzi analitycznych na przykładzie usług wchodzących w skład Microsoft Cortana Analytics Suite. Na konkretnych przykładach postaram się pokazać uczestnikom, jak przygotować się do przetwarzania dużej ilości danych. Jakie (darmowe i komercyjne) technologie znaleźć można na rynku? Jakie role i kompetencje przydadzą się wewnątrz organizacji? Jak dobrać właściwe narzędzia? Na czym warto skupić się samemu, a kiedy szukać pomocy na zewnątrz? Omówione zostaną również pierwsze komercyjne wdrożenia Cortany.
Shannon Holgate: Bending non-splittable data to harness distributed performanceAnalyticsConf
Performant XML processing in a distributed environment is a major challenge. We will dive into a financially viable pipeline to extract, load and transform XML on a platform of performance and flexibility. Hadoop, Spark and Impala will feature in this session about bringing commodity applications to a market of proprietary solutions.
What can we achieve by processing non-splittable data in a distributed fashion? I will talk about the motivation behind our research and show how we evolved a solution to cope with an ever changing environment. Stepping into the solution, I will show how you can strip away the restrictions of XML and load it onto Hadoop ready for analysis at scale in both an adhoc and modelling fashion.
Evaluating and evolving this solution is paramount. Load and throughput testing methods are highlighted along with guidance on tuning both the pipeline and the Hadoop platform to ensure your solution is optimised for a dynamic environment.
Włodek Bielski: Efektywne wdrożenie BI - z notatnika praktykaAnalyticsConf
Podczas sesji na rzeczywistych przykładach prześledzimy częste błędy popełniane podczas wdrożenia systemu BI. Rozważymy typowe sytuacje kryzysowe oraz sposoby radzenia z nimi. Przedyskutujemy też możliwości zastosowania formalnych procesów we wdrażaniu BI. Na koniec postaramy się określić zbiór najlepszych praktyk, mających zastosowanie w większości projektów.
Piotr Janczyk: Modele zachowań klientówAnalyticsConf
Czyli jak analizować dane w sprzedaży i marketingu?
Dynamiczna segmentacja Klientów
Podejście klasyczne, a może innowacyjne?
Segmentacja - odkrywanie nowych modeli w oparciu o dane.
Geolokalizacja
Analizy makro i mikroekonomiczne.
Czy adres o czymś świadczy?
Alex Kornilov: Building Big Data Company in Sports-Betting Industry - BETEGY ...AnalyticsConf
The session will cover following points from the experience of BETEGY founders:
- practical application of the Big Data in sports and betting;
- financing of the company (venture money vs. private money vs. strategic investors);
- product plans vs. market expansion;
- marketing techniques to promote Big Data company & product;
- challenges related to the product & industry;
- global vs. local company;
- other related topics.
Check out the webinar slides to learn more about how XfilesPro transforms Salesforce document management by leveraging its world-class applications. For more details, please connect with sales@xfilespro.com
If you want to watch the on-demand webinar, please click here: https://www.xfilespro.com/webinars/salesforce-document-management-2-0-smarter-faster-better/
Code reviews are vital for ensuring good code quality. They serve as one of our last lines of defense against bugs and subpar code reaching production.
Yet, they often turn into annoying tasks riddled with frustration, hostility, unclear feedback and lack of standards. How can we improve this crucial process?
In this session we will cover:
- The Art of Effective Code Reviews
- Streamlining the Review Process
- Elevating Reviews with Automated Tools
By the end of this presentation, you'll have the knowledge on how to organize and improve your code review proces
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
Software Engineering, Software Consulting, Tech Lead, Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Transaction, Spring MVC, OpenShift Cloud Platform, Kafka, REST, SOAP, LLD & HLD.
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Łukasz Chruściel
No one wants their application to drag like a car stuck in the slow lane! Yet it’s all too common to encounter bumpy, pothole-filled solutions that slow the speed of any application. Symfony apps are not an exception.
In this talk, I will take you for a spin around the performance racetrack. We’ll explore common pitfalls - those hidden potholes on your application that can cause unexpected slowdowns. Learn how to spot these performance bumps early, and more importantly, how to navigate around them to keep your application running at top speed.
We will focus in particular on tuning your engine at the application level, making the right adjustments to ensure that your system responds like a well-oiled, high-performance race car.
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.
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppGoogle
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-fusion-buddy-review
AI Fusion Buddy Review: Key Features
✅Create Stunning AI App Suite Fully Powered By Google's Latest AI technology, Gemini
✅Use Gemini to Build high-converting Converting Sales Video Scripts, ad copies, Trending Articles, blogs, etc.100% unique!
✅Create Ultra-HD graphics with a single keyword or phrase that commands 10x eyeballs!
✅Fully automated AI articles bulk generation!
✅Auto-post or schedule stunning AI content across all your accounts at once—WordPress, Facebook, LinkedIn, Blogger, and more.
✅With one keyword or URL, generate complete websites, landing pages, and more…
✅Automatically create & sell AI content, graphics, websites, landing pages, & all that gets you paid non-stop 24*7.
✅Pre-built High-Converting 100+ website Templates and 2000+ graphic templates logos, banners, and thumbnail images in Trending Niches.
✅Say goodbye to wasting time logging into multiple Chat GPT & AI Apps once & for all!
✅Save over $5000 per year and kick out dependency on third parties completely!
✅Brand New App: Not available anywhere else!
✅ Beginner-friendly!
✅ZERO upfront cost or any extra expenses
✅Risk-Free: 30-Day Money-Back Guarantee!
✅Commercial License included!
See My Other Reviews Article:
(1) AI Genie Review: https://sumonreview.com/ai-genie-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
#AIFusionBuddyReview,
#AIFusionBuddyFeatures,
#AIFusionBuddyPricing,
#AIFusionBuddyProsandCons,
#AIFusionBuddyTutorial,
#AIFusionBuddyUserExperience
#AIFusionBuddyforBeginners,
#AIFusionBuddyBenefits,
#AIFusionBuddyComparison,
#AIFusionBuddyInstallation,
#AIFusionBuddyRefundPolicy,
#AIFusionBuddyDemo,
#AIFusionBuddyMaintenanceFees,
#AIFusionBuddyNewbieFriendly,
#WhatIsAIFusionBuddy?,
#HowDoesAIFusionBuddyWorks
We describe the deployment and use of Globus Compute for remote computation. This content is aimed at researchers who wish to compute on remote resources using a unified programming interface, as well as system administrators who will deploy and operate Globus Compute services on their research computing infrastructure.
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxrickgrimesss22
Discover the essential features to incorporate in your Winzo clone app to boost business growth, enhance user engagement, and drive revenue. Learn how to create a compelling gaming experience that stands out in the competitive market.
E-commerce Application Development Company.pdfHornet Dynamics
Your business can reach new heights with our assistance as we design solutions that are specifically appropriate for your goals and vision. Our eCommerce application solutions can digitally coordinate all retail operations processes to meet the demands of the marketplace while maintaining business continuity.
OpenMetadata Community Meeting - 5th June 2024OpenMetadata
The OpenMetadata Community Meeting was held on June 5th, 2024. In this meeting, we discussed about the data quality capabilities that are integrated with the Incident Manager, providing a complete solution to handle your data observability needs. Watch the end-to-end demo of the data quality features.
* How to run your own data quality framework
* What is the performance impact of running data quality frameworks
* How to run the test cases in your own ETL pipelines
* How the Incident Manager is integrated
* Get notified with alerts when test cases fail
Watch the meeting recording here - https://www.youtube.com/watch?v=UbNOje0kf6E
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteGoogle
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-pilot-review/
AI Pilot Review: Key Features
✅Deploy AI expert bots in Any Niche With Just A Click
✅With one keyword, generate complete funnels, websites, landing pages, and more.
✅More than 85 AI features are included in the AI pilot.
✅No setup or configuration; use your voice (like Siri) to do whatever you want.
✅You Can Use AI Pilot To Create your version of AI Pilot And Charge People For It…
✅ZERO Manual Work With AI Pilot. Never write, Design, Or Code Again.
✅ZERO Limits On Features Or Usages
✅Use Our AI-powered Traffic To Get Hundreds Of Customers
✅No Complicated Setup: Get Up And Running In 2 Minutes
✅99.99% Up-Time Guaranteed
✅30 Days Money-Back Guarantee
✅ZERO Upfront Cost
See My Other Reviews Article:
(1) TubeTrivia AI Review: https://sumonreview.com/tubetrivia-ai-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
Zoom is a comprehensive platform designed to connect individuals and teams efficiently. With its user-friendly interface and powerful features, Zoom has become a go-to solution for virtual communication and collaboration. It offers a range of tools, including virtual meetings, team chat, VoIP phone systems, online whiteboards, and AI companions, to streamline workflows and enhance productivity.
2. Today’s Agenda
C# Functional Programming
Is It Worth An Effort? Maybe It Is
Controlling Complexity
Composition Function Composition
Programming Example
Copying Photo Files Implementation Variants
What Is Functional Programming?
Theoretical Perspective C# Programmer Perspective
4. What Is Functional Programming?
Wikipedia
Functional Programming is a programming paradigm,
a style of building the structure and elements of
computer programs, that treats computations as the
evaluation of mathematical functions and avoids
changing-state and mutable data. It is a declarative
programming paradigm, which means programming is
done with expressions.
5. Programming Paradigms
• Focus on describing how a program operates
• Programs described in terms of statements that change a program
state
• Structural (procedures as main actors) and object-oriented (objects as
main actors) programming styles fall into imperative paradigm
Imperative
• Focus on describing what a program should accomplish without
prescribing how to do it in terms of sequences of actions to be taken
• Programs expressed in terms of computation logic without describing
its control flow
• Functional (mathematical function as main actor) programming style
falls into declarative paradigm
Declarative
6. Multi-paradigm programming languages
Type inference (C# & F#)
Anonymous functions (C# & F#)
Language Integrated Query (C#
& F#)
Currying (F#)
Pattern matching (F#)
Lazy evaluation (F#)
Tail recursion (F#)
Immutability (F#)
Control statements (C#)
Classes (C#)
.NET framework (C# & F#)
Do notation (F#)
Declarative
Imperative
7. Object-Oriented vs. Functional Programming Style
Characteristic Object-oriented (imperative) approach Functional (declarative) approach
Programmer focus
How to perform tasks (algorithms) and
how to track changes in state.
What information is desired and what
transformations are required.
State changes Important. Localized and tightly controlled.
Order of execution Important. Low importance.
Primary flow control
Loops, conditionals, and function
(method) calls.
Function calls, including recursion.
Primary manipulation unit Instances of structures or classes.
Functions as first-class objects and data
collections.
9. Programming Example – problem statement
Copy photo files from the source folder (include subfolders) to the
destination folder (create subfolders as necessary). While copying
rename each file using pattern <base-name><sequence-number>.
Sequence numbers should preserve the order of date taken for each
photo. Additionally allow for each source photo file to create multiple
copies of the file in the target folder (useful for extending time-lapse
photography sequences).
10. Programming Example – object-oriented approach
foreach (sourceFile in sourceFilesSortedByPhotoDateTaken)
{
try
{
CreateTargetFolderPathIfNecessary
fileCopyCount = 0
while (fileCopyCount < PhotoFileCopyMultiplicationFactor)
{
MakeNewTargetFileName
CopySourceFileToTheTargetFolderUnderTheNewName
fileCopyCount += 1
}
}
catch
{
}
}
Programmer focus on how to perform
tasks (algorithms) and how to track
changes in state.
11. Programming Example – object-oriented approach
foreach (sourceFile in sourceFilesSortedByPhotoDateTaken)
{
try
{
CreateTargetFolderPathIfNecessary
fileCopyCount = 0
while (fileCopyCount < PhotoFileCopyMultiplicationFactor)
{
MakeNewTargetFileName
CopySourceFileToTheTargetFolderUnderTheNewName
fileCopyCount += 1
}
}
catch
{
}
}
var sourceFiles = .Visit (sourceFolder);
sourceFiles.Sort( .ByDateTaken);
foreach (var sourceFile in sourceFiles) {
try {
CreateTargetFolderPathIfNecessary
fileCopyCount = 0
while (fileCopyCount < PhotoFileCopyMultiplicationFactor) {
MakeNewTargetFileName
CopySourceFileToTheTargetFolderUnderTheNewName
fileCopyCount += 1
}
}
catch{
}
}
public static class FolderVisitor {
public static List<FileInfo> Visit(string rootFolder) {
return DoVisitFolder(rootFolder);
}
private static List<FileInfo> DoVisitFolder(string folder) {
var files = new List<FileInfo>();
var thisFolder = new DirectoryInfo(folder);
files.Add(thisFolder.EnumerateFiles());
var subFolders = thisFolder.EnumerateFolders();
foreach (var folder in subFolders) {
files.Add(DoVisitFolder(subfolder.FullName));
}
return files;
}
}
public static class Photo {
public static int ByDateTaken (FileInfo f1, FileInfo f2) {
if (f1 == null && f2 == null) {
return 0;
} else if (f1 == null) {
return -1;
} else if (f2 == null) {
return 1;
}
return Photo.DateTaken(f1).CompareTo(Photo.DateTaken(f1));
}
private static DateTime DateTaken(FileInfo f) {
DateTime dateTaken = DateTime.Now;
try {
using (var reader = ExifReader (f.FullName)) {
reader.GetTagValue<DateTime>(
ExifTags.DateTimeDigitized,
our dateTaken);
}
}
catch (IOException) {}
return dateTaken;
}
}
Add files from the
current folder.
Recursively add files
from subfolders.
Open source Exif Library
– read EXIF tag from the
photo file.
12. Programming Example – object-oriented approach
var sourceFiles = FolderVisitor.Visit (sourceFolder);
sourceFiles.Sort(Photo.ByDateTaken);
foreach (var sourceFile in sourceFiles) {
try {
CreateTargetFolderPathIfNecessary
fileCopyCount = 0
while (fileCopyCount < PhotoFileCopyMultiplicationFactor) {
MakeNewTargetFileName
CopySourceFileToTheTargetFolderUnderTheNewName
fileCopyCount += 1
}
}
catch{
}
}
public static class FolderHelper {
public static void MaterializeFolder(string root string path) {
var realtivePath = path.SubString(root.Length);
if (string.IsNullOrWhitespace(relativePath)) {
return;
}
var segments = relativePath.Split(new char[] {
Path.DirectorySeparatorChar,
Path.AltDirectorySeparatorChar
}, StringSplitOptions.RemoveEmptyEntries);
var workingPath = root;
foreach (var segment in segments) {
workingPath = Path.Combine(workingPath, segment);
if (!Directory.Exists(workingPath)) {
Directory.CreateDirectory(workingPath);
}
}
}
}
Create missing
folders.
13. Programming Example – object-oriented approach
var sourceFiles = FolderVisitor.Visit (sourceFolder);
sourceFiles.Sort(Photo.ByDateTaken);
foreach (var sourceFile in sourceFiles) {
try {
FolderHelper.MaterializeFolder(targetFolder, sourceFile.Directory.FullName);
fileCopyCount = 0
while (fileCopyCount < PhotoFileCopyMultiplicationFactor) {
MakeNewTargetFileName
CopySourceFileToTheTargetFolderUnderTheNewName
fileCopyCount += 1
}
}
catch{
}
}
public static class FolderHelper {
public static void CopyFile(string targetRoot,
FileInfo sourceFile, string fileNameBase, int sequenceNo) {
var newFileName = string.Format(„{0}{1}{2}”,
fileNameBase, sequenceNo,
Path.GetExtension(sourceFile.Name));
var realtivePath = sourceFile
.Directory.FullName
.SubString(targetRoot.Length);
var targetPath = Path.Combine(targetRoot, relativePath,
newFileName);
sourceFile.CopyTo(targetPath);
}
}
Make target file
name
Extract target
relative path.
Create target
absolute path.Copy source file to
the target folder.
14. Programming Example – object-oriented approach
var sourceFiles = FolderVisitor.Visit (sourceFolder);
sourceFiles.Sort(Photo.ByDateTaken);
foreach (var sourceFile in sourceFiles) {
try {
FolderHelper.MaterializeFolder(targetFolder, sourceFile.Directory.FullName);
fileCopyCount = 0
while (fileCopyCount < PhotoFileCopyMultiplicationFactor) {
FolderHelper.CopyFile(targetFolder, sourceFile,
newFileNameBase, sequenceNo);
fileCopyCount += 1;
sequenceNo += 1;
}
}
catch{
}
}
Make a list of source files.Sort source files by the
photo date taken.
Ensure target folder.
Make required file copies.
Update copying process state.
15. Programming Example – functional approach
• Make the list of source files
• Sort the source file list by picture date taken
• Make the list of pairs - source file and target
folder path
• Make the list of tuples – boolean flag
indicating sucessful file copy, source file,
copy operation status (destination path or
error message)
Programmer focus on what
information is desired and what
transformations are required.
16. Programming Example – functional approach
• Sort the source file list by picture date taken
• Make the list of pairs - source file and target
folder path
• Make the list of tuples – boolean flag
indicating sucessful file copy, source file,
copy operation status (destination path or
error message)
• Make the list of source filesvar sourceFiles = .Visit (sourceFolder);
type public FileVisitor() =
static member private folderFiles folderPath filter =
let emptyDirectory = List.Empty.AsEnumerable()
let dirInfo = new DirectoryInfo(folderPath)
try
dirInfo.EnumerateFiles(filter)
with
| :? ArgumentException -> emptyDirectory
| :? DirectoryNotFoundException -> emptyDirectory
| :? SecurityException -> emptyDirectory
| :? UnauthorizedAccessException -> emptyDirectory
static member private subFolders folderPath =
let dirInfo = new DirectoryInfo(folderPath)
let noSubFolders = List.Empty.AsEnumerable()
try
dirInfo.EnumerateDirectories()
with
| :? DirectoryNotFoundException -> noSubFolders
| :? SecurityException -> noSubFolders
| :? UnauthorizedAccessException -> noSubFolders
static member public Visit rootFolder fileNameFilter =
seq { yield! FileVisitor.folderFiles rootFolder fileNameFilter
for subFolder in FileVisitor.subFolders rootFolder do
yield! FileVisitor.Visit subFolder.FullName fileNameFilter }
A sequence is a logical series of elements all of one
type. Sequences are particularly useful when you have
a large, ordered collection of data but do not
necessarily expect to use all the elements. Individual
sequence elements are computed only as required, so
a sequence can provide better performance than a list
in situations in which not all the elements are used.
var sourceFiles = FolderVisitor.Visit (sourceFolder);IEnumerable<FileInfo>
17. Programming Example – functional approach
• Make the list of pairs - source file and target
folder path
• Make the list of tuples – boolean flag
indicating sucessful file copy, source file,
copy operation status (destination path or
error message)
var sourceFiles = FolderVisitor.Visit (sourceFolder);
• Sort the source file list by picture date taken
var sortedFiles = FolderVisitor.Visit (sourceFolder)
.OrderBy(Photo.DateTaken);
IEnumerable<FileInfo>
public static class Photo {
public static DateTime DateTaken(FileInfo f) {
DateTime dateTaken = DateTime.Now;
try {
using (var reader = ExifReader (f.FullName)) {
reader.GetTagValue<DateTime>(
ExifTags.DateTimeDigitized,
our dateTaken);
}
}
catch (IOException) {}
return dateTaken;
}
}
18. Programming Example – functional approach
• Make the list of pairs - source file and
target folder path
var sortedFiles = FolderVisitor.Visit (sourceFolder)
.OrderBy(Photo.DateTaken);
• Make the list of tuples – boolean flag
indicating sucessful file copy, source file,
copy operation status (destination path or
error message)
var copier =new (targetFolder, baseName, seqStart, noCopies);
var toBeCopiedFiles = FolderVisitor.Visit (sourceFolder)
.OrderBy(Photo.DateTaken)
.SelectMany(copier.MakeTargetPath);
public class FileCopier {
private readonly string _targetFolder;
private readonly string _baseName;
private readonly int _noOfCopies;
private int _sequenceNo;
public FileCopier(string targetFolder, string baseName, int seqStart, int noOfCopies) {
_targetFolder = targetFolder;
_baseName = baseName;
_noOfCopies = noOfCopies;
_sequenceNo = seqStart;
}
public IEnumerable<Tuple<FileInfo, string>> MakeTargetPath(FileInfo file) {
var result = new List<Tuple<FileInfo, string>();
for (var i = 0; i < _noOfCopies; ++i) {
var newFileName = string.Format(„{0}{1}{2}”, _baseName, _sequenceNo,
Path.GetExtension(file.Name));
var realtivePath = file.Directory.FullName.SubString(_targetFolder.Length);
var targetPath = Path.Combine(_targetFolder, relativePath, newFileName);
result.Add(new Tuple<FileInfo, string>(file, targetPath));
_sequenceNo += 1;
}
return result;
}
}
var copier =new FileCopier(targetFolder, baseName, seqStart, noCopies);
var toBeCopiedFiles = FolderVisitor.Visit (sourceFolder)
.OrderBy(Photo.DateTaken)
.SelectMany(copier.MakeTargetPath);
IEnumerable<Tuple<FileInfo, string>>
Projects each element of a sequence to an IEnumerable<T> and
flattens the resulting sequences into one sequence.
public static IEnumerable<TResult> SelectMany<TSource, TResult>(
this IEnumerable<TSource> source,
Func<TSource, IEnumerable<TResult>> selector
)
19. Programming Example – functional approach
• Make the list of tuples – boolean flag
indicating sucessful file copy, source file,
copy operation status (destination path or
error message)
var copier =new FileCopier(targetFolder, baseName, seqStart, noCopies);
var toBeCopiedFiles = FolderVisitor.Visit (sourceFolder)
.OrderBy(Photo.DateTaken)
.SelectMany(copier.MakeTargetPath);
var copier =new FileCopier(targetFolder, baseName, seqStart, noCopies);
var fileCopyStatus = FolderVisitor.Visit (sourceFolder)
.OrderBy(Photo.DateTaken)
.SelectMany(copier.MakeTargetPath)
.SelectMany(copier.CopyFile);
public class FileCopier {
private readonly string _targetFolder;
private readonly string _baseName;
private readonly int _noOfCopies;
private int _sequenceNo;
public FileCopier(string targetFolder, string baseName, int seqStart, int noOfCopies) {
_targetFolder = targetFolder;
_baseName = baseName;
_noOfCopies = noOfCopies;
_sequenceNo = seqStart;
}
public IEnumerable<Tuple<bool, FileInfo, string>> CopyFile(Tuple<FileInfo, string> file) {
var result = new List<Tuple<bool, FileInfo, string>();
try {
MaterializeFolder(_targetFolder, file.Item2);
file.Item1.CopyTo(file.Item2);
result.Add(new Tuple<bool, FileInfo, string>(true, file.Item1, file.Item2);
} catch (Exception ex) {
result.Add(new Tuple<bool, FileInfo, string>(false, file.Item1, ex.Message);
}
return result;
}
}
IEnumerable<Tuple<bool, FileInfo, string>>
20. Programming Example – functional approach
var copier =new FileCopier(targetFolder, baseName, seqStart, noCopies);
var fileCopyStatus = FolderVisitor.Visit (sourceFolder)
.OrderBy(Photo.DateTaken)
.SelectMany(copier.MakeTargetPath)
.SelectMany(copier.CopyFile);
var fileCopyObserver = new ();
fileCopyStatus.Subscribe (fileCopyObserver);
Console.WriteLine(fileCopyObserver.Summary());
public class FileCopyObserver : IObserver<Tuple<bool, FileInfo, string> {
private int _copiedFileCount;
private int _errorCount;
public string Summary() {
return string.Format(„Attempt to copy {0} files; {1} successful; {2} errors.”,
_copiedFileCount + _errorCount, _copiedFileCount, _errorCount);
}
public void OnCompleted() { }
public void OnError (Exception error) {}
public void OnNext(Tuple<bool, FileInfo, string> copyStatus) {
if (copyStatus.Item1) {
_copiedFileCoput += 1;
} else {
_errorCount += 1;
}
}
}
var fileCopyObserver = new FileCopyObserver();
fileCopyStatus.Subscribe (fileCopyObserver);
Console.WriteLine(fileCopyObserver.Summary());
System.Reactive.Linq
21. Programming Example – Object-Oriented vs Functional approach
var sourceFiles =
FolderVisitor.Visit (sourceFolder);
sourceFiles.Sort(Photo.ByDateTaken);
foreach (var sourceFile in sourceFiles) {
try {
FolderHelper.MaterializeFolder(targetFolder,
sourceFile.Directory.FullName);
fileCopyCount = 0
while (fileCopyCount < noOfCopies) {
FolderHelper.CopyFile(targetFolder,
sourceFile,
newFileNameBase,
sequenceNo);
fileCopyCount += 1;
sequenceNo += 1;
}
}
catch{
}
}
var copier = new FileCopier(targetFolder,
baseName,
seqStart,
noCopies);
var fileCopyStatus =
FolderVisitor.Visit (sourceFolder)
.OrderBy(Photo.DateTaken)
.SelectMany(copier.MakeTargetPath)
.SelectMany(copier.CopyFile);
var fileCopyObserver = new FileCopyObserver();
fileCopyStatus.Subscribe (fileCopyObserver);
Console.WriteLine(fileCopyObserver.Summary());
Control
statements,
state changes Function call
composition
Controlling Complexity By
23. Composition
Composition is the key to controlling complexity in software.
Expert programmers control the complexity of their designs by
combining primitive elements to form compound objects, they
abstract compound objects to form higher-level building blocks.
One form of composition, function composition, describes the
dependencies between function calls.
24. Function Composition
Function composition takes two functions and passes the result of
the second function as the argument of the first function –
effectively creating one function taking argument of the second
function and returning result of the first function.
public static Func<T, V> Compose<T, U, V>(this Func<U, V> f, Func<T, U> g)
{
return x => f(g(x));
}
Anonymous function (lambda) calling second function (g) with argument x and
passing its result as first function (f) argument, and returning the result of the
first function.
25. Function Composition
var r = f(g(x))
•Explicit
dependency
between f and g
var r = f.Compose(g)(x)
•Abstracted
dependency
between f and g
Abstract compound objects to form higher-level building blocks
26. Function Composition Laws
• Identity.Compose(f) = f
Left
identity
• f.Compose(Identity) = f
Right
identity
• f.Compose(g.Compose(h) =
(f.Compose(g)).Compose(h)Associative
public static T Identity<T>(this T value)
{
return value;
}
27. Function Composition – sometimes values are not enough
Generic (constructed) types package (amplify) values (integers,
strings, objects of class T)
The type IEnumerable<T> represents a lazily computed list of values
of type T
The type IEnumerable<T> packages (amplifies) the type T
28. Function Composition with IEnumerable<T>
public static Func<T, IEnumerable<V>> Compose<T, U, V>(
this Func<U, IEnumerable<V>> f,
Func<T, IEnumerable<U>> g)
{
return x => f(g(x));
}
Error – g(x) returns IEnumerable<U> while f takes U
We need to bind the result of g(x) with the function f. Binding will
iterate over a list returned by g(x) and pass individual list items to
the function f. The result of binding g(x) to the function f is a list of
results returned by the function f.
public static Func<T, IEnumerable<V>> Compose<T, U, V>(
this Func<U, IEnumerable<V>> f,
Func<T, IEnumerable<U>> g)
{
return x => g(x).Bind(f);
}
public static IEnumerable<V> Bind (
this IEnumerable<U> m,
Func<U, IEnumerable<V>> f)
public static IEnumerable<V> Bind (this IEnumerable<U> items, Func<U, IEnumerable<V>> f)
{
var result = new List<V>();
foreach (var item in items)
{
result.Add(f(item));
}
return result;
}
29. Function Composition with IEnumerable<T>
• Our Bind function allows the function f to use IEnumerable returned by the function g
• We need some function converting a type T to IEnumverable<T>
public static IEnumerable<T> Unit (this T value)
• Together the amplified type IEnumerable<T>,
the function Bind, and the function Unit enable
function composition with amplified values
A
type
A Unit
function
A Bind
function
Monad
Monads enable function
composition with amplified values
31. Creating a Monad
To define a particular monad, the writer
supplies the triple (a Type, a Unit function,
and a Bind function), thereby specyfying
the mechanics of the aplified values
34. C# Functional Programming
• Is it worth an effort?
• Maybe it is
• The Maybe monad is an example of a monadic
container type wrapping a value. The container
can either have a value or have missing value.
The Maybe monad is a better nullable type.
35. C# Functional Programming – Maybe monad
public class Maybe<T> {
public readonly static Maybe<T> Nothing = new Maybe<T>();
public bool IsNothing { get; private set; }
public T Just { get; private set; }
public Maybe() {
IsNothing = true;
Just = default(T);
}
public Maybe(T value) {
IsNothing = false;
Just = value;
}
public new string ToString() {
if (IsNothing) {
return "Nothing";
}
return Just.ToString();
}
}
Nothing represents all instances lacking a value.
Just the value if we have one.
We have the type. Now we need the Unit and
Bind functions to have the Maybe monad.
The Unit function which we call AsMaybe,
wraps a value.
The Bind function which we call SelectMany,
takes a Maybe instance and if there is a value
then it applies the delegate to the contained
value. Otherwise, it returns Nothing.
36. Maybe monad – Unit and Bind functions
public static class MaybeExtensions {
public static Maybe<T> AsMaybe<T> (this T value){
return new Maybe<T>(value);
}
public static Maybe<U> SelectMany<T, U>(this Maybe<T> m,
Func<T, Maybe<U>> doSemthingWith) {
if (m == null) {
return Maybe<U>.Nothing;
}
if (m.IsNothing) {
return Maybe<U>.Nothing;
}
try {
return doSomethingWith(m.Just);
}
catch (Exception) {
return Maybe<U>.Nothing;
}
}
}
The Unit function which we call AsMaybe, wraps
a value.
The Bind function which we call SelectMany,
takes a Maybe instance and if there is a value
then it applies the delegate to the contained
value. Otherwise, it returns Nothing.
The delegate takes the un-wrapped value of the
type T and returns wrapped (amplified) value of
the type U – we can bind another delegate to
ther result Maybe<U>.
Kompozycja, w sensie składania mniejszych elementów w większe konstrukcje jest kluczem do kontroli złożoności oprogramowania.
Zawodowcy kontrolują złożoność swoich projektów poprzez składanie prostych elementów w złożone obiekty. Abstrahowanie pozwala przekształcić złożone obiekty w klocki wyższego poziomu obdarzone funkcjonalnością umożliwiającą budowanie skomplikowanych systemów z dobrze zdefiniowanych składników (którymi łatwo się można posługiwać, bo są inteligetne tj. zawierają tyle funkcjonalności, że łatwo się jest składa w większą całość).
Jedną z form kompozycji (składania) jest złożenie funkcji.
Compose – funkcja zwracająca funkcję – co za pomysł! Na dodatek to extension method?! I to jeszcze generic! A dlaczego nie?
Associative - przechodni
Wróćmy do naszej funkcji Compose i zamieńmy parametr typu V na parametr typu IEnumerable<V>. Czy taka podmiana nadal umożliwia składanie funkcji?
Dobrze nam szło ale się skończyło. Jak zaradzić tej drobnej przeszkodzie?
Podsumujmy to co do tej pory uzyskaliśmy.
Bind umożliwia funkcji f konsumpcję wyniku zwracanego przez funkcję g
Przydałaby się funkcja, która wzmacnia dowolny typ T to IEnumerable<T> - nazwijmy ją Unit – pomińmy na moment jej implementację
Co daje nam ta trójka (IEnumerable<T>, Bind i Unit)? Możliwość złożenia funkcji biorących argumenty wzmocnionych typów i zwracających wyniki w wzmocnionych typach.
Taka trójka ma swoją nazwę – poznajcie Monadę – tajemniczy termin ze słownictwa programowania funkcjonalnego