Posts Tagged ‘LiveCoding’
[DevoxxBE2023] A Deep Dive into Advanced TypeScript: A Live Coding Expedition by Christian Wörz
Christian Wörz, a seasoned full-stack engineer and freelancer, captivated the Devoxx Belgium 2023 audience with a hands-on exploration of advanced TypeScript features. Through live coding, Christian illuminated powerful yet underutilized constructs like mapped types, template literals, conditional types, and recursion, demonstrating their practical applications in real-world scenarios. His session, blending technical depth with accessibility, empowered developers to leverage TypeScript’s full potential for creating robust, type-safe codebases.
Mastering Mapped Types and Template Literals
Christian kicked off with mapped types, showcasing their ability to dynamically generate type-safe structures. He defined an Events type with add and remove properties and created an OnEvent type to prefix event keys with “on” (e.g., onAdd, onRemove). Using the keyof operator and template literal syntax, he ensured that OnEvent mirrored Events, enforcing consistency. For instance, adding a move event to Events required updating OnEvent to onMove, providing compile-time safety. He enhanced this with TypeScript’s intrinsic Capitalize function to uppercase property names, ensuring precise naming conventions.
Template literals were explored through a chessboard example, where Christian generated all possible positions (e.g., A1, B2) by combining letter and number types. He extended this to a CSS validator, defining a GapCSS type for properties like margin-left and padding-top, paired with valid CSS sizes (e.g., rem, px). This approach narrowed string types to enforce specific formats, preventing errors like invalid CSS values at compile time.
Leveraging Conditional Types and Never for Safety
Christian delved into conditional types and the never type to enhance compile-time safety. He introduced a NoEmptyString type that prevents empty strings from being assigned, using a conditional check to return never for invalid inputs. Applying this to a failOnEmptyString function ensured that only non-empty strings were accepted, catching errors before runtime. He also demonstrated exhaustive switch cases, using never to enforce complete coverage. For a getCountryForLocation function, assigning an unhandled London case to a never-typed variable triggered a compile-time error, ensuring all cases were addressed.
Unraveling Types with Infer and Recursion
The infer keyword was a highlight, enabling Christian to extract type information dynamically. He created a custom MyReturnType to mimic TypeScript’s ReturnType, inferring a function’s return type (e.g., number for an addition function). This was particularly useful for complex type manipulations. Recursion was showcased through an UnnestArray type, unwrapping deeply nested arrays to access their inner types (e.g., extracting string from string[][][]). He also built a recursive Tuple type, generating fixed-length arrays with specified element types, such as a three-element RGB tuple, with an accumulator to collect elements during recursion.
Branded Types for Enhanced Type Safety
Christian concluded with branded types, a technique to distinguish specific string formats, like emails, without runtime overhead. By defining an Email type as a string intersected with an object containing a _brand property, he ensured that only validated strings could be assigned. A type guard function, isValidEmail, checked for an @ symbol, allowing safe usage in functions like sendEmail. This approach maintained the simplicity of primitive types while enforcing strict validation, applicable to formats like UUIDs or custom date strings.
Links:
[DevoxxFR2013] Live Coding: A WOA Application in 50 Minutes
Lecturer
Guillaume Bort co-founded Zenexity, specializing in Web Oriented Architecture. Previously a J2EE expert, he developed web frameworks for large enterprises, creating Play Framework to prioritize simplicity. He leads Play’s development.
Sadek Drobi, Zenexity’s CTO, focuses on enterprise applications, bridging problem and solution domains. As a programming languages expert, he contributes to Play Framework’s core team.
Abstract
Guillaume Bort and Sadek Drobi’s live coding demonstrates building a Web Oriented Architecture (WOA) application using Play Framework and Scala. Consuming Twitter’s API, they handle JSON, integrate MongoDB, and stream real-time data via Server-Sent Events to an HTML5 interface. The session analyzes reactive programming, asynchronous handling, and scalability, showcasing Play’s efficiency for modern web apps.
Setting Up the Foundation: Play Framework and Twitter API Integration
Bort and Drobi initiate with Play Framework, creating a project via activator. They configure routes for homepage and stream endpoints, using Scala’s async for non-blocking I/O.
Consuming Twitter’s search API: construct URLs with keywords like “DevoxxFR”, include entities for images. Use WS (WebService) for HTTP requests, parsing JSON responses.
They extract tweet data: user, text, images. Handle pagination with since_id for subsequent queries, building a stream of results.
This setup leverages Play’s stateless design, ideal for scalability.
Building Reactive Streams: Enumerators and Asynchronous Processing
To create a continuous stream, they employ Enumerators and Iteratees. Poll Twitter periodically (e.g., every 5 seconds), yielding new tweets.
Code uses concurrent scheduling:
val tweets: Enumerator[Tweet] = Enumerator.generateM {
Future {
// Fetch and parse tweets
Some(newTweets)
}
}
Flatten to a single stream. Handle errors with recover, ensuring resilience.
This reactive approach processes data as it arrives, avoiding blocking and enabling real-time updates.
Persisting Data: Integrating MongoDB with ReactiveMongo
For storage, integrate ReactiveMongo: asynchronous, non-blocking driver. Define Tweet case class, insert via JSONCollection.
val collection = db.collection[JSONCollection]("tweets")
collection.insert(tweetJson)
Query for latest since_id. Use find with sort/take for efficient retrieval.
This maintains asynchrony, aligning with WOA’s distributed nature.
Streaming to Clients: Server-Sent Events and HTML5 Interface
Output as EventSource: chunked response with JSON events.
Ok.chunked(tweets &> EventSource()).as("text/event-stream")
Client-side: JavaScript EventSource listens, appending images with animations.
Handle dynamics: form submission triggers stream, updating UI.
This enables push updates, enhancing interactivity without WebSockets.
Optimizing for Scalability: Backpressure and Error Handling
Address overload: use onBackpressureBuffer to queue, drop, or fail. Custom strategies compress or ignore excess.
Play’s Akka integration aids actor-based concurrency.
Implications: Builds resilient, scalable apps handling high loads gracefully.
Collaborative Development: Live Insights and Community Resources
Session highlights rapid prototyping: zero slides, GitHub commits for following.
Drobi comments on concepts like futures unification in Scala 2.10, inter-library interoperability.
They encourage exploring Play docs, plugins for extensions.
This methodology fosters understanding of reactive paradigms, preparing for distributed systems.
Links:
[DevoxxFR2012] Practicing DDD in a Flash – Sculptor, the DDD Code Generator for Java
Ulrich Vachon is a DDD and agile practitioner with experience at software vendors. He promotes expressive modeling and rapid feedback.
This article expands the live coding demo of Sculptor, a DSL-based code generator for DDD applications in Java. Domain-Driven Design is powerful but verbose. Sculptor accelerates bootstrapping while preserving DDD principles. Using a simple DSL, developers define aggregates, value objects, services, and repositories. Sculptor generates Spring, JPA, REST, and MongoDB code.
Sculptor DSL and Code Generation
A live demo built a blog application:
Application Blog {
Module posts {
Entity Post {
@Id String id;
String title;
String content;
@ManyToOne Author author;
}
ValueObject Author {
String name;
String email;
}
Service PostService {
Post save(Post post);
List<Post> findAll();
}
}
}
Sculptor generated entities, repositories, services, controllers, and tests.
Customization with the Gap Mechanism
The gap keyword allows hand-written extensions without regeneration conflicts.
Links
Relevant links include the Sculptor Project at sites.google.com/site/fornaxsculptor and the original video at YouTube: Practicing DDD in a Flash.