Functional Design and Architecture (Alexander Granin) (Z-Library)

Author: Alexander Granin

教育

No Description

📄 File Format: PDF
💾 File Size: 8.2 MB
54
Views
0
Downloads
0.00
Total Donations

📄 Text Preview (First 20 pages)

ℹ️

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

📄 Page 1
(This page has no text content)
📄 Page 2
Functional Design and Architecture EXAMPLES IN HASKELL Alexander Granin To comment go to liveBook Manning Shelter Island For more information on this and other Manning titles go to www.manning.com
📄 Page 3
Copyright For online information and ordering of these and other Manning books, please visit www.manning.com. The publisher offers discounts on these books when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: orders@manning.com ©2025 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps.
📄 Page 4
♾ Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid- free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. Manning Publications Co. 20 Baldwin Road Technical PO Box 761 Shelter Island, NY 11964 Development editor: Dustin Archibald Technical editor: Arnaud Bailly Review editor: Kishor Rit Production editor: Andy Marinkovich Copy editor: Lana Todorovic-Arndt Proofreader: Melody Dolab Technical proofreader: Thad Meyer Typesetter: Tamara Švelić Sabljić Cover designer: Marija Tudor ISBN: 9781617299612
📄 Page 5
dedication To my wife.
📄 Page 6
contents preface acknowledgments about this book about the author about the cover illustration Part 1. Introduction to functional declarative design 1 What is software design? 1.1 Why functional programming? 1.2 Software design Requirements, goals, and simplicity 1.3 Essential and accidental complexity Low coupling, high cohesion Interfaces, inversion of control, and modularity Functional design 1.4 Design in mainstream paradigms Imperative design Object-oriented design Object-oriented design principles 1.5 Software design in functional languages Immutability, purity, and determinism Strong static type systems Patterns and idioms Monads
📄 Page 7
2 The basics of functional declarative design 2.1 The engineering approach Software architecture classification Design tools and abstractions Top-down iterative development process Collecting requirements Requirements in mind maps 2.2 Application architecture Architecture layers Embedded domain-specific languages Modularization of applications Part 2. Minimum viable product 3 Drafting the MVP application 3.1 Goals, requirements, and plans Minimum viable product Andromeda software requirements The hardware subsystem Logic control scripts 3.2 Designing the architecture Defining architecture components Defining modules, subsystems, and relations Defining the application architecture Module organization 3.3 Naive implementation of the hardware subsystem The structure of the hardware subsystem Algebraic definition of HDL Functional interface to the hardware subsystem 4 End-to-end design
📄 Page 8
4.1 Finding the place for the end-to-end design Identifying and fixing wrong dependencies Improving models and naming Improving the Hdl language and interpreter Tests as a final consumer 4.2 Functional services Layers and sublayers The Service Handle pattern Hardware service Mocking with the Service Handle pattern Type class-powered service handle Part 3. Domain-driven design 5 Embedded domain-specific languages 5.1 Approaching embedded DSLs Everything is an eDSL Domain specific vs. domain centric 5.2 Modeling eDSLs with algebraic data types Clarifying the requirements Modeling eDSLs with ADTs Modeling multiple interacting eDSLs Decoupling languages with parameterized ADTs 5.3 Implementation of eDSLs Runtime objects and lifetimes Impure stateful interpreters 6 Domain modeling with free monads 6.1 Introducing free monads 6.2 Free monads as a functional interface Decoupling of computation and interpretation
📄 Page 9
The Free Monad pattern Advantages and disadvantages 6.3 How free monads work Wrapping languages into the free monad The Free type The functor instance Learning the recursive free type Interpretation of free monadic scripts 6.4 Free monadic eDSLs Improving eDSLs with the free monad Hierarchical free eDSLs Part 4. Stateful and reactive applications 7 Stateful applications 7.1 Stateful functional programming Simple stateful application Purity, layering, state, and design 7.2 State-handling approaches Argument-passing state Pure state with the state monad Bringing pure state into your monadic eDSLs Impure mutable state 8 Reactive applications 8.1 Actor model Simulation of actors The architecture of the simulator The MVar Request–Response pattern 8.2 Implementing the simulator Simulator as an actor
📄 Page 10
Stateful simulation model Part 5. Designing real-world software 9 Concurrent application framework 9.1 Multithreaded applications Why is multithreading hard? Bare threads Separating and abstracting the threads Threads bookkeeping 9.2 Software transactional memory Why STM is important STM-powered runtime of the framework Incorporating STM 10 Foundational subsystems 10.1 Logging subsystem Logger design Global static mutable logger Structured logging interface Structured logging implementation 10.2 Advanced state management Wrapping STM with the Typed-Untyped design pattern State subsystem and logging Trackable state 10.3 Resource initialization and the Bracket pattern RAII in OOP languages The Bracket pattern 11 Persistence: Key–value databases 11.1 Raw untyped key–value database subsystem
📄 Page 11
Native key–value database libraries String-based key–value database interface 11.2 Type-safe key–value database subsystem Basic key–value database model Approaching the type-level design Type-safe key–value database model Generic type-safe key–value interface 12 Persistence: Relational databases 12.1 Relational database model Designing relational database model ADTs Primary keys and the HKD pattern Polymorphic ADTs with the HKD pattern 12.2 Relational database subsystem SQL connectors The consequences of complexity and high coupling 13 Error handling and dependency inversion 13.1 Error handling through architectural layers Errors vs. exceptions Error domains Native exception-handling schemes Exceptions in free monadic languages 13.2 Functional interfaces and dependency inversion The Dependency Inversion principle Service Handle pattern ReaderT pattern Free monad GADT Final tagless/mtl Comparison of the approaches
📄 Page 12
14 Business logic design 14.1 Command-line client application API data model and HTTP schema Command-line interaction HTTP client functionality 14.2 Server application Extended HTTP schema Using the framework for business logic Web server Validation 15 Testing 15.1 Testing in functional programming Testing basics Property-based testing Property-based testing of a free monadic scenario Integration testing Acceptance testing 15.2 Advanced testing techniques Testable architecture Mocking with free monads White-box unit testing Testing framework Testability of different approaches Appendix A. Plenty of monads Appendix B. Stacking monads with monad transformers Appendix C. Word statistics example with monad transformers
📄 Page 13
Appendix D. Automatic white-box testing index
📄 Page 14
front matter preface You’re probably looking for new insights into what you already know about software design, or you might be wondering how to build real programs in functional languages such as Haskell, Scala, Elm, PureScript, F#, or OCaml. Perhaps you’ve always wanted to get a complete picture of software engineering in Haskell, or maybe the idea of having a methodology unifying all the main concepts of functional programming has attracted your attention. All of these reasons motivated me to write this book: I realized how big the knowledge gap was and that I desperately needed to fill in this gap for my day-to-day functional job. This book uses Haskell as a model language. The choice was deliberate because it’s the most iconic functional language with a rich type system. It could have been Scala or OCaml, but unfortunately, I am not proficient enough in those languages. The ideas are universal, and Haskell allows me to present them in a concise and easy-to-follow way. This book has a long story behind it. I started this book with Manning Publications at the beginning of 2016, but the process stalled out. At that time, I had completed a lot of supporting projects and examples. I also discovered a bunch of new concepts that I refined through several years of successful production usage. In 2020, I self-published the first writing of Functional Design and Architecture (https://leanpub.com/functional-design-and-
📄 Page 15
architecture). I received many great reviews from my readers and reached out to Manning to see whether they would be interested in publishing it in the completed form. This book is the result. This edition significantly differs from the first edition in the teaching material used, but the topics and approaches are identical. The core idea and the concept also remained the same, which is software design with statically typed functional languages. I rewrote the first half completely and made many improvements in the second half; it is now more polished and better organized, so you don’t have to read the earlier version. I personally love both, nevertheless. Long story short, this book is what I’ve been working on for more than eight years, and I truly believe the final product does a great job of shedding light on the subject. Many interesting ideas are presented here; however, one book can’t cover everything there is to know about functional programming for designing software. A lot of interesting stuff was left behind, and we likely need 20 additional ground-breaking books to cover everything. I will continue writing more books, so let’s keep in touch to develop this knowledge together! acknowledgments This book wouldn’t be what it is today without the contribution of many, and I am grateful to everyone who participated in the process. A heartfelt thanks goes to the pioneers of functional programming. Your innovative ideas and foundational work have been instrumental in shaping this field and, by extension, this book. Your efforts have made all the difference.
📄 Page 16
I also extend my gratitude to the trailblazers of software engineering. Your dedication to establishing and advancing this discipline has paved the way for professionals like me to grow and innovate. Your legacy is evident in every chapter of this work. To my readers, both past and present, your support has been invaluable. Your feedback, questions, and enthusiasm have not only motivated me but also played a crucial role in refining this book. Your contribution is deeply appreciated. Thank you to the team at Manning Publications who were so invaluable in making this edition of the book a reality. Your professionalism and belief in me are truly appreciated. Thanks also to my technical editor, Arnaud Bailly, who has been developing software and helping teams develop software in various technologies, contexts, and roles for nearly three decades. Arnaud’s experience was a great help in making sure everything in the book works as it should. Special thanks go to all the reviewers who helped refine and polish this manuscript: Adrian Bilauca, Andrei Formiga, Andres Sacco, Charles Earl, Daut Morina, David Cabrero, David Paccoud, Ernesto Garcia Garcia, Filip Mechant, German Gonzalez-Morris, Joel Holmes, Jose Luis Garcia Baltazar, Kai Gellien, Kelvin Chappell, Kent R. Spillner, Kevin Cheung, Luca Campobasso, Makarand Deshpande, Marco Perone, Mike Tedeschi, Mikkel Arentoft, Nikita Dyumin, Phillip Sorensen, Richard Tobias, Robert Walsh, Roberto Casadei, Rohinton Kazak, Satej Kumar Sahu, Tony Mullen, Walt Stoneburner, and William E. Wheeler. Your input and expertise have been vital in ensuring the clarity and quality of the final product.
📄 Page 17
In essence, this book is a collaborative effort, and I am grateful to everyone who was part of this journey. about this book Fundamental mainstream software engineering books are readily available, and we all know how important they have been for establishing the software engineering industry. While most of these books address object-oriented programming (OOP), this book expands the knowledge base to functional languages. I wrote Functional Design and Architecture to help developers build big, high-quality applications from end to end in functional languages and with functional reasoning. The book talks about functional design patterns, old and new, discussing various application architectures suitable for languages such as Haskell, Scala, and OCaml. It also introduces a number of best practices to follow, incorporating them into a bigger picture of software engineering with functional ideas. You’ll also find various design principles from both the mainstream and functional world, which all form the core of the methodology I craft in this book—functional declarative design (FDD). This book pioneers several concepts, such as free monads as true functional interfaces and the hierarchical free monads approach. It also builds on object-oriented design principles such as SOLID for functional settings. I also provide you with new ways of domain modeling, be they collection requirements with mind and concept maps or using interpretable embedded domain-specific languages as a main tool to maintain complexity. The book contains this and even more, but the main idea is based on pragmatism. You’ll rarely
📄 Page 18
find a book that talks about functional programming in such a practical and informal style, free from unnecessary math fleur and approachable to a wide audience. This book proves that functional programming can be a useful tool for serving businesses. Who should read this book? This book is intended for software developers and architects looking to enhance their skills by learning a comprehensive and complete methodology of software design with deep and interesting ideas coming from the functional world. Although Haskell is a model language, and some prior knowledge is assumed, the book is comprehensive, so its ideas can be applied to other statically typed functional languages such as OCaml, F#, PureScript, Elm, Scala, and even C++! The first half of the material is simplified to address a wider audience of developers, so it is quite helpful even if Haskell is not your favorite language. If you’re interested in learning Haskell, I recommend checking out these excellent Manning resources: Philipp Hagenlocher, Learn Haskell by Example, www.manning.com/books/learn-haskell-by-example Will Kurt, Get Programming with Haskell, www.manning.com/books/get-programming-with-haskell If you want to expand your knowledge even further, the following is a great resource: Vitaly Bragilevsky, Haskell in Depth, www.manning.com/books/haskell-in-depth
📄 Page 19
How this book is organized: A roadmap This book is organized into five parts. In the first four parts, we’ll talk a lot about domain-specific languages, domain-driven design, interpretable languages, design principles, design patterns, and the new methodology of functional declarative design (FDD). Part five continues this discussion, but the perspective is slightly different, as we will focus on designing real-world software. Part 1 offers an introduction to functional declarative design: Chapter 1—This chapter establishes the foundation for further discussion. It explains the main notions of software design, such as complexity, design principles, and design patterns. In addition, it introduces the terminology we’ll be using throughout the book. Chapter 2—In this chapter, I define my methodology, that is, functional declarative design. The chapter is organized as reference material listing topics pertaining to the methodology. Part 2 creates a minimum viable product: Chapter 3—We start building a spaceship control software application with simple functional approaches and then form the initial set of business requirements for our software. Chapter 4—Focusing on end-to-end design, we continue to develop the application by designing a skeleton that includes all the needed parts and a proper architecture.
📄 Page 20
Part 3 delves into domain-driven design: Chapter 5—This chapter opens a discussion of domain modeling with embedded domain-specific languages. This approach is superior when it comes to addressing business domains properly and keeping complexity low. Chapter 6—In this chapter, I introduce free monads using knowledge from the previous chapter. With free monads, domain modeling becomes truly powerful. Part 4 addresses stateful and reactive applications: Chapter 7—Here, we learn more about organizing stateful applications and maintaining state with direct approaches, such as argument-passing state and mutable references. Then we move to state monads. Chapter 8—This chapter covers the actor model and basics of multithreaded concurrent architectures. We also finish developing our spaceship control software by making a simulator environment for it. In part 5, we work on designing real-world software: Chapter 9—We move to the development of the concurrent application framework using the knowledge we’ve acquired and learn about additional architectural and design approaches. Chapter 10—Here, we craft several important subsystems of the framework, including, among others, logging and a state management subsystem.
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now
Back to List