<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Kenneth Lange</title>
	<atom:link href="https://kennethlange.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://kennethlange.com</link>
	<description></description>
	<lastBuildDate>Tue, 24 Feb 2026 18:34:59 +0000</lastBuildDate>
	<language>en-GB</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0</generator>

<image>
	<url>https://kennethlange.com/wp-content/uploads/2023/05/cropped-android-chrome-512x512-1-32x32.png</url>
	<title>Kenneth Lange</title>
	<link>https://kennethlange.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>AI-powered: What Tasks can be Performed by Generative AI?</title>
		<link>https://kennethlange.com/ai-powered-what-tasks-can-be-performed-by-generative-ai/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Sat, 04 May 2024 09:42:07 +0000</pubDate>
				<category><![CDATA[Artificial Intelligence]]></category>
		<guid isPermaLink="false">https://kennethlange.com/?p=1322</guid>

					<description><![CDATA[In a previous post, I discussed how Generative AI serves as an incredible new addition to your SaaS toolbox, enabling&#8230;<p><a href="https://kennethlange.com/ai-powered-what-tasks-can-be-performed-by-generative-ai/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In a previous post, I discussed how Generative AI serves as an incredible new addition to your SaaS toolbox, enabling you to optimize and automate core workflows. But what concrete capabilities does Generative AI offer?</p>



<p class="wp-block-paragraph">This post serves as my personal checklist outlining the tasks that Generative AI can potentially assist with within the context of a SaaS platform. It&#8217;ll primarily focus on its capabilities in language and text processing:</p>



<ul class="wp-block-list">
<li><a href="#text-summarization"><strong>Text Summarization</strong></a> (<em>e.g.,</em> create executive summaries)</li>



<li><a href="#text-classification"><strong>Text Classification</strong></a> (<em>e.g.,</em> is this customer case a feature request or a bug report)</li>



<li><a href="#sentiment-analysis"><strong>Sentiment Analysis</strong></a> (<em>e.g.,</em> positive or negative views)</li>



<li><a href="#emotion-detection"><strong>Emotion Detection</strong></a> (<em>e.g.,</em> is your customer surprised, joyful, or angry?)</li>



<li><a href="#text-tagging"><strong>Text Tagging</strong></a> (<em>e.g.,</em> add hashtags)</li>



<li><a href="#text-translation"><strong>Text Translation</strong></a> (<em>e.g.,</em> translate from French to English)</li>



<li><a href="#named-entity-recognition"><strong>Named-Entity Recognition</strong></a> (<em>e.g.,</em> identify real-world people and places in text)</li>



<li><strong><a href="#text-generation">Text Generation</a></strong> (<em>e.g.,</em> for chatbots, automatic replies)</li>



<li><strong><a href="#retrieval-augmented-generation">Retrieval-Augmented Generation</a></strong> (<em>e.g.,</em> use your own data with Generative AI)</li>



<li><strong><a href="#text-similarity">Text Similarity</a></strong> (<em>e.g.,</em> for semantic search, more-like-this features)</li>



<li><strong><a href="#question-and-answering">Question &amp; Answering</a></strong> (<em>e.g.,</em> for decision points, content moderation, evaluate ideas)</li>



<li><strong><a href="#text-transformation">Text Transformation</a></strong> (<em>e.g.,</em> transform CSV to JSON, transform free-text to a structured format)</li>



<li><strong><a href="#anomaly-detection">Anomaly Detection</a></strong> (<em>e.g.,</em> for quality control)</li>
</ul>



<p class="wp-block-paragraph">Remember, these capabilities can be like Legos – you can build impressive solutions by combining them! For instance, first translate all customer comments into a single language, such as English, then group similar comments together based on their topic, and finally summarize the key points of each group for speed reading.</p>



<h2 class="wp-block-heading" id="text-summarization">Text Summarization</h2>



<p class="wp-block-paragraph">Turn lengthy documents into concise summaries. Generative AI can extract key points from customer support tickets, emails, contracts, and more, making information easier to read and understand.</p>



<ul class="wp-block-list">
<li><strong>Example 1:</strong> Support agents can grasp customer issues faster with AI-generated summaries of requests.</li>
</ul>



<ul class="wp-block-list">
<li><strong>Example 2:</strong> Generate weekly executive summaries by condensing large volumes of customer messages into executive summaries.</li>
</ul>



<ul class="wp-block-list">
<li><strong>Example 3:</strong> Summarize all customer issues to identify common pain points and areas for improvement as input to the product development team.</li>
</ul>



<p class="wp-block-paragraph">Information overload is a real problem for many SaaS companies, because it leads to inefficiencies and bottlenecks in workflows. Summarization helps prioritize tasks, gain insights quickly, and make informed decisions.</p>



<h2 class="wp-block-heading" id="text-classification">Text Classification</h2>



<p class="wp-block-paragraph">Classify incoming text data into pre-defined classes. Generative AI can automatically classify incoming support tickets, emails, and other documents into classes or categories defined by you.</p>



<ul class="wp-block-list">
<li><strong>Example 1:</strong> Classifying incoming support tickets according to difficulty level (easy, medium, hard) for efficient routing to first or second-line support and thereby enabling faster resolution.</li>
</ul>



<ul class="wp-block-list">
<li><strong>Example 2:</strong> Efficiently route support tickets by automatically classifying them by type (bug report, feature request, or question) and immediately assigning them to the appropriate team.</li>
</ul>



<ul class="wp-block-list">
<li><strong>Example 3:</strong> In a web directory, automatically add new websites to the appropriate categories.</li>
</ul>



<p class="wp-block-paragraph">This intelligent and automatic classification of text can accelerate decision-making and efficiency in SaaS workflows.</p>



<h2 class="wp-block-heading" id="sentiment-analysis">Sentiment Analysis</h2>



<p class="wp-block-paragraph">Understand the sentiment behind incoming text data. Generative AI can analyze emails, chat messages, social media posts, and other documents to determine whether they are positive, negative, or neutral:</p>



<ul class="wp-block-list">
<li><strong>Example 1:</strong> Prioritize customer inquiries based on sentiment. Flag negative feedback for swift resolution.</li>
</ul>



<ul class="wp-block-list">
<li><strong>Example 2:</strong> Monitor sentiment shifts in customer chats during support interactions. Automatically escalate chats that turn negative to a manager.</li>
</ul>



<ul class="wp-block-list">
<li><strong>Example 3:</strong> Analyze sentiment in customer support tickets to identify areas for product improvement or highlight features customers love.</li>
</ul>



<p class="wp-block-paragraph">Sentiment analysis empowers businesses to gain insights into their customers&#8217; feelings through automated analysis of text data. This allows for proactive customer service and data-driven decision-making within SaaS workflows, ultimately leading to improved customer experiences.</p>



<h2 class="wp-block-heading" id="emotion-detection">Emotion Detection</h2>



<p class="wp-block-paragraph">Gain a deeper understanding of customer sentiment with emotion detection. This advanced AI capability goes beyond basic sentiment analysis by pinpointing specific emotions in customer messages, emails, and social media posts. Emotion detection can reveal <em>anger</em>, <em>disgust</em>, <em>fear</em>, <em>joy</em>, <em>sadness</em>, or <em>surprise</em>.</p>



<ul class="wp-block-list">
<li><strong>Example 1:</strong> A healthcare chatline can prioritize chats with extremely fearful patients, ensuring they receive prompt and empathetic care.</li>
</ul>



<ul class="wp-block-list">
<li><strong>Example 2:</strong> An e-commerce platform can use emotion detection to identify customers expressing joy about a new purchase, allowing for targeted upsell recommendations of complementary products (e.g., a new game for a joyful gamer).</li>
</ul>



<ul class="wp-block-list">
<li><strong>Example 3:</strong> A FinTech company might proactively reach out to customers expressing anger to understand their concerns and offer solutions, preventing potential churn and fostering stronger relationships.</li>
</ul>



<p class="wp-block-paragraph">Emotion detection empowers businesses to understand customer feelings on a deeper level. This valuable insight allows for personalized customer journeys (e.g., tailored product recommendations, empathetic support interactions) and improved interactions within SaaS workflows. By understanding specific emotions, businesses can provide more empathetic support, offer personalized product recommendations, and ultimately build stronger customer relationships.</p>



<h2 class="wp-block-heading" id="text-tagging">Text Tagging</h2>



<p class="wp-block-paragraph">Automatically enrich text content with relevant labels. Text tagging goes beyond text classification by allowing Generative AI to automatically assign relevant keywords, labels, or tags to incoming text data. Unlike text classification, these tags are not predefined but are automatically generated by the AI based on the content.</p>



<ul class="wp-block-list">
<li><strong>Example 1:</strong> Automatically add one or more tags to incoming customer messages (<em>e.g.,</em> billing, technical issue, feature request). This allows support agents to quickly see which topics are covered and route inquiries efficiently.</li>
</ul>



<ul class="wp-block-list">
<li><strong>Example 2: </strong>Based on the tags on a customer message, show the support agent a list of other customer messages with the same tags (e.g., similar billing inquiries). This can help identify recurring issues and find solutions faster.</li>
</ul>



<ul class="wp-block-list">
<li><strong>Example 3:</strong> Social media platforms can automatically suggest relevant hashtags to users when composing posts. This helps users improve post discoverability and reach a wider audience.</li>
</ul>



<p class="wp-block-paragraph">Text tagging empowers businesses to organize and categorize large volumes of text content. This can significantly improve information discovery, organization, and analysis within SaaS workflows. For example, customer support agents can leverage tags to quickly find similar inquiries or identify emerging customer issues. When a new tag suddenly appears and grows in usage, it can signal a new trend or problem that needs attention.</p>



<h2 class="wp-block-heading" id="text-translation">Text Translation</h2>



<p class="wp-block-paragraph">Automatically translate text content across languages. Generative AI offers advanced text translation capabilities, enabling real-time, natural-sounding translations between a wide variety of languages. This allows businesses to bridge the communication gap and reach a global audience.</p>



<ul class="wp-block-list">
<li><strong>Example 1:</strong> A multinational company can translate employee feedback surveys into a central language for analysis, fostering a more inclusive and informed decision-making process.</li>
</ul>



<ul class="wp-block-list">
<li><strong>Example 2:</strong> A global support center can offer 24/7 world-wide assistance by automatically translating incoming customer requests into the preferred language of the support agent.</li>
</ul>



<ul class="wp-block-list">
<li><strong>Example 3:</strong> An e-commerce platform can leverage text translation to showcase product descriptions and customer reviews in multiple languages, reaching a wider global audience and boosting international sales.</li>
</ul>



<p class="wp-block-paragraph">Text translation empowers businesses to achieve several key goals: increased customer satisfaction through multilingual support, improved brand recognition in international markets, and boosted business growth by reaching a global customer base and expanding sales opportunities.</p>



<h2 class="wp-block-heading" id="named-entity-recognition">Named-Entity Recognition</h2>



<p class="wp-block-paragraph">Automatically identify and classify named entities in text data. Named entities can include people, organizations, locations, products, events, dates, monetary values, etc. This allows Generative AI to extract key details and improve information organization.</p>



<ul class="wp-block-list">
<li><strong>Example 1:</strong> An insurance company might automatically locate and identify any person names (<em>e.g.,</em> policyholder, beneficiary) mentioned in incoming insurance claim reports and add them as involved parties in the case.</li>
</ul>



<ul class="wp-block-list">
<li><strong>Example 2:</strong> A customer service chat service might automatically identify what product or service (<em>e.g.,</em> specific software, subscription plan) the request is about, so it can be routed to the appropriate team.</li>
</ul>



<ul class="wp-block-list">
<li><strong>Example 3:</strong> An AI startup might use named-entity recognition to remove personally identifiable information (<em>e.g.,</em> names, addresses) from their dataset to ensure compliance with data privacy regulations.</li>
</ul>



<p class="wp-block-paragraph">Named-entity recognition empowers businesses to extract critical information from text data, automate data entry tasks (e.g., pre-populating forms), and enhance data analysis within SaaS workflows. This can lead to improved efficiency, streamlined workflows, and better decision-making.</p>



<h2 class="wp-block-heading" id="text-generation">Text Generation</h2>



<p class="wp-block-paragraph">This is a core capability of Generative AI: the ability to produce human-like text. Imagine creating chatbots like ChatGPT, but designed specifically for your SaaS company&#8217;s needs. These chatbots, powered by Generative AI, could answer customer questions, troubleshoot issues, and even schedule appointments – all fully automated.</p>



<ul class="wp-block-list">
<li><strong>Example 1:</strong> Create chatbots that answer customer questions, troubleshoot common issues, and even schedule meetings – all without human intervention. This frees up your support team to focus on more complex customer inquiries.</li>
</ul>



<ul class="wp-block-list">
<li><strong>Example 2:</strong> In a support chat, leverage Generative AI to suggest the next reply in the conversation with the customer. The support agent can then review and edit the suggestion before sending it. This allows for faster and more efficient customer service interactions while still maintaining a human touch.</li>
</ul>



<ul class="wp-block-list">
<li><strong>Example 3:</strong> A social media tool can use Generative AI to automatically create draft social media posts (<em>e.g.,</em> Tweets, LinkedIn posts) to promote a new blog post. These draft posts can include catchy headlines and engaging descriptions, saving social media managers time and allowing them to experiment with different creative approaches.</li>
</ul>



<p class="wp-block-paragraph">By leveraging text generation, SaaS companies can increase efficiency by automating tasks, improve customer engagement through personalized content, and speed up their core workflows.</p>



<h2 class="wp-block-heading" id="retrieval-augmented-generation">Retrieval-Augmented Generation (RAG)</h2>



<p class="wp-block-paragraph">Boost the power of Generative AI with real-world data. Retrieval-Augmented Generation (RAG) allows you to integrate your own data sources with Generative AI models. This empowers these models to access and leverage the most up-to-date and relevant information for specific tasks.</p>



<ul class="wp-block-list">
<li><strong>Example 1:</strong> A customer service chatbot can be augmented with your internal knowledge base (<em>e.g.,</em> support policies, FAQs) to answer customer questions directly rather than relying solely on its general training data. This ensures responses are accurate and based on your specific policies.</li>
</ul>



<ul class="wp-block-list">
<li><strong>Example 2:</strong> A news platform can leverage RAG to incorporate live news feeds into its AI models, delivering up-to-the-minute summaries of current events.</li>
</ul>



<ul class="wp-block-list">
<li><strong>Example 3:</strong> A sophisticated customer service chatbot can first search an internal knowledge base for an article that closely matches the customer&#8217;s query and then use this article when answering the customer&#8217;s request.</li>
</ul>



<p class="wp-block-paragraph">The ability to integrate your company&#8217;s data with Generative AI is a game-changer. By combining these technologies, you can benefit from the freshness of external data while still enjoying the many advantages of Generative AI. This allows for more accurate, up-to-date, and relevant responses tailored to the specific needs of the business.</p>



<h2 class="wp-block-heading" id="text-similarity">Text Similarity</h2>



<p class="wp-block-paragraph">Text similarity measures how similar two pieces of text are in semantic meaning. This powerful capability can help SaaS companies organize information and improve user experiences.</p>



<ul class="wp-block-list">
<li><strong>Example 1: </strong>Text similarity can power internal search functions, returning relevant documents even if a user&#8217;s query doesn&#8217;t match the exact keywords, and rank the documents in order of closeness to the user&#8217;s query. This can improve the effectiveness of internal knowledge bases and help users find the information they need faster.</li>
</ul>



<ul class="wp-block-list">
<li><strong>Example 2:</strong> Group large collections of documents into thematic categories based on their content similarity. This makes it easier for users to browse and find the information they need.</li>
</ul>



<ul class="wp-block-list">
<li><strong>Example 3:</strong> On an internal support site, text similarity can identify &#8220;Related Support Cases&#8221; based on semantic similarity. This allows users to find solutions to similar problems without needing to search through countless articles.</li>
</ul>



<p class="wp-block-paragraph">By leveraging text similarity, SaaS companies can improve user experience, streamline workflows, and reduce the time spent searching for relevant information.</p>



<h2 class="wp-block-heading" id="question-and-answering">Question &amp; Answering (Q&amp;A)</h2>



<p class="wp-block-paragraph">Generative AI empowers machines to understand and answer your questions in natural language, just like you would ask a colleague. This allows businesses to automate decision-making processes within workflows and tackle complex tasks that traditional programming struggles with.</p>



<ul class="wp-block-list">
<li><strong>Example 1:</strong> Automate decision points within workflows using Q&amp;A. Imagine a customer support workflow where Generative AI can analyze a support ticket and answer a question like &#8220;<em>Is this an angry customer complaint?</em>&#8221; Based on the answer (yes/no), the ticket can be automatically routed to the appropriate support tier (second level for escalated issues, first level for regular inquiries). This not only increases efficiency but also improves customer satisfaction by ensuring faster resolution times.</li>
</ul>



<ul class="wp-block-list">
<li><strong>Example 2:</strong> Ensure the quality and suitability of user-generated content with Generative AI. You can leverage Q&amp;A to automatically evaluate content and answer questions like &#8220;Is this content appropriate for all audiences?&#8221;. This allows for faster moderation and identification of potentially harmful content.</li>
</ul>



<ul class="wp-block-list">
<li><strong>Example 3:</strong> A company has crowd-sourced ideas for a new product and asks Generative AI to perform the first evaluation of the incoming ideas and answer questions like &#8220;<em>Does this idea align with our product goals?</em>&#8221; This initial evaluation helps prioritize high-potential ideas and saves human resources for in-depth analysis.</li>
</ul>



<p class="wp-block-paragraph">Q&amp;A empowers businesses to automate decision points in workflows, improve information retrieval, and streamline data processing, leading to increased efficiency and productivity. This allows human experts to focus on higher-level tasks and strategic decision-making.</p>



<h2 class="wp-block-heading" id="text-transformation">Text Transformation</h2>



<p class="wp-block-paragraph">Generative AI automates the process of transforming text data from one format to another. This empowers businesses to seamlessly integrate data from various sources, regardless of format, and unlock its full potential within workflows.</p>



<ul class="wp-block-list">
<li><strong>Example 1:</strong> A marketing automation platform can leverage text transformation to ingest customer data from various sources (e.g., CRMs, social media platforms), which might be in different formats (CSV, vCard, etc.). The Generative AI system can automatically convert this data into a unified format, enabling streamlined segmentation and targeted marketing campaigns.</li>
</ul>



<ul class="wp-block-list">
<li><strong>Example 2:</strong> A healthcare provider can utilize text transformation to process patient data from disparate sources. For example, converting doctor&#8217;s notes into a structured format allows for easier analysis and integration with electronic health records, improving patient care coordination.</li>
</ul>



<ul class="wp-block-list">
<li><strong>Example 3:</strong> A company receives unreliable data from a live source and can then use Generative AI to clean and standardize the format before it&#8217;s processed further, ensuring data quality and improving downstream workflows.</li>
</ul>



<p class="wp-block-paragraph">Text transformation empowers businesses to unify data from various sources, streamline data processing workflows, and unlock deeper insights from their data, leading to improved decision-making and better business outcomes. This allows businesses to leverage the full potential of their data and gain a competitive edge.</p>



<h2 class="wp-block-heading" id="anomaly-detection">Anomaly Detection</h2>



<p class="wp-block-paragraph">Proactively identify data issues with anomaly detection. Generative AI excels at recognizing patterns within data. This capability allows businesses to leverage anomaly detection to identify unexpected variations or outliers within datasets. This can be instrumental in proactive quality control, flagging potential issues before they impact downstream processes.</p>



<ul class="wp-block-list">
<li><strong>Example 1:</strong> A multilingual marketing agency can leverage anomaly detection to ensure the quality of translated marketing materials. The Generative AI system can analyze translated text for inconsistencies or deviations from the original source content, flagging potential errors for human review before campaign launch.</li>
</ul>



<ul class="wp-block-list">
<li><strong>Example 2:</strong> An e-commerce platform can utilize anomaly detection to identify irregularities in product data feeds from suppliers. The Generative AI system can compare new data against historical data, detecting outliers such as uncommon words or missing product descriptions, preventing inaccurate product information from being displayed on the platform.</li>
</ul>



<ul class="wp-block-list">
<li><strong>Example 3:</strong> A company receives a spreadsheet with a million user records that needs to be uploaded to their SaaS platform. Before uploading, Generative AI can check for anomalies within the data, highlighting outliers or inconsistencies that require manual review before upload, ensuring data integrity.</li>
</ul>



<p class="wp-block-paragraph">Anomaly detection empowers businesses to proactively identify and address data quality issues, minimize errors, and improve the overall reliability of their data. This leads to better decision-making and reduced operational costs. By proactively addressing data anomalies, businesses can ensure the smooth operation of their workflows and gain a significant competitive advantage.</p>



<p class="wp-block-paragraph">&#8212;ooo&#8212;</p>



<p class="wp-block-paragraph">This glimpse into Generative AI&#8217;s capabilities is just a starting point. As this technology continues to evolve, it has the potential to revolutionize various industries and workflows. While it&#8217;s important to acknowledge that Generative AI, like any powerful tool, has limitations, it can also generate inaccurate or misleading information at times. As the technology matures, researchers are addressing these challenges. We are only scratching the surface of what Generative AI can do, and the possibilities are truly exciting for the future <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f680.png" alt="🚀" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Defensibility for AI Startups</title>
		<link>https://kennethlange.com/defensibility-for-ai-startups/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Sat, 27 Jan 2024 11:39:39 +0000</pubDate>
				<category><![CDATA[Artificial Intelligence]]></category>
		<guid isPermaLink="false">https://kennethlange.com/?p=1287</guid>

					<description><![CDATA[A significant portion of AI startups that have emerged during the last year are essentially thin wrappers around OpenAI&#8217;s API.&#8230;<p><a href="https://kennethlange.com/defensibility-for-ai-startups/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">A significant portion of AI startups that have emerged during the last year are essentially thin wrappers around OpenAI&#8217;s API. This is the archetypal &#8220;ChatGPT for X&#8221; startup, where X can be anything from marathon planning to insurance claims handling.</p>



<p class="wp-block-paragraph">The problem with building a business around a thin wrapper of another company&#8217;s API is that there is almost zero defensibility against copycats who create a clone of your product. Y Combinator is already funding numerous AI startups pursuing almost identical ideas, and OpenAI has launched their GPT Store, pulling the rug out from under a whole bunch of young AI startups building on top of their API.</p>



<p class="wp-block-paragraph">If you&#8217;ve proven a product-market fit for a new &#8220;ChatGPT for X,&#8221; you may discover that you&#8217;ve essentially conducted free market research for a large incumbent company in that area, such as SalesForce, which can easily add a clone of your product to their portfolio. Alternatively, another startup might simply clone your idea, turning your product into an easily replaceable commodity, driving the price down, and making it challenging to establish a sustainable business.</p>



<p class="wp-block-paragraph">So, what can a young AI startup do to defend itself against copycats attempting to clone its product?</p>



<h2 class="wp-block-heading">Proprietaty Datasets</h2>



<p class="wp-block-paragraph">The ultimate strategic asset for an AI startup is to have exclusive access to a valuable and hard-to-copy dataset. In AI startups, the training data is often more valuable than the AI algorithms. For instance, OpenAI, despite its team of world-class AI experts, abandoned robotics because they lacked data.</p>



<figure class="wp-block-pullquote"><blockquote><p>The ultimate strategic asset for an AI startup is to have exclusive access to a valuable and hard-to-copy dataset.</p></blockquote></figure>



<p class="wp-block-paragraph">A less potent version of this strategic asset is to have non-exclusive access to valuable data, such as open-source or public datasets, and then enrich it with additional insights. This can also involve aggregating multiple separate datasets into a unified whole, where the sum is greater than the parts. For example, while Salesforce lacks direct access to HubSpot&#8217;s data, an AI startup could aggregate these two data sources to uncover new insights for companies using both systems.</p>



<p class="wp-block-paragraph">The problem with proprietary datasets is that they are often held by established incumbents, not emerging AI startups. For instance, Google possesses vast amounts of search data, and Tesla has an extensive collection of driving data. In contrast, an AI startup almost always begins with nothing unless it has an exclusive partnership with the owner of such a proprietary dataset.</p>



<h2 class="wp-block-heading">Niche Specialization</h2>



<p class="wp-block-paragraph">My bet is that most early-stage startup opportunities lie in the application layer of AI, rather than the platform layer. OpenAI is rumored to have invested over $100 million in training GPT-4, indicating that competing at the platform level requires access to massive resources. An exception to this may be found in compliance-intensive domains, such as insurance or conducting business in the EU, where there might be opportunities in the platform layer for specialized or on-premises AI platform products.</p>



<p class="wp-block-paragraph">While I believe that most opportunities lie in the application layer, pursuing <em>horizontal</em> products—those with broad applicability across various industries—poses a serious risk. You may find yourself merely conducting free market research for an incumbent, as horizontal product ideas often appeal to established companies, such as Microsoft, who may readily clone your idea and integrate it into their existing offerings.</p>



<p class="wp-block-paragraph">A more effective strategy is to pursue an AI-powered idea specifically tailored to a particular niche—a <em>vertical</em> solution that delivers superior value to a targeted industry compared to any generic, horizontal product. Large players, such as Google or Amazon, often ignore verticals, and even if they do pursue them, they rarely allocate their A-players to these, for them, peripheral opportunities.</p>



<figure class="wp-block-pullquote"><blockquote><p>Avoid building AI for AI&#8217;s sake by solving problems that nobody cares about, even if they can be solved with AI.</p></blockquote></figure>



<p class="wp-block-paragraph">Practical ideas for AI-powered startups within a niche or vertical include digitalizing <a href="https://kennethlange.com/generative-ai-in-b2b-saas/">workflows</a> that were impossible to automate in the pre-AI era or developing applications that address pain points that are top priorities for executives in that vertical. Avoid building AI for AI&#8217;s sake by solving problems that nobody cares about, even if they can be solved with AI. Instead, focus on solving a problem that truly matters. In B2B startups, the litmus test is always whether someone is willing to pay for your product, rather than merely offering compliments and praise for your innovative idea. Don&#8217;t limit your solution to AI, but use whatever it takes, with AI being one tool in your toolbox.</p>



<p class="wp-block-paragraph">A crucial benefit of the niche approach is that, over time, you can build a proprietary dataset within that vertical, which can be used for fine-tuning generic AI models. This strategy mirrors GitHub&#8217;s approach, utilizing its vast code repositories to fine-tune a generic GPT model for its Copilot AI assistant.</p>



<p class="wp-block-paragraph">It&#8217;s important to acknowledge that niche specialization alone does <em>not</em> guarantee defensibility—at least, not until a proprietary dataset has been collected and utilized. This is because a copycat can just as easily attack a vertical product as a horizontal one. While focusing on a niche can reduce the number of competitors, it cannot safeguard against all potential rivals. For instance, you may have built the first &#8220;ChatGPT for X,&#8221; but then a copycat emerges, learns from your mistakes, and creates a superior version of &#8220;ChatGPT for X,&#8221; potentially drawing customers away from your original product.</p>



<h2 class="wp-block-heading">Startup Velocity</h2>



<p class="wp-block-paragraph">A significant advantage that a startup holds over established players is its ability to move quickly. This applies not only to AI startups but to any startup. Until a proprietary dataset has been established to defend against copycats, the key is to rely on the advantage of speed—outpacing incumbents and other AI startups in the same domain. By prioritizing rapid development and delivering a solution that effectively addresses customer needs, startups can potentially enjoy the benefits of first-mover advantages, such as network effects.</p>



<p class="wp-block-paragraph">Mathematically speaking, a startup <em>cannot</em> achieve instant defensibility. That is, something a small number of people can build in a short timeframe can be copied by competitors with similar or greater resources. If a compelling product-market fit exists, it would be a trivial task for Google to invest the same resources as the startup in pursuing this idea. However, it&#8217;s <em>unlikely</em> that they would be able to catch up with a fast-moving startup, especially one with a headstart.</p>



<p class="wp-block-paragraph">In summary, my rule of thumb for defensibility in AI startups is to focus on a vertical, building a product that people within that niche love to use, and then outpace competitors in terms of innovation and speed to market. Over time, aim to accumulate and leverage a proprietary dataset within that niche, establishing long-term defensibility against copycats and other clones.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Generative AI in B2B SaaS: Focus on Your Core Workflows</title>
		<link>https://kennethlange.com/generative-ai-in-b2b-saas/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Sat, 13 Jan 2024 15:28:30 +0000</pubDate>
				<category><![CDATA[Artificial Intelligence]]></category>
		<category><![CDATA[SaaS]]></category>
		<category><![CDATA[ScaleUp]]></category>
		<category><![CDATA[StartUp]]></category>
		<guid isPermaLink="false">https://kennethlange.com/?p=1261</guid>

					<description><![CDATA[Artificial intelligence took the world with storm with the launch of ChatGPT in 2022, triggering a surge in interest in&#8230;<p><a href="https://kennethlange.com/generative-ai-in-b2b-saas/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Artificial intelligence took the world with storm with the launch of ChatGPT in 2022, triggering a surge in interest in this transformative technology.</p>



<p class="wp-block-paragraph">Many companies suddenly realized that a major technological paradigm shift had occurred right beneath their feet, and that they needed to move fast and embrace AI technology quickly to remain relevant in the market.</p>



<p class="wp-block-paragraph">In response to this wake-up call, many B2B SaaS companies have taken the approach of embedding third-party AI chatbots, typically for customer support or other inquiries, as an add-on to their B2B SaaS platforms</p>



<p class="wp-block-paragraph">But I think this is a too timid response to this transformative opportunity: Customer support and chatbots are <em>not</em> where AI can have its greatest impact on B2B SaaS platforms.</p>



<h2 class="wp-block-heading">AI is *not* an Add-on Module</h2>



<p class="wp-block-paragraph">Regardless of which vertical or industry a B2B SaaS operates within, its core product consists of supporting business workflows. A workflow is the way that a business generates value, irrespective of the underlying technologies used. Whether a bank employs pen and paper, desktop software, or a SaaS solution, there are certain workflows that they follow to generate value for their customers.</p>



<p class="wp-block-paragraph">I am convinced that AI needs to be seamlessly integrated into each step of those workflows to optimize their performance. This means not only speeding up the workflows (maintaining the same output levels while reducing processing time) but also enhancing their output (delivering better results with the same cost and speed).</p>



<h2 class="wp-block-heading">Domain Expertise is the Secret Sauce</h2>



<p class="wp-block-paragraph">The key to the effective use of AI in a B2B SaaS platform is to truly understand the workflows: how they work, how value is generated, and which metrics are important.</p>



<p class="wp-block-paragraph">Next, map each step of the workflow and examine how AI can enhance or accelerate it. This requires considering the full spectrum of AI capabilities — from text generation and translations to sentiment analysis, text categorization, and summarization.</p>



<p class="wp-block-paragraph">As an example, consider a scenario where a new insurance claim is reported. AI can analyze the details provided and suggest the type of claim — car theft, lost luggage, or something else — to the claims handler, saving them time and effort in classifying the claim. Additionally, AI can summarize the claims report and suggest an appropriate response to the customer, ensuring prompt and efficient communication. Sentiment analysis can also be employed to evaluate the tone of follow-up messages in the conversation, providing valuable insights for handling customer interactions effectively. This seamless integration of AI can significantly enhance the productivity of claims handlers without compromising human expertise.</p>



<h2 class="wp-block-heading">AI&#8230; Just Another Tool in the Tech Stack</h2>



<p class="wp-block-paragraph">The current perception of AI resembles the early days of the internet in the 1990s. AI is often viewed as a standalone entity, an add-on feature rather than an integral part of the overall application. This approach treats AI as an innovative novelty rather than a fundamental component of the platform&#8217;s functionality.</p>



<p class="wp-block-paragraph">AI should <em>not</em> be considered an isolated feature or module but rather a fundamental tool in our tech stack, designed to excel at specific tasks, much like databases for data storage, email services for user communication, and analytics for tracking product usage. In essence, AI is <em>not</em> a standalone add-on but just another tool that we use to create value for our users.</p>



<h2 class="wp-block-heading">New Technology, New Problems</h2>



<p class="wp-block-paragraph">Just as the adoption of web technologies brought forth new challenges, such as remote services becoming unavailable due to network outages, which were absent in standalone desktop applications, AI also introduces its own unique set of issues that were previously nonexistent. These include addressing emerging compliance and security concerns, tackling operational challenges like hallucinations, and incurring additional costs.</p>



<p class="wp-block-paragraph">To conclude, I firmly believe that AI should be considered primarily as a powerful tool to optimize core workflows, the areas where true value is created. Instead of merely adding chatbots as standalone features to handle support inquiries or other non-core tasks, we must fully integrate AI into the core of our platforms to unleash its transformative power.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Startup CTO: Role and Responsibilities</title>
		<link>https://kennethlange.com/startup-cto-role-and-responsibilities/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Sat, 11 Nov 2023 09:58:21 +0000</pubDate>
				<category><![CDATA[CTO]]></category>
		<category><![CDATA[StartUp]]></category>
		<guid isPermaLink="false">https://kennethlange.com/?p=1242</guid>

					<description><![CDATA[In an early-stage startup, there are fantastic visions for the future and an almost endless stream of wild product ideas.&#8230;<p><a href="https://kennethlange.com/startup-cto-role-and-responsibilities/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In an early-stage startup, there are fantastic visions for the future and an almost endless stream of wild product ideas. The Chief Technology Officer (CTO) is responsible for transforming these wild ideas into a functional product that exceeds the expectations of real-world customers.</p>



<p class="wp-block-paragraph">In the archetypal two-person startup, the non-technical co-founder — typically the CEO — serves as the visionary and dreamer (think: <a href="https://www.intelligent-quotes.com/steve-jobs" target="_blank" rel="noreferrer noopener">Steve Jobs</a>), while the technical co-founder, the CTO, plays the crucial role of the engineer and builder (think: Steve Wozniak) who brings the startup&#8217;s product to life.</p>



<p class="wp-block-paragraph">However, whether it&#8217;s a one-person or two-person startup or a scale-up with a growing executive team, there are core technical responsibilities that must be addressed by the startup. The younger the startup, the more likely these responsibilities need to be handled by the CTO:</p>



<ul class="wp-block-list">
<li><strong>Product:</strong> Determining the functionality to build to delight users the most. This can include feature discovery, UI/UX design for new features, and prioritization of product ideas.</li>



<li><strong>Development: </strong>Develop the product that the startup is selling. This includes building the various apps and services comprising the product, such as a native mobile app, backend, and back-office tools. It also involves addressing non-functional aspects, such as security.</li>



<li><strong>Testing:</strong> Ensure the delivered software is of high quality and won&#8217;t disappoint users. This involves activities such as automated testing (from unit to E2E), manual/smoke testing (ensuring the feature delights the user), and penetration testing (for security).</li>



<li><strong>Support:</strong> Once the product is launched and users are onboard, support cases will begin to arise, whether due to bugs or missing functionality preventing users from extracting maximum value from the product. This responsibility involves addressing these incoming cases. While often challenging, it&#8217;s an incredible opportunity to learn more about users and how they engage with the system.</li>



<li><strong>DevOps:</strong> Manage all the necessary infrastructure (servers and databases) and tools (IDEs, CI/CD pipelines) required to build and run the product.</li>



<li><strong>Data/Analytics:</strong> Provide analytics on how the product is performing on metrics such as Monthly Active Users (MAU) and observe user behavior within it. With the growing importance of AI, the responsibility for data is likely to expand both in scope (including data engineering and data science) and significance.</li>



<li><strong>Internal IT:</strong> Manage tools essential for running the company, but unrelated to software development, such as HubSpot or Google Workspace. Fortunately, this responsibility has significantly diminished over the last 10 years, thanks to the shift to the cloud.</li>
</ul>



<p class="wp-block-paragraph">All these responsibilities need <em>not</em> be taken care of by the CTO, especially as the startup enters Series A and beyond. However, they will need to be handled by someone in the startup. For instance, over time, the company might hire a CPO to handle Product responsibility or a CIO to manage Internal IT.</p>



<p class="wp-block-paragraph">Furthermore, the exact distribution of responsibilities will depend on the composition of the leadership team. For instance, the CEO might take on product responsibilities, or the COO could handle Internal IT.</p>



<p class="wp-block-paragraph">Many of the responsibilities can be divided. For example, Customer Success can manage first-level support, leaving the CTO to handle second-level support. In testing, the CTO might take care of automated testing (unit tests, service tests, and end-to-end tests), while delegating UI/UX testing and functional testing (ensuring the delivered software meets user needs) to someone else.</p>



<p class="wp-block-paragraph">My advice is that the most crucial task for a CTO in a startup is to establish a development cycle capable of consistently delivering new features, bug fixes, and refactoring. Building and growing the product should be the top priority for a startup. Following this, consider delegating technical responsibilities not directly related to development, such as Internal IT, to other team members.</p>



<p class="wp-block-paragraph">A word of warning, though: do not isolate the CTO from customer contact (for instance, by removing them entirely from product, support, and analytics). I firmly believe that the CTO needs customer contact to stay linked to reality. While support may seem mundane and thankless, there is a surprising tendency for startups that take a support-driven approach to development, like Kayak or Wufoo, to perform remarkably well.</p>



<p class="wp-block-paragraph">So, in summary, if you listen to your customers and develop rapidly and continuously based on their inputs, you can afford to make mistakes in other areas and still succeed as a CTO.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>The Startup CTO: From Seed Stage to Exit</title>
		<link>https://kennethlange.com/startup-cto/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Sat, 30 Sep 2023 07:21:06 +0000</pubDate>
				<category><![CDATA[CTO]]></category>
		<category><![CDATA[StartUp]]></category>
		<guid isPermaLink="false">https://kennethlange.com/?p=1218</guid>

					<description><![CDATA[Startup CTOs often find themselves bombarded with well-intentioned advice, but the truth is, much of it misses the mark. As&#8230;<p><a href="https://kennethlange.com/startup-cto/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Startup CTOs often find themselves bombarded with well-intentioned advice, but the truth is, much of it misses the mark.</p>



<p class="wp-block-paragraph">As a CTO at <a href="https://woba.io/en/" target="_blank" rel="noreferrer noopener">Woba.io</a>, a SaaS startup, I frequently encounter perplexing pieces of advice in <a href="https://www.linkedin.com/in/kennethlange/" target="_blank" rel="noreferrer noopener">my LinkedIn feed</a>. The often low quality of these posts can be attributed to their authors, who are <em>not</em> CTOs themselves but rather software engineers or content writers who are trying to give good advice based on their own personal theories or shallow research, neither of which has been pressure-tested in a demanding real-world environment.</p>



<p class="wp-block-paragraph">However, I contend that much of the misguided advice and seemingly endless online discussions can be attributed to a simple source: confusion.</p>



<p class="wp-block-paragraph">The role of a CTO at a startup is dynamic, with success criteria evolving significantly depending on the startup&#8217;s stage. Advice that may be entirely logical for a startup poised for an IPO — such as the CTO shouldn&#8217;t do hands-on coding — can prove lethal to a seed-stage startup.</p>



<p class="wp-block-paragraph">In my mental model, I see five distinct stages of startup development, with each stage dramatically altering the nature of the CTO&#8217;s role:</p>



<ol class="wp-block-list">
<li><strong>Seed Stage (Pre-Seed, Seed):</strong> In this initial phase, the startup is typically pre-product and pre-revenue. The founders are driven by a promising idea, and the primary objective is to transform this idea into a product that people want, essentially seeking the elusive initial product-market fit (PMF). While the PMF will undergo refinement in later stages, this phase serves as the foundation upon which the journey forward is built.
<ul class="wp-block-list">
<li><strong>CTO Role:</strong> The CTO must be a versatile engineer capable of independently transforming the product idea into a working prototype — an MVP that the startup can present to users and investors to assess their interest. During this stage, expect numerous iterations, based on user feedback, some of which may entail significant changes to the prototype, particularly in the initial iterations.</li>
</ul>
</li>



<li><strong>Early Stage (Series A):</strong> The startup has successfully launched its product, gained its first satisfied customers, and achieved some initial revenue. The primary focus now shifts towards optimizing the product-market fit to create something highly desirable for a broader audience.
<ul class="wp-block-list">
<li><strong>CTO Role:</strong> At this stage, the CTO will be leading a small, tight-knit team of engineers who are rapidly enhancing the product, moving it ever closer to its optimal product-market fit. Simultaneously, the team must ensure the smooth operation of a live system with real users, underscoring the increasing importance of quality assurance and customer support within the CTO role.</li>
</ul>
</li>



<li><strong>Growth Stage (Series B-C):</strong> With the startup&#8217;s optimal product-market fit firmly in place and a crystal-clear understanding of its potential customer base, significant investments now flow into the startup, all geared toward the rapid acquisition of as many of these customers as possible.
<ul class="wp-block-list">
<li><strong>CTO Role:</strong> The CTO must facilitate explosive user growth, rapidly scaling everything from infrastructure to the engineering team to accommodate this high growth. This involves swift hiring while the CTO&#8217;s role also transforms into that of a manager of managers within an ever-growing organization.</li>
</ul>
</li>



<li><strong>Expansion Stage (Series D+):</strong> The startup, having maxed out organic growth within its customer base, now explores new avenues for expansion. These pathways may encompass global expansion, competitor acquisitions, the launch of new product lines, or the establishment of strategic partnerships.
<ul class="wp-block-list">
<li><strong>CTO Role:</strong> The scope of the CTO&#8217;s responsibilities varies depending on the chosen avenue of expansion. For global expansion, it entails product internationalization (beyond mere translation). Acquiring competitors necessitates rigorous technical due diligence and integration into the current platform. The introduction of new product lines involves the incorporation of additional teams into the existing engineering organization.</li>
</ul>
</li>



<li><strong>Exit Stage:</strong> Eventually, founders and investors will reach a crucial decision — the divestment (selling) of their ownership in the startup, typically achieved through an IPO (<em>e.g.,</em> Facebook), a sale to a strategic buyer (<em>e.g.,</em> Instagram to Facebook), or a transaction with a private equity firm.
<ul class="wp-block-list">
<li><strong>CTO Role:</strong> At this stage the CTO will typically lead the product/tech workstream part of the exit process, sometimes even in secret, while continuing to do their day job as CTO.</li>
</ul>
</li>
</ol>



<p class="wp-block-paragraph">As evident from the above, the role of a startup CTO undergoes profound transformations throughout the startup&#8217;s journey, evolving from a one-person powerhouse to a manager of managers, and from a garage-based operation to a fully-fledged enterprise. Alongside these shifting dynamics, the criteria for achieving success in this role also undergo remarkable changes, as do the tips and tricks that can help the CTO becoming successful.</p>



<p class="wp-block-paragraph">If you&#8217;d like to receive an email when the next post, please consider <a href="https://kennethlange.com/subscribe/">signing up here</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>8 Examples of Using Reduce in TypeScript</title>
		<link>https://kennethlange.com/reduce-in-typescript-examples/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Sat, 10 Dec 2022 09:59:52 +0000</pubDate>
				<category><![CDATA[TypeScript]]></category>
		<guid isPermaLink="false">https://kennethlange.com/?p=1143</guid>

					<description><![CDATA[This post shows common use cases for reduce in TypeScript. The examples include how to imitate SQL&#8217;s aggregate functions, such&#8230;<p><a href="https://kennethlange.com/reduce-in-typescript-examples/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">This post shows common use cases for <strong><a href="https://kennethlange.com/reduce-in-typescript/">reduce</a></strong> in TypeScript. The examples include how to imitate SQL&#8217;s aggregate functions, such as <strong>count</strong> and <strong>sum</strong>.</p>



<p class="wp-block-paragraph">All examples use the same array of blog posts, and each example is self-contained and can be easily copy/pasted (into <a href="https://www.typescriptlang.org/play/">TypeScript&#8217;s Playground</a>.)</p>



<p class="wp-block-paragraph">Happy coding!</p>



<h2 class="wp-block-heading">Examples 1: Find the min element in an array using reduce</h2>



<p class="wp-block-paragraph">When we have an array of objects, <strong><a href="https://kennethlange.com/reduce-in-typescript/">reduce</a></strong> is an easy way to identify the smallest element. For example, if we want to find the blog post with the least number of <em>likes</em>, we can do it like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="typescript" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const posts = [
    {id: 1, title: 'Clean TypeScript', category: 'TypeScript', likes: 91},
    {id: 2, title: 'Stateless React',  category: 'React',      likes: 12},
    {id: 3, title: 'Functional Core',  category: 'TypeScript', likes: 65}
];

const worstPost = posts.reduce((worstPost, post) => worstPost.likes &lt; post.likes ? worstPost : post);

console.log(worstPost.title); // Output: "Stateless React"</pre>



<h2 class="wp-block-heading">Example 2: Find the max element in an array using reduce</h2>



<p class="wp-block-paragraph">When we have an array of objects, <strong><a href="https://kennethlange.com/reduce-in-typescript/">reduce</a></strong> is an easy way to identify the largest element. For example, if we want to find the blog post with the most <em>likes</em>, we can do it like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="typescript" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const posts = [
    {id: 1, title: 'Clean TypeScript', category: 'TypeScript', likes: 91},
    {id: 2, title: 'Stateless React',  category: 'React',      likes: 12},
    {id: 3, title: 'Functional Core',  category: 'TypeScript', likes: 65}
];

const bestPost = posts.reduce((bestPost, post) => bestPost.likes > post.likes ? bestPost : post);

console.log(bestPost.title); // Output: "Clean TypeScript"</pre>



<h2 class="wp-block-heading">Example 3: Make an array unique using reduce</h2>



<p class="wp-block-paragraph">If we have a non-unique array of objects, we can use <strong><a href="https://kennethlange.com/reduce-in-typescript/">reduce</a></strong> to make it unique. For example, if we want to see a unique list of categories used in a number of blog posts, we can do it like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="typescript" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const posts = [
    {id: 1, title: 'Clean TypeScript', category: 'TypeScript', likes: 91},
    {id: 2, title: 'Stateless React',  category: 'React',      likes: 12},
    {id: 3, title: 'Functional Core',  category: 'TypeScript', likes: 65}
];

const uniqueCategories = posts
    .map(post => post.category)
    .reduce((categories, c) => categories.includes(c) ? categories : [...categories, c], new Array&lt;string>());

console.log(uniqueCategories); // Output: ["TypeScript", "React"]</pre>



<p class="wp-block-paragraph">The behavior is similar to <strong>SELECT DISTINCT category FROM Posts</strong> in SQL.</p>



<p class="wp-block-paragraph">In fairness, using a <strong>Set</strong> (and not <strong>reduce</strong>) is a better choice in this use case where we are using an array of values (and not objects):</p>



<pre class="EnlighterJSRAW" data-enlighter-language="typescript" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const posts = [
    {id: 1, title: 'Clean TypeScript', category: 'TypeScript', likes: 91},
    {id: 2, title: 'Stateless React',  category: 'React',      likes: 12},
    {id: 3, title: 'Functional Core',  category: 'TypeScript', likes: 65}
];

const categories = [ ...new Set(posts.map(post => post.category))];

console.log(categories); // Output: ["TypeScript", "React"]</pre>



<h2 class="wp-block-heading">Example 4: Imitate SQL Count with Reduce (Map)</h2>



<p class="wp-block-paragraph">I mostly use <strong><a href="https://kennethlange.com/reduce-in-typescript/">reduce</a></strong> as an alternative to SQL&#8217;s aggregate functions, such as the one below:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="sql" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">SELECT category, count(*)
  FROM Posts
 GROUP BY category</pre>



<p class="wp-block-paragraph">Which can be imitated using <strong><a href="https://kennethlange.com/reduce-in-typescript/">reduce</a></strong> like shown below:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="typescript" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const posts = [
    {id: 1, title: 'Clean TypeScript', category: 'TypeScript', likes: 91},
    {id: 2, title: 'Stateless React',  category: 'React',      likes: 12},
    {id: 3, title: 'Functional Core',  category: 'TypeScript', likes: 65}
];

const categories = posts.reduce((categories, post) => categories.set(post.category, (categories.get(post.category) ?? 0) + 1), new Map&lt;string, number>());

categories.forEach((count, category) => console.log(`${category} (count: ${count})`));
// Output:
// "TypeScript (count: 2)"
// "React (count: 1)"</pre>



<h2 class="wp-block-heading">Example 5: Imitate SQL Count with Reduce (Object Props)</h2>



<p class="wp-block-paragraph">If needing to have the result as <strong>object properties</strong> instead of a <strong>Map</strong>, then it can be done like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="typescript" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const posts = [
    {id: 1, title: 'Clean TypeScript', category: 'TypeScript', likes: 91},
    {id: 2, title: 'Stateless React',  category: 'React',      likes: 12},
    {id: 3, title: 'Functional Core',  category: 'TypeScript', likes: 65}
];

const categories = posts.reduce(
    (categories, post) => {
        return {
            ...categories,
            [post.category]: (categories[post.category] ?? 0) + 1
        }
    },
    {} as Record&lt;string, number>
);

console.log(categories.TypeScript); // Output: "2"</pre>



<h2 class="wp-block-heading">Example 6: Imitate SQL Count with Reduce (Array of Objects)</h2>



<p class="wp-block-paragraph">If preferring to have the result as an <strong>array of objects</strong>, then it can done like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="typescript" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const posts = [
    {id: 1, title: 'Clean TypeScript', category: 'TypeScript', likes: 91},
    {id: 2, title: 'Stateless React',  category: 'React',      likes: 12},
    {id: 3, title: 'Functional Core',  category: 'TypeScript', likes: 65}
];

type Category = {
    name: string,
    count: number
}

const categories = posts.reduce(
    (categories, post) => {
        const category = categories.filter(c => c.name === post.category);
        if (category.length === 0) {
            return [...categories, {name: post.category, count: 1}];
        } else {
            const c = {name: category[0].name, count: category[0].count + 1};
            return [...categories.filter(c => c.name !== post.category), c]
        }
    },
    new Array&lt;Category>()
);
console.log(categories.length); // Output: 2

// If you want the array sorted descending
const sortedCategories = categories.sort((a, b) => b.count - a.count);
console.log(sortedCategories[0].name); // Output: "TypeScript"</pre>



<h2 class="wp-block-heading">Example 7: Imitate SQL Sum with Reduce</h2>



<p class="wp-block-paragraph">Sometimes it may also be necessary to SQL&#8217;s <strong>sum</strong> function (instead of <strong>count</strong>):</p>



<pre class="EnlighterJSRAW" data-enlighter-language="sql" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">SELECT category, sum(likes)
  FROM Posts
 GROUP BY category</pre>



<p class="wp-block-paragraph">This can be imitated using <strong><a href="https://kennethlange.com/reduce-in-typescript/">reduce</a></strong> like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="typescript" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const posts = [
  {id: 1, title: 'Clean TypeScript', category: 'TypeScript', likes: 91},
  {id: 2, title: 'Stateless React',  category: 'React',      likes: 12},
  {id: 3, title: 'Functional Core',  category: 'TypeScript', likes: 65}
];

const categories = posts.reduce((categories, post) => categories.set(post.category, (categories.get(post.category) ?? 0) + post.likes), new Map&lt;string, number>());

categories.forEach((likes, category) => {
    console.log(`${category} (${likes} likes)`)
});
// Output: 
// "TypeScript (156 likes)"
// "React (12 likes)"</pre>



<h2 class="wp-block-heading">Example 8: Add TypeScript Types to Reduce</h2>



<p class="wp-block-paragraph">One of the things I like most about TypeScript is the compiler&#8217;s ability to automatically infer types from code; however, if wanting to add explicit types to a <strong><a href="https://kennethlange.com/reduce-in-typescript/">reduce</a></strong> function, then it can be done like this: </p>



<pre class="EnlighterJSRAW" data-enlighter-language="typescript" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">type Post = {
    id: number,
    title: string,
    category: string,
    likes: number
}

const posts: Post[] = [
    {id: 1, title: 'Clean TypeScript', category: 'TypeScript', likes: 91},
    {id: 2, title: 'Stateless React',  category: 'React',      likes: 12},
    {id: 3, title: 'Functional Core',  category: 'TypeScript', likes: 65}
];

const totalLikes = posts.reduce&lt;number>((likes: number, post: Post) => likes += post.likes, 0);

console.log(totalLikes); // Output: "168"</pre>



<p class="wp-block-paragraph">Hope you liked this post and some of the examples were useful. If you know someone who might like this post, please share it<img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f60a.png" alt="😊" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Reduce in TypeScript</title>
		<link>https://kennethlange.com/reduce-in-typescript/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Sat, 10 Dec 2022 09:21:14 +0000</pubDate>
				<category><![CDATA[TypeScript]]></category>
		<guid isPermaLink="false">https://kennethlange.com/?p=1018</guid>

					<description><![CDATA[The basic idea of the Array.prototype.reduce() function is to reduce an array to a single value. For example, reduce an&#8230;<p><a href="https://kennethlange.com/reduce-in-typescript/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">The basic idea of the <strong>Array.prototype.reduce()</strong> function is to <em>reduce</em> an array to a single value. For example, <em>reduce</em> an array of integers into their combined sum.</p>



<p class="wp-block-paragraph">In other words, instead of calculating the <strong>sum of an array of numbers</strong> like:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="typescript" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const integers = [1, 2, 3];

let sum = 0;
for (let i = 0; i &lt; integers.length; i++) {
  sum += integers[i];
}

console.log(sum); // Output: "6"</pre>



<p class="wp-block-paragraph">Then, <strong>reduce</strong> can be used to sum an array of integers like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="typescript" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const integers = [1, 2, 3];

const sum = integers.reduce((sum, integer) => sum + integer, 0);

console.log(sum); // Output: "6"</pre>



<p class="wp-block-paragraph">When using <strong>reduce</strong>, there are three key elements involved:</p>



<ol class="wp-block-list">
<li>An <strong>array</strong> with elements that should be reduced to a value, such as the <strong>integers</strong> array in the example above.</li>



<li>An <strong>initial value</strong> of the variable that will eventually be returned as the result of the reduce function. The initial value is <strong>0</strong> in the sum example above.</li>



<li>A <strong>function</strong> that is called for each element in the array, so in the sum example above it would be called three times. The function has two parameters:
<ol class="wp-block-list">
<li><strong>previousValue</strong> (renamed to <strong>sum</strong> in the example above): The accumulated result of the processing so far. When the function is called on the first element in the array, then previousValue has the value specified in initial value (0 in the example above). <em>After that previousValue will hold the return value of the previous element that the function was called for. </em></li>



<li><strong>currentValue</strong> (renamed to <strong>integer</strong> in the example above): The array element that is currently being processed. The function will be called once for each element in the array.</li>



<li><strong>Return value:</strong> The function should return the new accumulated result of the processing. The return value will then be provided in the <strong>previousValue</strong> parameter when processing the next element in the array.</li>
</ol>
</li>
</ol>



<p class="wp-block-paragraph">As can be seen in the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce" target="_blank" rel="noreferrer noopener">documentation</a> there are more optional parameters, but one can get pretty far with the parameters above.</p>



<h2 class="wp-block-heading"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Tip 1: Leave out the initial value</h2>



<p class="wp-block-paragraph">When calling <strong>reduce</strong>, the initial value can be left out and then the first array element is used as the initial value. For example, to join an array of strings:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="typescript" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const titles = ['Clean TypeScript', 'Stateless React', 'Functional Core'];

const joinedTitles = titles.reduce((joinedTitles, title) => joinedTitles += `, ${title}`);

console.log(joinedTitles); // Output: "Clean TypeScript, Stateless React, Functional Core"</pre>



<p class="wp-block-paragraph">I tend <em>not</em> to use this, because if it is called on an empty array, then it will fail. TypeScript can of course catch those instances on compile time where this might happen but cannot catch those that originate from an external API or database.</p>



<h2 class="wp-block-heading"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Tip 2: Rename the parameters to match your function </h2>



<p class="wp-block-paragraph">The function given as input to <strong>reduce</strong> is using <strong>previousValue</strong> and <strong>currentValue</strong> as default names of its parameters. It&#8217;s almost always a good idea to rename these parameters to something more precise and fitting for the domain of the function.</p>



<h2 class="wp-block-heading"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Tip 3: Start with defining the return value</h2>



<p class="wp-block-paragraph">If it is a <strong>reduce</strong> function with some complex processing, I tend to start with the <strong>return value</strong> by defining the initial value and then work backwards from that.</p>



<h2 class="wp-block-heading"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Tip 4: Learning by doing </h2>



<p class="wp-block-paragraph"><strong>Reduce</strong> can be a bit more difficult to learn than <strong>map</strong>, <strong>filter</strong>, and the other array functions, and I think the best way to learn reduce is simply to copy/paste some of the examples from this post (and from <a href="https://kennethlange.com/reduce-in-typescript-examples/">my post with reduce examples</a>) into<a href="https://www.typescriptlang.org/play/" target="_blank" rel="noreferrer noopener"> TypeScript Playground</a> to get some hands-on experience, <em>learning-by-doing</em> and all that.</p>



<p class="wp-block-paragraph">In the <a href="https://kennethlange.com/reduce-in-typescript-examples/">next post</a>, I will add a number of examples of using <strong>Reduce</strong> to solve a number of common scenarios. Stay tuned!<img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f680.png" alt="🚀" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Scale Engineering Teams</title>
		<link>https://kennethlange.com/how-to-scale-engineering-teams/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Sat, 10 Sep 2022 09:33:32 +0000</pubDate>
				<category><![CDATA[Tech Leadership]]></category>
		<category><![CDATA[ScaleUp]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=916</guid>

					<description><![CDATA[This is an opinionated blog post about my experiences with scaling engineering teams, and my preferences for each level of&#8230;<p><a href="https://kennethlange.com/how-to-scale-engineering-teams/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">This is an opinionated blog post about my experiences with scaling <a href="https://www.kennethlange.com/how-to-structure-your-engineering-teams/">engineering teams</a>, and my preferences for each level of the scale-up journey. All <a href="https://www.kennethlange.com/wrong-cto-profiles-for-a-scale-up-part-1/">CTOs are different</a>, and the scaling journey will always reflect the CTO, the company, and what they are developing, so this post is not intended as immutable laws, but merely as inspiration.</p>



<h2 class="wp-block-heading">Level 1: One Team</h2>



<p class="wp-block-paragraph">My rule of thumb is to have a single engineeering team for as long as possible. In practical terms, this means as long as there are less than 10&#8217;ish members of the engineering, I keep it as one team. The reason is to avoid the overhead of having multiple teams and to maximize the benefits of smallness (low overhead, instant communication, fast decisions) for as long as possible.</p>



<p class="wp-block-paragraph">I don&#8217;t really think too much about defining <em>leads</em> or other roles at this level, and I strongly prefer Full-Stack Engineers (or <a href="https://www.kennethlange.com/domain-knowledge-beats-code-expertise/">Full-Stack Product Engineers</a>), rather than front-end or back-end developers, simply to be able to move as fast as possible.</p>



<h2 class="wp-block-heading">Level 2: Multiple Teams</h2>



<p class="wp-block-paragraph">As some point at the end of seed funding or start of Series A, the number of engineers in the SaaS will exceed 10 people, and one needs to start to think of having multiple teams.</p>



<p class="wp-block-paragraph">My strong preferen here is to use <a href="https://www.kennethlange.com/team-pattern-the-product-team/">Product Teams</a>, rather than <a href="https://www.kennethlange.com/team-pattern-the-technology-team/">Technology Teams</a>, to align the teams with the product portfolio and with what&#8217;s important for the business. For example, I&#8217;d prefer to have a car booking and billing team, rather than a frontend and backend team.</p>



<p class="wp-block-paragraph">It&#8217;s kind of like when Uncle Bob talked about <em>Screaming Architecture</em> (in his fine book, <em>Clean Architecture</em>), meaning that when you look at the architecture you should know whether it the architecture for a social media platform, a car rental service, or computer game. I think it&#8217;s the same when it comes to team structure: the org chart should scream what this department is developing, not what technologies are used.</p>



<h2 class="wp-block-heading">Level 3: Team of Teams</h2>



<p class="wp-block-paragraph">At some later point in the scale-up journey, the company may reach a size (in the ballpark of around 100&#8217;ish members of engineering) where all teams cannot report directly to the CTO and you need another organizational layer.</p>



<p class="wp-block-paragraph">For this I much prefer some variation of the so-called <a href="https://blog.crisp.se/wp-content/uploads/2012/11/SpotifyScaling.pdf">Spotify model</a> where related product teams (squads) are group into tribes — and avoid things like SAFe and related methodologies favored by <a href="https://www.kennethlange.com/wrong-cto-profiles-for-a-scale-up-part-2/">non-technical CTOs</a>. Again, to minimize bureacracy, align the teams with the business success, and maximize speed.</p>



<p class="wp-block-paragraph">Now, what are your experience with scaling engineering teams? <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f680.png" alt="🚀" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Startup CTO versus Executive CTO</title>
		<link>https://kennethlange.com/startup-cto-versus-executive-cto/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Sat, 03 Sep 2022 08:12:06 +0000</pubDate>
				<category><![CDATA[Tech Leadership]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=904</guid>

					<description><![CDATA[CTO is one of those funny titles that can refer to so many different jobs. The title has a certain&#8230;<p><a href="https://kennethlange.com/startup-cto-versus-executive-cto/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">CTO is one of those funny titles that can refer to so many different jobs. The title has a certain prestige among technical-minded people, but can mean so many things, from <strong>Chief Architect</strong> (with little/no people management), to <strong>IT Manager</strong> (in non-SaaS companies), to <strong>Head of Development</strong> (in many SaaS companies).</p>



<p class="wp-block-paragraph">Even when the CTO is a Head of Development in a SaaS, I still see two different types:</p>



<ol class="wp-block-list">
<li>One is the <strong>Startup CTO</strong> whose &#8220;development department&#8221; consists of a single small team (&lt;10 people) in a young, fast-growing company.</li>



<li>The other is the <strong>Executive CTO</strong> who is responsible for a large development department (&gt;40 people) that consists of multiple teams where typically only managers and/or directors report directly to the Executive CTO.</li>
</ol>



<p class="wp-block-paragraph">I often see discussions about what the CTO should do — <em>should the CTO do hands-on coding?</em> —go haywire, because people think of the two different profiles. And what makes good sense for the Startup CTO may not make much sense for the Executive CTO, and vice versa.</p>



<p class="wp-block-paragraph">In my mind, the greatest differentiater between the Executive CTO and Startup CTO is that the Executive CTO is a <strong>manager of managers</strong>, so Executive CTO is mostly about <strong>scale</strong>, and the Startup CTO is mostly about <strong>speed</strong>.</p>



<p class="wp-block-paragraph">However, while there are tons of things that differentiate the two types of CTO — and I&#8217;ve been both — I think what unites them is that the person will be <strong>the last line of defence</strong> for all technical issues and decisions in the company, and this is super important!</p>



<p class="wp-block-paragraph">In a large SaaS you may have a <strong>Director of Engineering</strong> who is responsible for 30-40 engineers, but can still escalate tough choices to the VP or CTO level, whereas a Startup CTO may have just 5 engineers, but no one to escalate to and must just &#8220;deal with it&#8221; whatever it is.</p>



<p class="wp-block-paragraph">This means that whether you’re a Startup CTO or an Executive CTO, then an unusually high degree of <strong>resourcefulness</strong> will be required to flourish in the job<img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f680.png" alt="🚀" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Wrong CTO Profiles for a Scale-Up: Part 2</title>
		<link>https://kennethlange.com/wrong-cto-profiles-for-a-scale-up-part-2/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Sat, 20 Aug 2022 11:12:20 +0000</pubDate>
				<category><![CDATA[CTO]]></category>
		<category><![CDATA[SaaS]]></category>
		<category><![CDATA[ScaleUp]]></category>
		<category><![CDATA[StartUp]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=845</guid>

					<description><![CDATA[In the first post in this mini-series about wrong CTO profiles for a scale-up, I talked about why a too&#8230;<p><a href="https://kennethlange.com/wrong-cto-profiles-for-a-scale-up-part-2/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In the <a href="https://www.kennethlange.com/wrong-cto-profiles-for-a-scale-up-part-1/">first post</a> in this mini-series about wrong CTO profiles for a scale-up, I talked about why a <em>too</em> technical CTO often fails. Funnily enough, the other CTO profile who often fails does this because the CTO is <em>not</em> not technical enough.</p>



<p class="wp-block-paragraph">The story I often hear goes like this: As a reaction to having had <a href="https://www.kennethlange.com/wrong-cto-profiles-for-a-scale-up-part-1/">a too technical CTO</a>, a SaaS hired a non-technical CTO who can communicate with non-technical stakeholders, enjoys project management, and knows how to deal with people. These are all good things! But their new CTO didn&#8217;t really know technical stuff and didn&#8217;t come from a developer background — but was a project manager or some sort of business consultant — and due to this lack of technical insights, the CTO has made some terrible technical decisions and/or hires, and the company is now in deep troubles.</p>



<p class="wp-block-paragraph">The lack of technical insights means that the CTO cannot make informed <strong>technical decisions</strong>. Even people who are smart, rational, and math-savvy — but <em>not</em> software engineers — often fail when it comes to this. Paul Graham (co-founder of Y Combinator) once gave <a href="http://www.paulgraham.com/gh.html">this advice</a> to non-technical technical leaders: <strong>Give up!</strong> His reason was simply that a non-technical manager cannot recognize great engineers or great technical work, and that is why they fail.</p>



<p class="wp-block-paragraph">Having smart engineers who can advice the non-technical CTO about technical decisions also never really works in practice&#8230; As Joel Spolsky (co-founder of Stack Overflow) <a href="https://www.joelonsoftware.com/2006/06/16/my-first-billg-review/">once wrote</a>, it reminded him of someone who doesn&#8217;t know how to surf, try to surf, with advisors standing on the beach shouting to the poor surfer what to do, while the surfer falls into the water again and again.</p>



<p class="wp-block-paragraph">A CTO who is <em>not</em> coming from a developer background is almost always a problem, but in mature, established software houses, it is less of a short-term problem, because the CTO can cruise on for years on the existing architecture and tech stack — and just focus on pumping out new features and not shaking the boat — before it turns into a serious problem (but when it becomes a problem, it does so with a vengeance and needs a a big, nasty, re-platforming project, but that&#8217;s a story for another blog post).</p>



<p class="wp-block-paragraph">In most SaaS scale-ups, even those without complex tech, making the right technical decisions and the right technical hires is critical to the survival of the company. While the company is scaling up, its CTO needs to decide what components from its original startup codebase (which almost always have a fair bit of duct tape and hacks) to keep, what parts to replace, and what to replace them with.</p>



<p class="wp-block-paragraph">I&#8217;ve see at least four developer archetypes who want to influence those decisions, and <em>not</em> necessarily in a way that&#8217;s right for the company, and the CTO needs to be able to challenge them:</p>



<ul class="wp-block-list">
<li><strong>Not-Invented-Here (NIH) Engineer:</strong> Sometimes as part of the scale-up journey, a company hires a new engineer who concludes that everything that was written before they joined the company is hopeless and beyond repair, so all code needs to be rewritten from scratch. Given that reading code is much more difficult than writing code, this is a common conclusion. For example, I know one company where a senior developer had started a naive project of rewriting the whole codebase from scratch, without really understanding the existing codebase or the size of such a project. Another typical <em>not-invented-here</em> example is an ecommerce scale-up that I talked with who had decided, in 2021, that they needed to write their own web shop software from scratch, because they didn&#8217;t think any of the existing solutions fitted with their pretty common needs (!) and now their web shop was missing essential features, like a mobile app, because they were too busy developing and maintaining other features that are available in most standard ecommerce solutions.</li>



<li><strong>Cloud-Vendor Salesperson:</strong> Smooth-talking salesperson from vendors such as AWS or Google Cloud who is trying to push more of their services into the scale-up&#8217;s tech stack, and offer all kinds of temptings-sounding offers, like you get Google&#8217;s own engineers to work on your product for free, if you just migrate to them. Of course, their aim is to create vendor lock-in so you stay with their services for good.</li>



<li><strong>New-Tech Engineer: </strong>Working with new technologies is super fun, so often there is at least one software engineer in the company who thinks it could be really awesome to use some new, uncommon technology. One example I recall from some years ago is a SaaS where one of the developers was really passionate about <a href="https://www.rust-lang.org" target="_blank" rel="noreferrer noopener">Rust</a> (which I totally get!), but Rust didn&#8217;t really have any benefits that were <em>business critical</em> to the SaaS, the developer simply thought it would be a cool language to learn and do something in. The problem was that it was almost impossible for the SaaS to hire experienced Rust developers, which made scaling up their company much slower than it needed to be.</li>



<li><strong>Opposite-Tech Engineer:</strong> An engineer who always wants to use the opposite tech of the ones the company is using. If the company uses AWS, they want to use Google Cloud (and if you had used Google Cloud, they wanted to use AWS). If you use <a href="https://www.kennethlange.com/creating-a-web-app-in-angular-2-0/">Angular</a>, they want to use React; and so on. In most cases, if techs are more or less comparable, then switching tech is just an expensive project that adds little value to the customers while draining the time of the company&#8217;s most senior engineers, so there needs to be a pretty good reason to start such a tech migration.</li>
</ul>



<p class="wp-block-paragraph">In my experience, then scale-ups need to make so many important technical hires and decisions — where a wrong choice can put the company&#8217;s health at risk as neither funding nor time is unlimited — that they need a CTO who can listen to and challenge all of the persons above, and separate signals from noise, and at the end of the day be able to confidently make the right technical decision for their company.</p>



<p class="wp-block-paragraph">That&#8217;s it! Hope you enjoyed this little series on the wrong CTO profiles for a scale-up<img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f680.png" alt="🚀" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Wrong CTO Profiles for a Scale-Up: Part 1</title>
		<link>https://kennethlange.com/wrong-cto-profiles-for-a-scale-up-part-1/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Sat, 13 Aug 2022 09:10:35 +0000</pubDate>
				<category><![CDATA[CTO]]></category>
		<category><![CDATA[SaaS]]></category>
		<category><![CDATA[ScaleUp]]></category>
		<category><![CDATA[StartUp]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=781</guid>

					<description><![CDATA[When I talk with scale-ups where their CTO didn't work out, then in 90% of the cases it's because the CTO was one of two profiles.]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">When I talk with scale-ups where their CTO didn&#8217;t work out, then in 90% of the cases it&#8217;s because the CTO was one of these profiles:</p>



<ol class="wp-block-list">
<li>The CTO was the <em>too</em> technical co-founder</li>



<li>The CTO was a non-technical, project manager type</li>
</ol>



<p class="wp-block-paragraph">In this post I&#8217;ll talk about the first type, and in the next post about the second one.</p>



<p class="wp-block-paragraph">For the first CTO type, the story usually goes like this: A customer-focused CEO and a technical-focused CTO joined forces and founded a start-up together. And they succeeded!!<img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f680.png" alt="🚀" class="wp-smiley" style="height: 1em; max-height: 1em;" /> They discovered a great product/market fit and secured funding to grow to the next level. Regardless of everything else written in this post, then this is pretty amazing! And it&#8217;s only something like 1% of start-ups who get this far, so anyone who gets so far has my respect.</p>



<p class="wp-block-paragraph">But after the product/market fit was discovered, and customers started to rush onboard, and the company got funding to scale up, then the CTO started to struggle with being a technical leader, being responsible for a growing team of engineers, instead of being a brilliant individual engineer.</p>



<div class="wp-block-group"><div class="wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow">
<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">For example, one SaaS scale-up I helped, the technical co-founder came into the office in the morning — without saying hello to anybody, not even those on his team — and walked to his desk, put on his noise-canceling earphones, and coded away for the entire day, just like he had successfully done in the start-up phase. His personal productivity was prodigal, but he wasn&#8217;t a leader of the technical team or even interested in the people on &#8220;his&#8221; team or what they were working on — which absolutely did <strong>not</strong> <strong>scale</strong> and prevented the company from growing as fast as it should, and it had even allowed a new, faster competitor to catch-up with them and gain significant market shares.</p>
</blockquote>
</div></div>



<p class="wp-block-paragraph">The situation can often be tricky, because the CTO might <strong>lack self-insights</strong> of their own strengths and weaknesses, while simultaneously own a significant part of the company, which is only fair, considering the CTO&#8217;s instrumental role in getting the company this far, but it means you need to get the CTO onboard before you can make changes to their job.</p>



<p class="wp-block-paragraph">I&#8217;ve seen companies where they tried to move the technical co-founder into a <strong>Chief Architect</strong> role, without people management, but I must admit that while it sounds like a tempting solution, I haven&#8217;t really seen it being <em>that</em> successful in the real world&#8230;</p>



<p class="wp-block-paragraph">Another option, if the company needs it, is to ask the CTO to build a new <strong>adjacent product</strong> or module from scratch, which is what the CTO has done better than 99% of other founders, and then the company can build a new team around the scale-up&#8217;s original product and scale that up. While I&#8217;ve seen this work out in the short-term, the problem is often that the company&#8217;s focus gets spread over too many products, which is a bridge too far for most scale-ups.</p>



<p class="wp-block-paragraph">The optimal situation is of course that the CTO gets an <strong>Aha! experience</strong><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" />and realizes that being a super-productive engineer isn&#8217;t the same as being a technical leader — as the saying goes: <em>what got you here, won&#8217;t get you there</em> — and based on this insight does one of the following:</p>



<ol class="wp-block-list">
<li>The CTO actually wants to become a technical leader (and is fine with designing and coding becoming an ever-smaller part of the job) and wants to get the coaching necessary to build up the necessary leadership skills.</li>



<li>The CTO moves to a senior engineer role and reports to a new CTO (often tricky and requires a fairly experienced CTO to make this work out).</li>



<li>The CTO simply decides to move on and found a new start-up, if the start-up phase is the part of a company&#8217;s journey that they enjoy the most, and then takes another tour in the carousel.</li>
</ol>



<p class="wp-block-paragraph">Having had a <em>too</em> technical CTO, some companies overreact by hiring a <strong>non-technical CTO</strong>, typically a project manager type, who&#8217;s good at the non-technical stuff, but in the next post I will explain why this profile is an equally bad choice for a scale-up. Stay tuned! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f680.png" alt="🚀" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Domain Knowledge &gt; Code Expertise</title>
		<link>https://kennethlange.com/domain-knowledge-beats-code-expertise/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Sat, 06 Aug 2022 11:58:49 +0000</pubDate>
				<category><![CDATA[Others]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=760</guid>

					<description><![CDATA[It's wrong to think of a programmer as being a "translator" who merely translates a specification, written by someone else, into computer code.]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">It&#8217;s unhealthy, unsustainable, and wrong to think of a programmer as being a &#8220;translator&#8221; who <em>merely</em> translates a specification, written by someone else, into computer code.</p>



<p class="wp-block-paragraph">There is no historical precedent from other professions of working this way. If we look at other professionals who master an advanced <em>body of knowledge</em>, like attorneys or a medical doctors, then they discuss directly with their client, without an intermediate layer of managers or bureaucracy, and listen to their client&#8217;s needs and apply their body of knowledge to help solve the client&#8217;s problem in the best possible way.</p>



<p class="wp-block-paragraph">From a supply/demand perspective, then if we look at writing code as an isolated skill, then this is becoming easier and easier to learn (due to easier languages, richer framework, and amazing tooling), which means that the barrier of entry is continually lowered, which increases the supply and competition.</p>



<p class="wp-block-paragraph">Moreover, the rise of low-code/no-code tools gives even more people the ability to perform coding-like tasks. And a last thing that boosts the supply is that the COVID lockdown taught even the most conservative company that working remotely is feasible, so they can hire in many new locations. Right now we have a hot job market, but historically those things don’t last forever, unfortunately.</p>



<p class="wp-block-paragraph">So in a world where the supply of generic coding skills increases, how can programmers differentiate themselves from the competition?</p>



<p class="wp-block-paragraph">I think the key is to learn the business of their company — and then start to think of themselves as, <em>primarily</em> someone who solves business problems, and <em>secondarily</em>, someone who solves these problems by writing code.</p>



<h2 class="wp-block-heading">How does a programmer create value?</h2>



<p class="wp-block-paragraph">Code has no inherent business value in itself. Code only adds value when it contributes to solving a business problem; for example, automating a task, which previously required expensive manual work, which reduces the operating cost of the company, which increases the bottom line.</p>



<p class="wp-block-paragraph">Now, it would be easy to say that a Business Analyst / Product Manager should be the one understanding the business and then handover a detailed specification over to the programmer who can then translate the specification into code.</p>



<p class="wp-block-paragraph">However, in my view, a natural evolution is already happening: </p>



<ul class="wp-block-list">
<li>A company used to have backend developers, frontend developers, and maybe even DBAs.</li>



<li>This made sense because everything was really complicated; for example, memory leaks in C++ could give even the most chilled programmer gray hairs, and operating an Oracle Database was so non-intuitive that it required a dedicated, full-time specialist to keep it running.</li>
</ul>



<p class="wp-block-paragraph">However, everything is becoming easier, from automatic memory management to DBaaS.</p>



<h2 class="wp-block-heading">Why we got Product Teams and Full-Stack Engineers</h2>



<p class="wp-block-paragraph">During the last ten years, we have seen the rise of Full-Stack Engineers and <a href="https://www.kennethlange.com/team-pattern-the-product-team/">Product Teams</a> (instead of <a href="https://www.kennethlange.com/team-pattern-the-technology-team/">Technology Teams</a>), because:</p>



<ol class="wp-block-list">
<li>It&#8217;s actually possible to master the full stack, because developing comparable functionality becomes easier and easier as we evolve forward.</li>



<li>Because a full-stack engineer can deliver complete features (rather than a &#8220;layer&#8221; of it), which is insanely important from a business perspective, because this increases speed to market — as there are fewer handovers and less coordination — which means that the feature can get into production faster and generate business value sooner and seize business opportunities before they vanish or are seized by a competitor.</li>
</ol>



<h2 class="wp-block-heading">The coming rise of the Full-Stack Product Engineer</h2>



<p class="wp-block-paragraph">I think the next natural evolutionary step after the Full-Stack Engineer role is that the Full-Stack Engineer and Product Manager (or Business Analyst, at first) will slowly start to merge together into a single role, meaning that we end up with a person who can talk with the business or customers to understand their problem, and also write the code to solve the problem. In my view this is a natural state of things that aligns with how other professions with an advanced body of knowledge operates.</p>



<h2 class="wp-block-heading">I feel the need — the need for speed!</h2>



<p class="wp-block-paragraph">Why is this beneficial? Two reasons: (1) Because we can get an <em>even</em> faster speed to market &#8211; from idea to production &#8211; due to even fewer handovers and even less coordination &#8211; and speed becomes evermore important to businesses in our fast-changing world, and (2) many &#8220;micro decisions&#8221; need to be taken when writing code and the more an engineer knows about the business context, the better (micro) decisions they can take.</p>



<p class="wp-block-paragraph">So my recommendation is to really <a href="https://www.kennethlange.com/6-ways-to-increase-your-industry-knowledge/">learn the business domain</a> that you are writing code for. Don’t wait for someone to teach you, actively pursue the knowledge. This will both make you more valuable to your business right now, because you can make better &#8220;micro decisions&#8221; and can communicate more easily. And you will be aligned with the long-term evolutionary trend of software development.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Drag and Drop in Pure TypeScript and React</title>
		<link>https://kennethlange.com/drag-and-drop-in-pure-typescript-and-react/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Sat, 18 Sep 2021 09:54:13 +0000</pubDate>
				<category><![CDATA[TypeScript]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=721</guid>

					<description><![CDATA[When you need to move on-screen objects, drag and drop is such a direct, intuitive, and just plain nice way&#8230;<p><a href="https://kennethlange.com/drag-and-drop-in-pure-typescript-and-react/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">When you need to move on-screen objects, drag and drop is such a direct, intuitive, and just plain nice way of doing it compared to clicking buttons and other indirect ways of moving objects.</p>



<p class="wp-block-paragraph">Initially, drag and drop functionality was really tricky to support in HTML and JavaScript due to the document-oriented background of these technologies, but HTML5 introduced a super easy way to add drag and drop functionality to web apps.</p>



<p class="wp-block-paragraph">Basically, we just need to follow the four steps below to enable drag and drop. The first two steps enable the dragging, and the last two steps enable the dropping:&nbsp;</p>



<ol class="wp-block-list">
<li>Set the <strong>draggabe</strong> attribute on the HTML element that you wish to drag.</li>



<li>Add an <strong>onDragStart</strong> event handler to the draggable HTML element to store its identifier when it&#8217;s being dragged.</li>



<li>Add an <strong>onDragOver</strong> event handler to the HTML element that should be able to receive dropped elements.</li>



<li>Add an <strong>onDrop</strong> event handler to the HTML element that can receive dropped element to handle what should happen when a dragged element is dropped onto it.</li>
</ol>



<p class="wp-block-paragraph">In the follow sections, we will look into each of these steps. Rather than using a library, such as react-dnd, we will implement the steps in pure TypeScript and React.</p>



<h2 class="wp-block-heading">1. Set the Draggable Attribute</h2>



<p class="wp-block-paragraph">By default, HTML elements are not draggable, so to make one draggable, you need to set its draggable attribute to true, as shown below:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="html" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;div id="d1" draggable="true">Drag me&lt;/div>
&lt;div id="d2" draggable="true">Or me!&lt;/div></pre>



<p class="wp-block-paragraph">This ensures that the HTML element can be dragged. Obviously, it&#8217;s no fun to drag an element without having anywhere to drop it, but it&#8217;s a good start.</p>



<h2 class="wp-block-heading">2. Add an onDragStart Event Handler</h2>



<p class="wp-block-paragraph">Unless you only have one draggable element, you will need to store an identifier of the element that is currently being dragged, so you can identify the element if it&#8217;s being dropped.</p>



<p class="wp-block-paragraph">For this purpose, we add an <strong>onDragStart</strong> event handler to the draggable elements:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="html" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;div id="d1" draggable="true" onDragStart={handleDragStart}>Drag me&lt;/div>
&lt;div id="d2" draggable="true" onDragStart={handleDragStart}>Or me!&lt;/div></pre>



<p class="wp-block-paragraph">The event handler itself can be pretty straight forward:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="typescript" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const handleDragStart = (event: React.DragEvent&lt;HTMLDivElement>) => {
    event.dataTransfer.setData('text', event.currentTarget.id);
}</pre>



<p class="wp-block-paragraph">Here we&#8217;re using <strong>DragEvent</strong>, a synthetic React event, as the type of the argument to the event handler, and specifying that it must be a <strong>Div</strong> element. Depending on the use case, we can pick a more generic type, such as <strong>HTMLElement</strong> (event: React.DragEvent), or leave out the template entirely (event: React.DragEvent). Personally, I like the types to be as precise as possible to catch as many errors as possible upfront.</p>



<p class="wp-block-paragraph">Inside the event handler, we call <strong>setData</strong> to store the identifier of the dragged element in the <a href="https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer" target="_blank" rel="noreferrer noopener">dataTransfer</a> object, which can later be read by the HTML element that the dragged element is dropped upon. The first argument (&#8216;text&#8217;) given to <strong>setData</strong> is the type of the identifier given as the second argument, and not a property name.</p>



<p class="wp-block-paragraph"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Tip:</strong> Remember that <strong>id</strong> attributes on HTML elements must be globally unique, not just unique for the element type, so a simple number (such as a numeric primary key from a database) might not be enough in itself to guarantee uniqueness, but you can prefix it with something to ensure uniqueness; for example, <code class="" data-line="">task_${task.id}</code>.</p>



<h2 class="wp-block-heading">3. Add an onDragOver Event Handler</h2>



<p class="wp-block-paragraph">By default, an HTML element cannot receive dropped elements, so we must override this behavior on the HTML element that should receive dropped elements.</p>



<p class="wp-block-paragraph">This is easily done by adding an event handler that simply prevent the default behavior:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="typescript" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const enableDropping = (event: React.DragEvent&lt;HTMLDivElement>) => { 
    event.preventDefault();
}</pre>



<p class="wp-block-paragraph">Add the event handler to the receiving HTML element:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="html" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;div onDragOver={enableDropping}>Drop Area&lt;/div></pre>



<h2 class="wp-block-heading">4. Add an onDrop Event Handler</h2>



<p class="wp-block-paragraph">When an HTML element is being dropped, we want to perform some kind of action. This can be done in an <strong>onDrop</strong> event handler on the element that receives the dropped element:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="html" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;div onDragOver={enableDropping} onDrop={handleDrop}>Drop Area&lt;/div></pre>



<p class="wp-block-paragraph">And add the code to the HTML element that can receive dropped elements:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="typescript" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const handleDrop = (event: React.DragEvent&lt;HTMLDivElement>) => {
    const id = event.dataTransfer.getData('text');
    console.log(`Somebody dropped an element with id: ${id}`);
}</pre>



<p class="wp-block-paragraph">We use the <strong>getData</strong> method to retrieve the identifier that we set in <strong>onDragStart</strong> event handler, so we can do something meaningful with the dropped object.</p>



<p class="wp-block-paragraph">That&#8217;s basically all the code we need to enable basic drag and drop functionality in a web app. The code snippets in previous sections are collected into a complete example in the next section.</p>



<h2 class="wp-block-heading">Example 1: A Minimal Drag and Drop Example</h2>



<p class="wp-block-paragraph">For copy/paste convenience, the complete minimal is listed below:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="typescript" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const handleDragStart = (event: React.DragEvent&lt;HTMLDivElement>) => {
    event.dataTransfer.setData('text', event.currentTarget.id);
}

const enableDropping = (event: React.DragEvent&lt;HTMLDivElement>) => { 
    event.preventDefault();
}
    
const handleDrop = (event: React.DragEvent&lt;HTMLDivElement>) => {
    const id = event.dataTransfer.getData('text');
    console.log(`Somebody dropped an element with id: ${id}`);
}

return (
    &lt;div>
        &lt;div id="d1" draggable="true" onDragStart={handleDragStart}>Drag me&lt;/div>
        &lt;div id="d2" draggable="true" onDragStart={handleDragStart}>Or me!&lt;/div>
        &lt;div onDragOver={enableDropping} onDrop={handleDrop}>Drop Area&lt;/div>
    &lt;/div>
);</pre>



<h2 class="wp-block-heading">Example 2: Highlight the Drop Area when an HTML is Dragged Over</h2>



<p class="wp-block-paragraph">A missing feature in the drag and drop functionality in HTML5 is that there is no CSS pseudo selector (like :hover on mouse over) to highlight an HTML element when another element is being dragged over it. For example, like in MacOS, where a folder is highlighted when a file is being dragged over it.</p>



<p class="wp-block-paragraph">But, fortunately, we can easily simulate this hover-like functionality by using the <strong>onDragEnter</strong> and <strong>onDragLeave</strong> event handlers as shown in the example below:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="typescript" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">const [ dragOver, setDragOver ] = React.useState(false); 
const handleDragOverStart = () => setDragOver(true);
const handleDragOverEnd = () => setDragOver(false);

const handleDragStart = (event: React.DragEvent&lt;HTMLDivElement>) => {
    event.dataTransfer.setData('text', event.currentTarget.id);
}

const enableDropping = (event: React.DragEvent&lt;HTMLDivElement>) => { 
    event.preventDefault();
}
    
const handleDrop = (event: React.DragEvent&lt;HTMLDivElement>) => {
    const id = event.dataTransfer.getData('text');
    console.log(`Somebody dropped an element with id: ${id}`);
    setDragOver(false);
}

return (
    &lt;div>
        &lt;div id="d1" draggable="true" onDragStart={handleDragStart}>Drag me&lt;/div>
        &lt;div id="d2" draggable="true" onDragStart={handleDragStart}>... Or me!&lt;/div>
        &lt;div
            onDragOver={enableDropping}
            onDrop={handleDrop}
            onDragEnter={handleDragOverStart}
            onDragLeave={handleDragOverEnd}
            style={ dragOver ? {fontWeight: 'bold', background: 'red'} : {} }
        >
            Drop Zone
        &lt;/div>
    &lt;/div>
);</pre>



<p class="wp-block-paragraph">That&#8217;s it. Good luck with making your web apps more intuitive with super cool drag and drop functionality.</p>



<p class="wp-block-paragraph">Happy coding! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f680.png" alt="🚀" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p class="wp-block-paragraph">PS. The code is available at GitHub (<a href="https://github.com/kenneth-lange/tsx-drag-and-drop" target="_blank" rel="noreferrer noopener">https://github.com/kenneth-lange/tsx-drag-and-drop)</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>The Functional Core, Imperative Shell Pattern</title>
		<link>https://kennethlange.com/functional-core-imperative-shell/</link>
					<comments>https://kennethlange.com/functional-core-imperative-shell/#comments</comments>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Sat, 27 Mar 2021 07:13:47 +0000</pubDate>
				<category><![CDATA[Design Patterns]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=693</guid>

					<description><![CDATA[The Functional Core, Imperative Shell pattern is just so exciting! 🔥 This pattern enables us to use functional programming for&#8230;<p><a href="https://kennethlange.com/functional-core-imperative-shell/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">The Functional Core, Imperative Shell pattern is just so exciting! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f525.png" alt="🔥" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p class="wp-block-paragraph">This pattern enables us to use <strong>functional programming</strong> for what it does the best, and to use <strong>imperative programming</strong> for all the messy, mutable, side-effectful stuff that most applications also need to do. And what makes this pattern super nice is that it provides a clear separation between the two programming styles, so they can <strong>peacefully coexist</strong> in the same application.</p>



<p class="wp-block-paragraph">The Functional Core, Imperative Shell pattern is similar to Hexagonal Architecture, <a href="https://www.kennethlange.com/ports-and-adapters/">Ports and Adapters</a>, Clean Architecture, and similar styles that, a bit simplified, are characterized by two key architectural attributes:</p>



<ol class="wp-block-list">
<li>There is a <strong>core </strong>with the core business logic, and a <strong>shell </strong>that handles interactions with the outside world, such as persisting data in databases or providing UIs to interact with end users.</li>



<li>The shell can call the core, but the core <em>cannot</em> call the shell and the core is even unaware of the existence of the shell. This is also known as the <strong>Dependency Rule</strong> (see, for example, <a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html" target="_blank" rel="noreferrer noopener">Clean Architecture</a> to learn more about this rule).</li>
</ol>



<p class="wp-block-paragraph">An additional architectural attribute in the Functional Core, Imperative Shell pattern is, unsurprisingly, that the core should be written in a functional style, meaning using immutable values and pure functions. </p>



<p class="wp-block-paragraph">The key objectives in the Functional Core, Imperative Shell pattern is to separate functional code and imperative code, and to minimize the imperative code, so when in doubt whether a piece of functionality belongs in the core or shell, then make it functional and put it in the core.</p>



<p class="wp-block-paragraph"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <em><strong>Book Tip: </strong>If you want to use <strong>Domain-Driven Design</strong> and functional programming (for example, in the Functional Core, Imperative Shell pattern), I can warmly recommend <a href="https://twitter.com/KennethLange/status/1370733250939924481" target="_blank" rel="noreferrer noopener">Domain Modeling Made Functional</a>, a truly awesome book</em> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f44d.png" alt="👍" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p class="wp-block-paragraph">In practice, the core will often be an instance variable in the shell. The shell will call the core with a value and get a new value returned, and then do side-effectful, imperative stuff, like displaying it to a user or storing it in a database, with value returned from the core.</p>



<p class="wp-block-paragraph">If you&#8217;d like to read more about the Functional Core, Imperative Shell pattern, I recommend the links below:</p>



<ul class="wp-block-list">
<li><a href="https://www.destroyallsoftware.com/screencasts/catalog/functional-core-imperative-shell" target="_blank" rel="noreferrer noopener">Functional Core, Imperative Shell</a></li>



<li><a href="https://www.destroyallsoftware.com/talks/boundaries" target="_blank" rel="noreferrer noopener">Boundaries</a></li>



<li><a href="https://news.ycombinator.com/item?id=18043058" target="_blank" rel="noreferrer noopener">Functional core, imperative shell</a> (a Hacker News discussion)</li>



<li><a href="https://github.com/kenneth-lange/ts-functional-core-imperative-shell" target="_blank" rel="noreferrer noopener">Functional Core, Imperative Shell in TypeScript</a> (my demo implementation in TypeScript).</li>
</ul>



<p class="wp-block-paragraph">Thank you for reading. Hope you will find this pattern useful. If you know someone who might enjoy this article, please share it <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f64f.png" alt="🙏" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
					<wfw:commentRss>https://kennethlange.com/functional-core-imperative-shell/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>The Backends for Frontends (BFF) Pattern</title>
		<link>https://kennethlange.com/backends-for-frontends-pattern/</link>
					<comments>https://kennethlange.com/backends-for-frontends-pattern/#comments</comments>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Tue, 28 Apr 2020 16:02:41 +0000</pubDate>
				<category><![CDATA[Design Patterns]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=544</guid>

					<description><![CDATA[Many textbooks assume that your frontend will just call a single, beautiful, and secure API, but in the real-world this&#8230;<p><a href="https://kennethlange.com/backends-for-frontends-pattern/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Many textbooks assume that your frontend will just call a single, beautiful, and secure API, but in the real-world this is rarely the case&#8230;</p>



<p class="wp-block-paragraph">For example, imagine a bank that offers both banking and insurance to its customers. The bank has acquired the insurance business, which already had an insurance solution. The customer master data is stored in a CRM system. So if we were tasked with developing a customer self-service portal for the bank, the portal would need to call three different systems (CRM/Bank/Insurance), with three different protocols, and three different security schemes, just to get a basic overview of a customer&#8217;s engagement with the bank.</p>



<p class="wp-block-paragraph">A common way to overcome this imperfect setup is to create a new backend in front of the real backend(s) and then design the perfect API for the frontend.</p>



<p class="wp-block-paragraph">This is known as the <strong>Backends for Frontends</strong> (BFF) pattern and an example (using our imaginary bank) is shown below:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://www.kennethlange.com/wp-content/uploads/2020/04/backends-for-frontends-pattern.png"><img fetchpriority="high" decoding="async" width="912" height="925" src="https://www.kennethlange.com/wp-content/uploads/2020/04/backends-for-frontends-pattern.png" alt="" class="wp-image-547" srcset="https://kennethlange.com/wp-content/uploads/2020/04/backends-for-frontends-pattern.png 912w, https://kennethlange.com/wp-content/uploads/2020/04/backends-for-frontends-pattern-500x507.png 500w, https://kennethlange.com/wp-content/uploads/2020/04/backends-for-frontends-pattern-768x779.png 768w, https://kennethlange.com/wp-content/uploads/2020/04/backends-for-frontends-pattern-624x633.png 624w" sizes="(max-width: 912px) 100vw, 912px" /></a></figure>
</div>


<p class="wp-block-paragraph">The <strong>Web BFF</strong> in the diagram above can expose a simple <code class="" data-line="">GET /customers/{id}</code> REST operation that our frontend can call instead of dealing with the complexity of calling and integrating three different systems.</p>



<p class="wp-block-paragraph">Beside respecting the <strong>separation of concerns</strong> principle, by separating our presentation logic from our integration logic, we get many more benefits from using the BFF:</p>



<ul class="wp-block-list">
<li><strong>Call the backends in parallel:</strong> We can call the backends in parallel and perhaps respond faster to the end user.</li>



<li><strong>Filter the responses:</strong> We can remove internal or sensitive data, such as an unwanted customer flag, or unnecessary data that just adds complexity to the frontend and drains battery power when parsing on mobile devices.</li>



<li><strong>Transform the responses:</strong> We can transform the responses to the frontend into something more usable, such as translating internal codes to something more descriptive. For example, a code in a job field can be translated from <code class="" data-line="">SH_CLERK</code> to <code class="" data-line="">Shipping Clerk</code>.</li>



<li><strong>Enhanced security:</strong> We can add extra security in the BFF, such as OAuth2, to protect the unsecure backend solutions, and we can implement a single sign on, so the frontend doesn&#8217;t need to deal with different authentication methods in different backend systems.</li>



<li><strong>Handle different protocols:</strong> The BFF can call FTP, SOAP, REST, GraphQL, and other types of services, but still use a single protocol when interacting with the client.</li>



<li><strong>Encapsulate advanced business logic:</strong> Issuing a new insurance policy may be a complex operation that requires multiple service calls, but this can be simplified for the clients into a single end point with only the absolute minimum data in a flat structure.</li>



<li><strong>Caching across clients:</strong> Some of backends may be slow so caching across different clients may be an effective way to deliver acceptable response times to the end users. Moreover, if we need to call usage-based external APIs, it may also be worth caching those responses across clients to reduce the cost.</li>



<li><strong>Protect the client from changes to the backend:</strong> Changes in the backends APIs need not to result in changes in the UI, the changes can be handled in the BFF.</li>



<li><strong>It&#8217;s still just code:</strong> A BFF doesn&#8217;t involve canonical data models, ESBs, or other old-school integration patterns that are complex and time consuming to deal with; it&#8217;s just plain code. Moreover, a change in the BFF will not affect other systems, like with an ESB, so it is better aligned with DevOps and microservice thinking.</li>
</ul>



<p class="wp-block-paragraph">The main drawback of the BFF pattern is that, at least in the beginning, it can seem like extra work for the frontend team (which should be the ones developing and owning the BFF) but it usually pays back if the underlying backends are non-trivial. Remember that there are no technical restrictions to what language / framework we can use for the BFF; if the frontend team is skilled in JavaScript, they may be more comfortable with writing the BFF in Node.js and that&#8217;s perfectly fine.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://kennethlange.com/backends-for-frontends-pattern/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>The Circuit Breaker Pattern</title>
		<link>https://kennethlange.com/the-circuit-breaker-pattern/</link>
					<comments>https://kennethlange.com/the-circuit-breaker-pattern/#comments</comments>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Sat, 18 Apr 2020 08:58:22 +0000</pubDate>
				<category><![CDATA[Design Patterns]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=516</guid>

					<description><![CDATA[When we start using external services in our code, we introduce a whole new range of potential problems, such as&#8230;<p><a href="https://kennethlange.com/the-circuit-breaker-pattern/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">When we start using external services in our code, we introduce a whole new range of potential problems, such as timeouts and service unavailability, that we don&#8217;t need to deal with when using in-memory API calls.</p>



<p class="wp-block-paragraph">For example, a web shop can be designed to scale automatically to handle peak loads, such as Black Friday, but if its core business process depends on an external service that breaks under unexpected loads, then the whole web shop can be brought to its knees, unless we design for this situation.</p>



<p class="wp-block-paragraph">One of the best ways to address this problem is to use the <strong>circuit breaker</strong> pattern, which stops all calls to an external service when that service is unavailable and then the circuit breaker returns an artificial response instead (more on that later).</p>



<p class="wp-block-paragraph">In the Java-based <strong>NewsReader</strong> example in <a href="https://www.kennethlange.com/ports-and-adapters/">the previous blog post</a>, we can add a circuit breaker as a <strong>decorator</strong> around the <strong>Feed</strong> interface as seen in the diagram below:</p>



<figure class="wp-block-image size-large"><img decoding="async" width="755" height="434" src="https://www.kennethlange.com/wp-content/uploads/2020/04/circuit_breaker_java_class_diagram.png" alt="" class="wp-image-519" srcset="https://kennethlange.com/wp-content/uploads/2020/04/circuit_breaker_java_class_diagram.png 755w, https://kennethlange.com/wp-content/uploads/2020/04/circuit_breaker_java_class_diagram-500x287.png 500w, https://kennethlange.com/wp-content/uploads/2020/04/circuit_breaker_java_class_diagram-624x359.png 624w" sizes="(max-width: 755px) 100vw, 755px" /></figure>



<p class="wp-block-paragraph">A pseudocode implementation of the <strong>FeedCircuitBreaker </strong>class is shown below:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">public final class FeedCircuitBreaker implements Feed {
    private Feed feed;
    private List&lt;Post> cache = Collections.emptyList();

    private boolean circuitOpen = true;
    private LocalDateTime circuitRetry;

    public FeedCircuitBreaker(Feed feed) {
        this.feed = Objects.requireNonNull(feed);
    }

    @Override
    public List&lt;Post> getPosts() {
        // Is it time to reopen the circuit and try again?
        if(!circuitOpen &amp;&amp; LocalDateTime.now().isAfter(circuitRetry)) {
            circuitOpen = true;
        }

        if(circuitOpen) {
            try {
                cache = feed.getPosts();
            } catch(Exception e) {
                // Close the circuit and wait 5 minutes before trying again
                circuitOpen = false;
                circuitRetry = LocalDateTime.now().plusMinutes(5);
            }
        }

        return cache;
    }
}</pre>



<p class="wp-block-paragraph">And using the circuit breaker is a matter of decorating an underlying feed:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Feed f = new FeedCircuitBreaker(new TwitterFeed("@KennethLange"));</pre>



<p class="wp-block-paragraph">The tricky part of the circuit breaker pattern is to design the right <strong>fallback strategy</strong> where we need to decide what will happen when the external service is unavailable. There are many different fallback strategies we can choose from, and some of the most common ones are shown below:</p>



<ul class="wp-block-list">
<li><strong>Crash and burn:</strong> We assume errors will not occur and don&#8217;t design for it. For example, we have all seen websites where raw PHP errors are shown directly in the HTML returned to the end users (not recommended, neither from a usability nor security point of view).</li>



<li><strong>Wait and see:</strong> Inform the users that the service is temporarily unavailable and encourage them to try again later. Wikipedia has <a rel="noreferrer noopener" href="https://en.wikipedia.org/wiki/Circuit_breaker_design_pattern" target="_blank">an example</a> of this implemented in PHP.</li>



<li><strong>Alert an operator:</strong> A manual task is created for an operator. For example, to check whether the RSS feed has been moved to a new address.</li>



<li><strong>Empty response:</strong> We return an empty response. For example, if the response from a service is used for displaying product recommendations on a website, then we can return an empty list and let the UI act as if there were no product recommendations.</li>



<li><strong>Default response:</strong> We return a safe default response. For example, in an insurance claims process, we can default the fraud risk to high, to be on the safe side, but otherwise continue with the automated process.</li>



<li><strong>Cached response:</strong> We return the last successful response. Like in the example with the newsreader earlier in this post.</li>



<li><strong>Degraded response:</strong> We use local data to generate a lower quality response as a substitute for the real one. For example, in the insurance claims process in the previous bullet then if it&#8217;s a VIP customer who hasn&#8217;t reported a claim during the last year and the claim amount is less than $1,000 then we consider the fraud risk as being low.</li>



<li><strong>Eventual consistency:</strong> We will synchronize the systems later. For example, if our web shop cannot access the inventory system, we will still take the customer&#8217;s order, put the request in a queue, and update the inventory system when it eventually becomes available again.</li>
</ul>



<p class="wp-block-paragraph">The right fallback strategy is almost always a business decision. For example, issuing motor insurance policies based on partial information may be an unacceptable risk and a <strong>wait and see</strong> strategy should be used. But for a web shop it may be a better fallback strategy to accept the customer’s order, without knowing if we are able to fulfill it, and then send a gift certification if we later realize that we cannot fulfill the order.</p>



<p class="wp-block-paragraph">That&#8217;s it. I hope you enjoy this short post about a design pattern that doesn&#8217;t get all the attention that it deserves.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://kennethlange.com/the-circuit-breaker-pattern/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>The Ports and Adapters Pattern</title>
		<link>https://kennethlange.com/ports-and-adapters/</link>
					<comments>https://kennethlange.com/ports-and-adapters/#comments</comments>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Sat, 11 Apr 2020 07:08:19 +0000</pubDate>
				<category><![CDATA[Design Patterns]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=432</guid>

					<description><![CDATA[Most software solutions today are part of an active ecosystem where calling external services is an integrated part of its&#8230;<p><a href="https://kennethlange.com/ports-and-adapters/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Most software solutions today are part of an active ecosystem where calling external services is an integrated part of its business processes. However, external integrations come with all kinds of headaches, from keeping your code clean, to executing automated tests within a reasonable timeframe, to the tight integration of external services into your code which makes switching vendors hard, if not impossible.</p>



<p class="wp-block-paragraph">The ports and adapters pattern (also known as <a rel="noreferrer noopener" href="https://netflixtechblog.com/ready-for-changes-with-hexagonal-architecture-b315ec967749" target="_blank">hexagonal architecture</a>) is an effective way of addressing these problems. The problem for existing applications is that re-architecting them may not be economically feasible. So a minimalist approach is to use ports and adapters when you call external services, which you do not control, but not necessarily when using external libraries or products, which you do control.</p>



<p class="wp-block-paragraph">The basic concept behind ports and adapters is very simple: You define a <strong>port</strong> that can be used with various <strong>adapters </strong>as long as the adapters conform to the port’s interface. An example from the physical world is the HDMI port in your laptop, which you can connect to any monitor as long as the monitor obeys the HDMI standard.</p>



<p class="wp-block-paragraph">Moving back to software, then a simplified example of using ports and adapters is shown in the Java-based <strong>newsreader</strong> below:</p>



<figure class="wp-block-image size-large"><img decoding="async" width="831" height="491" src="https://www.kennethlange.com/wp-content/uploads/2020/04/c4_adapters-14.png" alt="" class="wp-image-493" srcset="https://kennethlange.com/wp-content/uploads/2020/04/c4_adapters-14.png 831w, https://kennethlange.com/wp-content/uploads/2020/04/c4_adapters-14-500x295.png 500w, https://kennethlange.com/wp-content/uploads/2020/04/c4_adapters-14-768x454.png 768w, https://kennethlange.com/wp-content/uploads/2020/04/c4_adapters-14-624x369.png 624w" sizes="(max-width: 831px) 100vw, 831px" /></figure>



<p class="wp-block-paragraph">The <strong>core </strong>package contains the core logic of the newsreader. I know that the feedreader will need to connect to various newsfeeds, but I don&#8217;t want to pollute my core code with all kind of implementation details, such as storing Twitter client secrets, obeying rate limiting in the API calls, dealing with broken XML in RSS feeds, so I define the <code class="" data-line="">Feed</code> interface that defines the methods that I need a feed to offer.</p>



<p class="wp-block-paragraph">The <code class="" data-line="">Feed </code>interface can be something really simple like the code snippet below:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">public interface Feed {
    List&lt;Post> getPosts();
}</pre>



<p class="wp-block-paragraph">All the implementation details, I keep in the <strong>infrastructure</strong> package where I keep the implementations of different news feeds, such as RSS and Twitter. To avoid polluting the core code with implementation details, the key is to use <strong>inversion of control</strong>, so the core package has no dependencies on the infrastructure package.</p>



<p class="wp-block-paragraph">When your application needs to connect the core code with the infrastructure code, you can use <strong>dependency injection</strong> in your application:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// Initialize the feeds from the infrastructure package
List&lt;Feed> feeds = new ArrayList&lt;>();
feeds.add(new RssFeed("http://feeds.feedburner.com/KennethLange"));
feeds.add(new TwitterFeed("@KennethLange"));

// Inject the feeds into the FeedReader
FeedReader reader = new FeedReader(feeds);
for(Post post : reader.getRecentPosts()) {
    System.out.println(post.getTitle());
}</pre>



<p class="wp-block-paragraph">Beside the benefit of keeping the concerns of <strong>core</strong> and <strong>infrastructure</strong> code separate, you can add new feeds, such as Atom or Google News, without touching the <strong>core</strong> code. If Twitter shutdowns their APIs then you do not end up with dead Twitter code scattered throughout your application, and you can provide other feeds that provide similar content.</p>



<p class="wp-block-paragraph">Another benefit is that your unit tests of the <strong>core</strong> code become much more reliable as you can easily make a fake (or stub) implementation of the <code class="" data-line="">Feed</code> interface for testing purposes. This both means that you no longer need to rely on unreliable infrastructure in your tests and the unit tests will most likely become a lot faster to execute, which will also benefit your continuous integration.</p>



<p class="has-light-gray-background-color has-background wp-block-paragraph"><strong>Beyond Java</strong><br>The basic idea of ports and adapters is that you define an interface and can collaborate with anyone who implements the interface. The concept is not limited to Java or other languages that offer an <code class="" data-line="">interface</code> type. You can even define the interface as a service contract, perhaps in <a href="https://www.kennethlange.com/write-beautiful-rest-documentation-with-swagger/">Swagger</a>, and can then collaborate with any third-party service that implements the contract. This is similar to how <a rel="noreferrer noopener" href="https://www.linkedin.com/pulse/painless-integration-webhooks-kenneth-lange/" target="_blank">webhooks</a> work and would result in a very loose coupling where you would not even need to redeploy your code to support a new service. The difficulty would obviously be to get third parties to support your service contract.</p>



<p class="wp-block-paragraph">When you call external services as part of your business processes, it is usually a good idea to stick in <strong>circuit breaker</strong> to avoid instability from a third-party service to spread to your system, so if the third-party service goes down, then your system doesn’t go down with it. The circuit breaker pattern will be the topic of my next blog post to improve improve the way we use external services in our code.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://kennethlange.com/ports-and-adapters/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>Don&#8217;t Limit Your REST API to CRUD Operations</title>
		<link>https://kennethlange.com/dont-limit-your-rest-api-to-crud-operations/</link>
					<comments>https://kennethlange.com/dont-limit-your-rest-api-to-crud-operations/#comments</comments>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Thu, 08 Nov 2018 19:00:28 +0000</pubDate>
				<category><![CDATA[API Engineering]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=146</guid>

					<description><![CDATA[I think one of the best things about RESTful web services is the Collection Pattern. It&#8217;s a really smart and&#8230;<p><a href="https://kennethlange.com/dont-limit-your-rest-api-to-crud-operations/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[<p>I think one of the best things about RESTful web services is the <strong>Collection Pattern</strong>. It&#8217;s a really smart and developer-friendly way of designing a REST service.</p>
<p>For example, the <strong>Task REST API</strong>&nbsp;below, which is taken from my company&#8217;s REST API, is a typical example of how the collection pattern looks:</p>
<p><img loading="lazy" decoding="async" class="alignnone wp-image-155 size-full" src="https://www.kennethlange.com/wp-content/uploads/2018/10/task_api.png" alt="" width="767" height="250" srcset="https://kennethlange.com/wp-content/uploads/2018/10/task_api.png 767w, https://kennethlange.com/wp-content/uploads/2018/10/task_api-300x98.png 300w, https://kennethlange.com/wp-content/uploads/2018/10/task_api-624x203.png 624w" sizes="auto, (max-width: 767px) 100vw, 767px" /></p>
<p>The collection pattern is so widely adopted that even a REST newbie, who has never seen this API before, will be able to guess the description in the <strong>Task</strong> column based on the content in the <strong>Method</strong> and <strong>Path</strong> columns.</p>
<p>The collection pattern is also really smart from a code perspective, because many frameworks have some sort of <strong>Active Record</strong> implementation on top of the collection pattern, so the framework can automatically wrap the whole REST service in a convenient way.</p>
<p>For example, in the old <strong>AngularJS</strong> framework they had this wonderful $resource factory that you could simply give the URI of a REST service that followed the collection pattern &#8211; and then the $resource factory would automatically figure out the rest (no pun intended!)</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">var Task = $resource('/tasks/:taskId', {taskId: '@id'}); 

var task = new Task(); 
task.description = "Put a man on the moon."; 
task.assignee = "James Webb"; 
task.$save();</pre>
<p>While the collection pattern is really clever and so easy to use &#8211; and the best solution for almost all REST services &#8211; there are some <strong>edge cases</strong> where its CRUD approach just doesn&#8217;t make sense and other patterns should be considered.</p>
<h1>Now it gets controversial&#8230;</h1>
<p>When the web was the new big thing &#8211; and online pet shops were worth hundreds of millions of dollars &#8211;&nbsp;<span style="font-size: 1rem;">you would see web pages with HTML forms like this:&nbsp;</span></p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;form method="POST" action="send_mail.cgi"&gt;
    &lt;input type="text" name="subject"&gt;
    &lt;input type="text" name="message"&gt;
    &lt;input type="submit" value="Send Message"&gt;
&lt;/form&gt;</pre>
<p>While you can long for those innocent days when you could publish code like that on the web and not be flooded with spam; the important thing here is that you can also call the <strong>send_mail.cgi</strong> script directly and use it as a web service; for example, using the small <strong>JQuery</strong> script below:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">var mail = {
    subject: "Man walks on the moon",
    message: "Armstrong and Aldrin become the first men on the moon..."
};

$.post({
    url: "/send_mail.cgi",
    contentType: "application/x-www-form-urlencoded",
    data: mail, success: function() {
        console.log("Mail sent!");
    }
});</pre>
<p>Now, I will argue that <strong>send_mail.cgi</strong> is a RESTful web service (!) even if it&#8217;s a really poorly designed one and a simple <strong>POST /mails</strong>&nbsp;service would have been a lot nicer!</p>
<p>If you finish the demanding, yet satisfying task of reading <a href="https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm">Roy Fielding&#8217;s PhD thesis</a>, which defines the REST architectural style,&nbsp;you will see that it says nothing about limiting our REST services to CRUD operations and&nbsp;it also says nothing about limiting ourselves to the collection pattern&#8230;</p>
<p>In fact, Fielding later wrote <a href="https://roy.gbiv.com/untangled/2009/it-is-okay-to-use-post">a blog post</a> about the use of the POST method in REST, and said, <strong>&#8220;As long as the method is being used according to its own definition, REST doesn’t have much to say about it.&#8221;</strong>&nbsp; And if we read the <a href="https://tools.ietf.org/html/rfc2616#section-9.5">HTTP specification</a> we can see that it doesn&#8217;t limit the use of POST to adding new items to collections &#8211; and if we read the <a href="https://tools.ietf.org/html/rfc3986#section-1.1">URI specification</a> we can see that it doesn&#8217;t limit our URI naming to plural nouns&#8230;</p>
<p>So <strong>POST /send_mail.cgi</strong> is OK from a specification point of view and can be considered RESTful&#8230;</p>
<h1>So what are you saying?</h1>
<p>So what am I saying? Is this the sacking of Rome and we can now all go crazy with <strong>POST /add-new-order.cgi</strong> and&nbsp;<strong>GET /find-my-orders.xml</strong>. No laws! No limits!</p>
<p>Of course not. I still think that the Collection Pattern is the right choice for almost all RESTful web services &#8211; and it should be the default choice for any new RESTful web service &#8211; because it&#8217;s so widely adopted and easily recognizable by most API users.</p>
<p>However, there are <strong>edge cases</strong> where it makes sense to use other patterns, such as the <strong>Controller Pattern</strong>. For example, if I have a REST service for rockets then <em>one does not simply just launch a rocket</em> (or walk into Mordor!) because you need to provide launch codes and the rocket needs to go through multiple stages before actual take-off &#8211; and this goes way beyond just changing the value of a field in the resource representation. So for this scenario I would add a controller subresource:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">/rockets/43/launch-rocket</pre>
<p>When breaking with the Collection Pattern I really like the verb-noun naming of the URI, such as <strong>launch-rocket</strong>. This is without doubts because I read <strong>Code Complete</strong> way too many times (!) but also because it makes it obvious to the API user that it isn&#8217;t a part of the Collection Pattern. On top of that, remember to add a link to controller subresource in the resource representation to make the API user aware that the subresource exists:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">{
    "id": 43,
    "name": "Apollo 11",
    "state": "Ready for launch",
    "_links": {
        "self": {"href": "/rockets/43"},
        "launch-rocket": {"href": "/rockets/43/launch-rocket"} 
    }
}</pre>
<p>This meaning of this post isn&#8217;t to say that the Collection Pattern is bad. In fact, it&#8217;s the right choice for almost all REST APIs and everybody will love you for using it! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> The purpose is to say that <strong>Collection Pattern != REST</strong> and you still have some wriggle room for edge cases that doesn&#8217;t fit neatly into the Collection Pattern without losing your API&#8217;s RESTfulness or the desirable properties that come with this architectural style.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://kennethlange.com/dont-limit-your-rest-api-to-crud-operations/feed/</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
			</item>
		<item>
		<title>Team Pattern #4: The Self-Managed Product Team</title>
		<link>https://kennethlange.com/team-pattern-the-self-managed-product-team/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Sat, 13 Oct 2018 05:23:05 +0000</pubDate>
				<category><![CDATA[Tech Leadership]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=6</guid>

					<description><![CDATA[This is the last post in the blog series about team patterns and it’s all about self-managed product teams. At&#8230;<p><a href="https://kennethlange.com/team-pattern-the-self-managed-product-team/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[<p>This is the last post in the blog series about team patterns and it’s all about self-managed product teams.</p>
<p>At first this team pattern looks similar to the <a href="https://www.kennethlange.com/team-pattern-the-product-team/">product team pattern</a>, but unlike the product team pattern there is no engineering manager directly responsible for the team’s work.</p>
<p>This pattern also looks a little like the <a href="https://www.kennethlange.com/team-pattern-the-matrix-team/">matrix team</a> as the people on the team report to a manager outside of the team, but unlike the matrix team there is no common theme for the engineers who report to an engineering manager.</p>
<p>That is, a single manager is responsible for a diverse group of engineers working with different technologies (e.g., C++, Android, Node.js) and different products areas (e.g., billing, orders, customers) — and there’s no guarantee that two Android Engineers will report to the same manager or that all people on the Orders product team will report to the same manager.</p>
<p>In this team pattern, the manager is less of a traditional manager who directs and supervises work — and more of a career counsler and coach who can advice the engineer.</p>
<p>In this team pattern the leadership of a team can be split into three separate roles:</p>
<ul>
<li><strong>Product Manager:</strong> This role is focused on product leadership, such as talking with customers and preparing product road maps.</li>
<li><strong>Engineering Manager:</strong> This role is focused on people management, such as recruitment, career guidance, building culture, finding and fix interpersonal issues.</li>
<li><strong>Lead Engineer:</strong> This role is focused on technical leadership, such as technical best practices, mentoring, and anticipate the future technical needs of the team.</li>
</ul>
<p>An real-world example of this team pattern is described by Josh Tyler, who is EVP Engineering at <a href="https://www.coursehero.com/" target="_blank" rel="noopener noreferrer">Course Hero</a>, in his fine book <a href="https://www.apress.com/gp/book/9781484211342" target="_blank" rel="noopener noreferrer">Building Great Software Engineering Teams</a>; at his company Course Hero, an online learning website, they’ve organized their teams according to their product areas:</p>
<p><img decoding="async" src="https://www.kennethlange.com/images/course_hero_org_2.png" /></p>
<p>On each product team they have a Lead Engineer who takes care of technical mentoring and guidance, define best practices, and make sure they are followed.<br />
The Lead Engineer works closely with the Product Manager to scope projects, prioritize tasks, and give the team the context necessary to be successful.</p>
<p>Where it starts to divert from the <a href="https://www.kennethlange.com/team-pattern-the-product-team/">product team pattern</a> previous example is that the engineering manager’s role is independent from the Lead Engineers.<br />
The Engineering Manager is responsible for a group of engineers across multiple product teams. The Engineering Manager is no longer involved in technical leadership and<br />
doesn’t supervise the work of the Lead Engineer, but is focused on people management, such as finding and fixing people-related problems.</p>
<p>The roles of Engineering Manager and Lead Engineer are completely independent. So it is possible for a Lead Engineer in one product team to report to an Engineering Manager.<br />
This engineering manager may be part of another product team — as a hands-on engineer — and report to another Lead Engineer for technical matters on that team.</p>
<p>But what do Course Hero do when they have a person who is both talented in people management and technical leadership? They considers those rare people to be precious gems that should be treasured and see them as people with executive potential. But still then, they recommend that the person starts by focusing on one of the two paths (i.e., Lead Engineer or Engineering Manager) and then master the other one later.</p>
<h1>Strengths</h1>
<p>The self-organized product team shares many of the strengths we have seen in the other team patterns.</p>
<p>But a distinct strength is that splitting the engineering manager role into two opens up for a genuine two-track career model with a track for managerial leadership<br />
and another for technical leadership. This is important as most first-rate engineers are not really interested in traditional management, but are deeply passionate about technology, so in this<br />
team pattern they have a career path where they grow without losing their technical edge. This will also make it easier to attract and retain highly skilled technical people<br />
as you don’t expect them to become a traditional manager (and lose that all-important technical edge) or force them to report to a incompetent manager who overrides<br />
their technical decisions due to authority, and not merits.</p>
<p>It may also make hiring easier, which should not be underestimated in a competitive job market, as finding a single candidate who excels in both technical leadership and people management is really tough.</p>
<p><!--A common argument is also that as a manager you should always hire people who are smarter than you. And if you really do this, it doesn&rsquo;t make sense for you to tell them what to do (technical leadership). I think this argument is simplistic. The counter argument is obviously that you hire people who are better than you in some area (Swift programming) but not necessarily in another area (getting a group of passionate and opinionated engineers to agree on a common set of practices).

--></p>
<h1>Weaknesses</h1>
<p>At first sight the clear definition and separation of product, technology, and people leadership roles look attractive — as it makes it real easy to figure out who to ask:</p>
<ul>
<li>Should you upgrade to the latest version of Angular? Ask the Lead Engineer!</li>
<li>Do you dream of becoming a Full-Stack Developer? Talk with your Engineering Manager!</li>
<li>What’s the most important feature to work on right now? Ask the Product Manager!</li>
</ul>
<p>The risk is that in real life many problems doesn’t fit neatly into one of these categories…</p>
<p>For example, the CEO thinks that the team is not developing fast enough:</p>
<ul>
<li>Is that a product thing? Maybe the team is focusing on low-value, low-visible features?</li>
<li>Is it a engineering thing? Maybe there is too much technical debts or poor design?</li>
<li>Is it a people thing? Maybe the people on the team lack skills in the technologies used or their motivation is low?</li>
<li>Is it a mix of these? All of these? Some of these?</li>
</ul>
<p>This will make the debugging of the problem harder — as the debugging may spans multiple areas of responsibility owned by different people — it will make finding and fixing the problem take longer.</p>
<p>From a manager perspective: The primary weakness is that the manager is often no longer involved in engineering, neither as a lead nor as a individual contributor, and if this is the case then his or her engineering skills can quickly deteriorate as things are evolving pretty fast within computing these days (it’s a <a href="https://en.wikipedia.org/wiki/Red_Queen%27s_race" target="_blank" rel="noopener noreferrer">Red Queen’s race</a>!) and the manager is in high danger of fast becoming a dinosaur that suggests solutions that made perfect sense… on mainframes! Or thinking that ASP Classic and React are more of less the same… I mean they are just web development frameworks, right? <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>The knock-on effect of losing one’s technical instinct is that it can lead to poor judgement.</p>
<p>Of course, these risks can be mitigated — especially with good collaboration and some general curiosity about what’s happening in one’s field — but left unattended they may turn into issues.</p>
<p>That’s it! I hope you enjoy this little blog series on team patterns!</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Team Pattern #3: The Product Team</title>
		<link>https://kennethlange.com/team-pattern-the-product-team/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Sat, 06 Oct 2018 06:07:47 +0000</pubDate>
				<category><![CDATA[Tech Leadership]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=14</guid>

					<description><![CDATA[It’s time for the next episode in this blog series on team patterns! It has been slightly delayed, because I&#8230;<p><a href="https://kennethlange.com/team-pattern-the-product-team/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[<p>It’s time for the next episode in this <a href="https://www.kennethlange.com/team-patterns-how-to-structure-an-engineering-team/">blog series</a> on team patterns!</p>
<p>It has been slightly delayed, because I got a last-minute invite to present at <a href="http://www.tiatechnology.com/events-2018/tcc-2018/" target="_blank" rel="noopener noreferrer">TCC 2018</a> (our annual conference for customers and partners) and to host a roundtable there as well. Both great experiences <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> You can see <a href="https://www.linkedin.com/feed/update/urn:li:activity:6450293732343373824/" target="_blank" rel="noopener noreferrer">a nice photo on LinkedIn</a> where I’m rehearsing together with Christian (our CEO).</p>
<p>But enough about my everyday work and back to the blog series <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>This post is about the <strong>product team pattern</strong>!</p>
<p>At first sight a product team is very similar to <a href="https://www.kennethlange.com/team-pattern-the-matrix-team/">a matrix team</a>. You organize a team around a product area and take all the different roles needed to build the product and put them inside this team.</p>
<p>The big difference from a matrix team is that all team members, regardless of their role, report to the same line manager. So it doesn’t matter whether a team member is a designer, frontend developer, backend developer; everybody on the team reports to the same line manager.</p>
<p>The motivation for doing this is to simplify decision making (i.e., the buck stops at the line manager regardless of the functional area) and to encourage people on the team to learn more about the business that the product area serves (as they will work within that area for a long time, rather than on the matrix team, where they are more likely to be moved to a completely new product area).</p>
<p>When <a href="https://hbr.org/2017/11/how-we-reorganized-instagrams-engineering-team-while-quadrupling-its-size" target="_blank" rel="noopener noreferrer">Instagram</a> moved away from the technology team patterns, which we saw in an earlier post in this series, they adopted the product team pattern, as you can see in the org chart below:</p>
<p><img decoding="async" src="https://www.kennethlange.com/images/instagram_engineering.jpg" /></p>
<p>As you can see in the org chart above, Instagram organized their team around the product areas (such as content creation). To handle general stuff that doesn’t fit neatly into a product area, they added two platform teams: The Core Client team for developing the container (or app shell) that the product teams develop their product areas within, and a Core Infrastructure team that handles servers and other infrastructure.</p>
<p>At <a href="https://medium.com/airbnb-engineering/engineering-culture-at-airbnb-345797c17cbe" target="_blank" rel="noopener noreferrer">Airbnb</a> they have made an interesting variation on this pattern: They let their product teams focus on a specific persona, such as guest or host, instead of more traditional product areas, such as billing or booking. This makes it really easy for Airbnb to establish business-related KPIs for the team.</p>
<p>The line manager in this team pattern is often called an engineering manager to show that it is not a manager for a specific technology area (such as mobile) or a specific discipline (such as QA), but rather a manager responsible for all engineering within a product area.</p>
<p>The product team pattern tends to grow leaders who can bring different disciplines together and make them build a unified product where all the pieces fit nicely together. And it encourages leaders to focusing on building a product that actually solves a business problem. This is also the motivation for many organizations who use this team pattern: It aligns the engineering teams’ success much more closely with the company’s success and it becomes much easier to define a business-related KPI for the team (compared to the <a href="https://www.kennethlange.com/team-pattern-the-technology-team/">technology team pattern</a>).</p>
<p>Another interesting dynamic is that companies, which move away from technology teams and to product teams, is that full-stack developers with a good understand of the product area tend to replace the technical specialists (e.g., experts in one layer of the tech stack) as the rock stars of the development organization.</p>
<p>The reason is that a specialist can only typically build partial features. For example, a Django developer who can develop the backend functionality, but doesn’t not know React so cannot finish the frontend part of the feature.</p>
<p>But the developer will report to a line manager responsible for the whole product area (and not just a single technology) and who is motivated towards shipping whole features, and hence, more likely to reward people who can actually deliver whole features.</p>
<p>This dynamic is further accelerated if the company uses continuous deployment and is in a business where speed to market matters (which is most businesses).</p>
<h1>Strengths</h1>
<p>An advantage of a product team over a technology team is that the team is much closer aligned with business success. The team will <i>not</i> feel like a success if their product has just flunked a major public review — even if their code is so beautiful that it would make Jon Bentley shed a tear.</p>
<p>In continuation of this, it is also my experience that more and more software engineers no longer really fit the old computer geek stereotype, who just wanted to be left alone and code. Now they also want to see their product succeed in the market and make meaningful contributions towards that. As in <a href="https://www.anecdote.com/2008/07/the-stonecutters-cathedral-builder/" target="_blank" rel="noopener noreferrer">the old parable about the three stonecutters</a>, they are no longer satisfied with merely cutting stones, they want to build grand cathedrals!</p>
<p>To an even higher degree than with the matrix team, the product team is more likely to build a unified product and have better collaboration across disciplines and lower the risk of a “us-versus-them” culture.</p>
<p>Another advantage of the product team over the matrix team is that decision making becomes much easier as there is only a single line manager involved when a decision needs to be taken or impediment needs to be escalated.</p>
<p>All this usually really contribute to the team’s ability to iterate very fast and launch new product features quickly; and contributes positive to the team’s autonomy.</p>
<p>A caveat is that many of these strengths may be nullified if the team has strong dependencies outside the team’s control. These dependencies could be organizational (like external reviews or approvals) or technical (like an architecture that is a big ball of mud and any change to the codebase can have side effects anywhere else so all teams must coordinate their work).</p>
<h1>Weaknesses</h1>
<p>A serious risk with product teams — especially compared to technology teams — is that they may pay less attention to technical excellence.</p>
<p>There can be several reasons for this:</p>
<ol>
<li>Engineers may become too focused on market success at the expense of engineering excellence. Especially if there is a strong and opinionated product manager or customer.</li>
<li>Each team may become a silo (reporting to a single line manager) and there can only be so many senior engineers within a single team. So, for example, if the team only has a single junior Android engineer who will make sure that the quality of his or her code is satisfying? Or making sure he or she knows the best Android blogs to follow?</li>
</ol>
<p>Similarly, there is also a higher risk of code duplication. That is, several product teams may code the same functionality in their individual codebases (which may or may not be a problem depending on your belief system).</p>
<p>Another risk compared to <a href="https://www.kennethlange.com/team-pattern-the-matrix-team/">matrix teams</a> is that it may become more difficult to move people between teams. When an engineer changes team in the matrix, he or she continues with the same line manager. But in product team pattern, he or she will change line manager as well, which may be a major change. So there may be more resistance, both the engineer might like his or her current line manager and not want to change and start all over with a new manager. Plus some manager have empire tendencies and may be less willing to “give away” an engineer for good. The consequence of this may be that the company is not allocating its people to its highest priorities or biggest opportunities.</p>
<p>Another risk compared to <a href="https://www.kennethlange.com/team-pattern-the-technology-team/">technology teams</a> is that recruitment may be tougher. It is easier to explain to an Angular engineer that it would be great to be part of an Angular team compared to being part of a Life Insurance product team. Even with the matrix organization you can tell the engineer that he or she will report to a manager well-versed in that area. You can mitigate this by explaining why this area is interesting from a technical point of view or important to society at large.</p>
<p>Some companies brand their product teams (at least in job ads) as full-stack team, and given it is cool to be a full-stack developer, the thinking is that it will be easier to recruit people for a full-stack team compared to a Life Insurance team.</p>
<p>From a manager perspective, my experience (as having been both a development manager and an engineering manager) is that being an engineering manager is a more demanding job. It is not because the job is difficult from a technical point of view, it is just that the responsibility is broader. You will essentially become a mini VP of Engineering for a small development department.</p>
<p>You will also have a more direct impact on the business, which you cannot shy away from. That is, as a development manager (for a technology team) you can say that the product is perfect from a technical point of view and it is not your fault that it cannot sell. Due to the broader scope of the role there are also many more things that can go wrong. You will be responsible for things outside of your primary area of expertise but will be responsible for them anyway.</p>
<p>Finally, as a manager your technical skills will most likely erode faster than in the other team patterns. You will be responsible for multiple technologies, such as backend, frontend, data — and have people management on top of that. The rapid pace of technological progress only accelerates this; for example, you were an expert in AngularJS and then they release Angular 2 and all your hard-earned skills become obsolete. And this is not only happening in one layer of the stack, but on all layers, so keep up with everything can become pretty tough.</p>
<p>Given this broad scope of responsibility for the engineering manager — from people management to technical leadership — some companies keep the product team but split the engineering manager role into two: One person will be responsible for technical leadership (i.e., a lead engineer) and one person will be responsible for people management (i.e., a people manager).</p>
<p>This pattern, where the engineering manager role is split into two, will be the topic for the next post in this <a href="https://www.kennethlange.com/team-patterns-how-to-structure-an-engineering-team/">blog series</a>. Stay tuned!</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Team Pattern #2: The Matrix Team</title>
		<link>https://kennethlange.com/team-pattern-the-matrix-team/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Tue, 25 Sep 2018 04:41:12 +0000</pubDate>
				<category><![CDATA[Tech Leadership]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=16</guid>

					<description><![CDATA[This is the third post in my blog series on team patterns, and this time we will look at the&#8230;<p><a href="https://kennethlange.com/team-pattern-the-matrix-team/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[<p>This is the third post in <a href="https://www.kennethlange.com/team-patterns-how-to-structure-an-engineering-team/">my blog series</a> on team patterns, and this time we will look at the matrix team pattern.</p>
<p>A matrix team is a temporary product (or project) team, which is made up of specialists from different functional areas. The idea with the cross-functional nature of the team is to increase collaboration between different functions to create better products and faster releases.</p>
<p>An old-school example of this team pattern is Microsoft Solutions Framework (MSF), which was hot back when Microsoft ruled the (software) world:</p>
<p><img decoding="async" src="https://www.kennethlange.com/images/matrix_team2.png" /></p>
<p>A feature team is usually focused on a product area and will typically last for the duration of a product release or longer. For example, in Microsoft you would have multiple feature teams working on Microsoft Excel, and one of them would focus on Excel Macros.</p>
<p>An example of the members of a feature team could a <a href="https://www.joelonsoftware.com/2009/03/09/how-to-be-a-program-manager/" target="_blank" rel="noopener noreferrer">Program Manager</a> (responsible for <a href="https://www.joelonsoftware.com/2000/10/02/painless-functional-specifications-part-1-why-bother/" target="_blank" rel="noopener noreferrer">functional specifications</a> and project management within the team), 4 developers, and 2 testers. The Program Manager will tell the developers and testers which is the most important feature to work on and handle the planning and coordination of the feature team’s work.</p>
<p>However, developers report to a development manager who provides guidelines on how they should do their job (e.g., job descriptions, development process, engineering practices, coding standards) and be responsible for people management (e.g., promotions, training, move to a new team, etc.) — and it is the same for the other roles, so program managers report to a group program manager, and testers report to a test manager.</p>
<p>The underlying idea is that it will encourage cross-functional collaboration when specialists are <i>literally</i> on the same team, but the specialists will continue to report to a functional manager who is an expert in their area of expertise.</p>
<h1>Tuning the Matrix</h1>
<p>The most common parameters to tune in this team pattern are the influence of the line manager on the team’s work (degree of team autonomy) and the duration of the matrix team (short-lived versus long-lived).</p>
<h2>Yammer: Very short-lived matrix teams</h2>
<p>A modern variation of this team pattern is used by <a href="http://firstround.com/review/Why-Yammer-believes-the-traditional-engineering-organizational-structure-is-dead/" target="_blank" rel="noopener noreferrer">Yammer</a>, a social network for enterprises. A key difference between Yammer and Microsoft is that Yammer continually deploy new features to production and don’t have major product release like Microsoft used to have for their shrink-wrap products.</p>
<p>Yammer’s developers share the ownership of the entire codebase, so there is no thing such as “my code” or “my module”. Each time a task needs to be performed on the codebase, they establish a temporary team for this specific task. When the task is done the code is released to production and the task force is disbanded and developers are free again to join new ad-hoc team to address new tasks.</p>
<p>The thinking is that this is highly agile, and people will not be limited to work on a single product area but can quickly go wherever there is the biggest need for them.</p>
<p>The development manager is responsible for developers within his or her technical area, such as Ruby on Rails, Java, or React. But the development manager is no longer defining guidelines for how the developers should work, but instead a coach who is focus on turning his or her developers into top-notch experts in their given technology.</p>
<h2>Spotify: Long-lived, autonomous matrix teams</h2>
<p>At <a href="https://blog.crisp.se/wp-content/uploads/2012/11/SpotifyScaling.pdf" target="_blank" rel="noopener noreferrer">Spotify</a>, an online music player, they take a different approach and encourage long-lived, stable matrix teams (which they call “squads”). Their reasoning is that it takes a long time to master a product area, such as Spotify Radio, and mastery is needed to build an awesome product for their users.</p>
<p>They also empower their matrix teams and give them greater autonomy than many more traditional matrix organizations.</p>
<p>However, Spotify still have line managers (which they call “chapter leads”), but with the important twist that the line manager is also an active member of a matrix team (for example, as a back-end developer) to make sure he or she stay in touch with reality.</p>
<h1>Strengths</h1>
<p>The primary strength of the matrix team (compared to the <a href="https://www.kennethlange.com/team-pattern-the-technology-team/">technology team pattern</a> from the previous post) is that it fosters much closer collaboration across functional disciplines. Now the developers and testers are part of the same team; especially, if the program manager successfully makes a shared vision for the product area.</p>
<p>On top of that being a cross-functional team means that all the necessary skills will be immediately available within the team, so there won’t be these gaps between the teams which we saw in the technology team pattern. This improves time to market:</p>
<p><img decoding="async" src="https://www.kennethlange.com/images/matrix_team_time_to_market.png" /></p>
<p>It also encourages developers and testers to learn more about the business domain, such as banking or medicine, that the matrix team is working in. This is really useful when it is a highly complex business domain with lots of counter-intuitive business rules. For simple domains, such as social networks or blogging, it may be less important.</p>
<p>It also brings engineers closer to the business and makes it easier to see how they contribute to the success of the company, while they can still continue to seek mastery within their chosen technology and continue to report to a line manager who appreciates and understands their technical work. The line manager also enforces alignment and quality across teams, and the engineers will have a second opinion (and supporter) in case of a powerful and persuasive program manager on the team or they feel uncomfortable with the decisions taken within the team.</p>
<p>The matrix organization also scales well and can be used for delivering very large products. Microsoft released many of their greatest hits, such as Windows and Microsoft Office, using this team pattern. They were even able to compete with young startups, such as Netscape, while using this model. Obviously, Microsoft used some dirty business tricks to win the browser war against Netscape, but they would not have been able to compete with Netscape if they had not been able to keep up with Netscape’s development speed.</p>
<h1>Weaknesses</h1>
<p>In theory, a matrix team has a high degree of autonomy, but in practice multiple line managers will often enforce controls that limit the team’s autonomy and the team will need to consult with the line managers before trying anything too radical.</p>
<p>There is also a risk that work process inside the team will turn into small waterfalls with extensive handovers between the disciplines inside the team. This can happen when the line manager is not actually part of the team but defines the process that his or her people must follow within the team.</p>
<p>There is also a risk that the line managers may not see the big picture and start to suboptimize for their functional area. For example, the test manager wants to introduce NASA-like quality controls, while the customers are actually happy with the current quality level and is much more interested in getting new features quicker (at the current quality level).</p>
<p>Many developers who worked in a matrix team feel like they have two managers (i.e., the development manager and the program manager) and they often receive conflicting signals about what is important. For example, the program manager says that the developer can skip the unit testing to meet the deadline, but the development manager says that unit tests must be written for all new code — and the developer is caught in the middle. Unclear or overlapping responsibilities are a frequent source of conflict and frustration in a matrix organization.</p>
<p>Decision making related to how the team works may even turn into a lengthy process as multiple line managers may need to be involved in a single decision. For example, the development manager wants to introduce static code analysis (and pay the technical debts it reveals), which should be a pure development activity. But the program manager feels that it will delay the development activities already on the team’s roadmap, so she wants to be involved. The test manager feels that it is an initiative related to quality, and hence, he should have a say in it, and incorporate it as part of an overall test strategy.</p>
<p>To address these weaknesses, some engineering organizations introduced product teams where they would continue to organize teams around product areas to harvest the benefits of cross-functional teams, but to boost the team’s autonomy and speed up decision making, they decided to drop the matrix organization (with multiple line managers) and instead have the all people on a product team — regardless of their specialties — report to the same line manager.</p>
<p>We will look at this pattern in the next post in this <a href="https://www.kennethlange.com/team-patterns-how-to-structure-an-engineering-team/">blog series</a> on team patterns. Stay tuned!</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Team Pattern #1: The Technology Team</title>
		<link>https://kennethlange.com/team-pattern-the-technology-team/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Sat, 08 Sep 2018 07:45:07 +0000</pubDate>
				<category><![CDATA[Tech Leadership]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=18</guid>

					<description><![CDATA[This is the second post in my blog series about team patterns, and it’s about the technology team pattern. A&#8230;<p><a href="https://kennethlange.com/team-pattern-the-technology-team/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[<p>This is the second post in <a href="https://www.kennethlange.com/team-patterns-how-to-structure-an-engineering-team/">my blog series</a> about team patterns, and it’s about the technology team pattern.</p>
<p>A technology team is focused on a technical area, such as front-end or back-end, and all members of the team are specialists in that area. So there will be no product managers, QA specialists, or engineers specialized in other technologies on the team. All members of the team report to a manager who is also a specialist in this particular technical area.</p>
<p>For example, it could be a mobile team with a number of mobile developers reporting to a mobile development manager:</p>
<p><img decoding="async" src="https://www.kennethlange.com/images/mob_team.png" /></p>
<p>When there are multiple technology teams, such as a mobile team and a back-end team, there is usually very little (if any) code shared between the teams. This is because the code is often written in different languages/framework (e.g., Swift versus Python) and exists in different code repositories. The interaction between the teams will often happen through <a href="https://www.kennethlange.com/what-are-restful-web-services/">REST APIs</a> or similar.</p>
<p>A real-world example of this team pattern is early <a href="https://hbr.org/2017/11/how-we-reorganized-instagrams-engineering-team-while-quadrupling-its-size" target="_blank" rel="noopener noreferrer">Instagram</a> (around 2015) where they had split their engineering organization into three development teams (they eventually moved away from this setup, but more about that in a later post):</p>
<p><img decoding="async" src="https://www.kennethlange.com/images/instagram_team.png" /></p>
<p>The reporting lines in such an organization is based on expertise. In other words, a mobile developer will <strong><i>not</i></strong> report to back-end development manager, but to the mobile development manager.</p>
<p>The managers in such an organization is likely to be a senior engineer who has been promoted into management, and now also takes care of people management on his or her team. The manager may still be writing code (or at least have the ability to do so). It is also likely that the manager will handle project management for the team’s work and coordination with other teams.</p>
<p>The rock star in such an engineering organization is likely be a technical specialist measured by some technical standard, such as mastering all the advanced features of the chosen language, or writing the most elegant, concise code.</p>
<h1>Strengths</h1>
<p>The primary strength of the technology team is its technical mastery, which is likely to be higher than in any of the other team patterns which we will explore in the following posts in this blog series.</p>
<p>The team’s codebase is likely to be of a high quality and take full advantage of the latest advancements within the chosen technology — and there is likely to be little technical debts.</p>
<p>It can also be easier to recruit technical experts for such a team. For example, if an engineer is intensely passionate about Django then the idea of working in a Django team, reporting to a Django manager and being surrounded by Django engineers is pretty attractive by default.</p>
<p>Finally, the team’s manager is likely to be highly competent in the work that the team performs, which is key to high job satisfaction according to <a href="https://hbr.org/2016/12/if-your-boss-could-do-your-job-youre-more-likely-to-be-happy-at-work" target="_blank" rel="noopener noreferrer">recent research</a>. This also means that the manager can evaluate the engineers based on merit, and not some measure which can be easily faked (like who stays the longest in the office). The manager will also be able to provide detailed coaching, such as how to write better code and be aware when an engineer is ready to be promoted to the next level.</p>
<h1>Weaknesses</h1>
<p>A common problem for engineering organizations which use the technology team pattern is that time to market (for new features) tends to be slow.</p>
<p>The reason is that one team may finish its part of the feature fast, but the next team might be busy with something else and cannot pick up the task any time soon — as shown in the diagram below:</p>
<p><img decoding="async" src="http://www.kennethlange.com/images/time_to_market.png" /></p>
<p>This means that work queues up between the teams. The cost of a feature may not be higher in actual development time, but it can be very expensive in calendar time.</p>
<p>This problem should not be underestimated. Time to market is hugely important for most businesses. In Lean thinking, unfinished features are expensive inventory that cost the company money, because they don’t generate business value until it’s in production and being used by the end-user.</p>
<p>This team pattern will also nudge you towards phased (or waterfall) development where each team finishes its part of the work before passing it on to the next team. This will discourage iterative development and feedback loops — and when mistakes start to occur due to limited communication between the teams, the handovers are likely to become elaborate and time consuming — and it can even lead to a destructive “us-versus-them” mentality between the teams.</p>
<p>In an attempt to overcome the weaknesses of technology teams, some engineering organizations introduced cross-functional matrix teams. The thinking was that this would lead to improved collaboration between functions (e.g., product management, development, testing) because they would now <i>literally</i> be the same (matrix) team. On top of that, the expectation was also that time to market would improve, because when a matrix team takes on a new feature it will have all the necessary skills inside the team to finish it!</p>
<p>So in the next post in this <a href="https://www.kennethlange.com/team-patterns-how-to-structure-an-engineering-team/">blog series</a>, we will explore the matrix team pattern. Stay tuned!</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Team Patterns: How to Structure an Engineering Team?</title>
		<link>https://kennethlange.com/team-patterns-how-to-structure-an-engineering-team/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Sat, 01 Sep 2018 07:47:34 +0000</pubDate>
				<category><![CDATA[Tech Leadership]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=21</guid>

					<description><![CDATA[This is the first post in a blog series about how top-performing software companies are organizing their engineering teams. You&#8230;<p><a href="https://kennethlange.com/team-patterns-how-to-structure-an-engineering-team/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[<p>This is the first post in a blog series about how top-performing software companies are organizing their engineering teams.</p>
<p>You don’t need to network a lot before you realize that software companies are organizing their teams in very different ways.</p>
<p>But after you’ve heard about a few dozens companies, you start to detect patterns. You start to realize that even though there are lots of small variations then their team structures can all be boiled down to a handful of general patterns.</p>
<p>In my experience there are four general team patterns that most companies follow. Yes, they have tweaked them to fit their circumstances, but the overall idea behind the pattern remains the same:</p>
<ol>
<li><strong>Technology Team:</strong> The team is formed around a technology, such as Android. For example, a team of mobile developers who build and maintain a mobile app.</li>
<li><strong>Matrix Team:</strong> The developers report to a Development Manager, but they are “lend out” to cross-functional product or project teams where they do their daily work.</li>
<li><strong>Product Team:</strong> The team is oriented around a product area, such as billing. It’s cross-functional, but all people on the team, regardless of their specialization, report to the same line manager.</li>
<li><strong>Self-Managed Product Team:</strong> The team is oriented around a product area. But the management of the team is divided into technical leadership, typically handled by an Engineering Lead on the team, and people management, typically handled by an Engineering Manager outside the team.</li>
</ol>
<p>My plan is that each post in this blog series will explore one of these team patterns in depth to identify its strengths and weaknesses — and then spice the whole thing up with plenty of examples of top-performing companies who are actually using the team pattern in the real-world.</p>
<p>The blog series will continue over the next month. I’ll add links to the posts in the series below when they have been published:</p>
<ol>
<li><a href="https://www.kennethlange.com/team-patterns-how-to-structure-an-engineering-team/">Team Patterns: How to Structure an Engineering Team?</a></li>
<li><a href="https://www.kennethlange.com/team-pattern-the-technology-team/">Team Pattern #1: The Technology Team</a></li>
<li><a href="https://www.kennethlange.com/team-pattern-the-matrix-team/">Team Pattern #2: The Matrix Team</a></li>
<li><a href="https://www.kennethlange.com/team-pattern-the-product-team/">Team Pattern #3: The Product Team</a></li>
<li><a href="https://www.kennethlange.com/team-pattern-the-self-managed-product-team/">Team Pattern #4: The Self-Managed Product Team</a></li>
</ol>
<p>You can <a target="_blank" href="https://feedburner.google.com/fb/a/mailverify?uri=KennethLange&amp;loc=en_US" rel="noopener noreferrer">subscribe to my blog</a> to automatically get an email when the next post is published.</p>
<p>If you have any questions or comments to this blog series, feel free to send me an <script>document.write(atob("PGEgaHJlZj1tYWlsdG86aGVsbG9Aa2VubmV0aGxhbmdlLmNvbT9zdWJqZWN0PVRlYW0lMjBQYXR0ZXJucz5lbWFpbDwvYT4="));</script>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Model Workflows in REST APIs</title>
		<link>https://kennethlange.com/how-to-model-workflows-in-rest-apis/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Sat, 03 Dec 2016 08:57:43 +0000</pubDate>
				<category><![CDATA[API Engineering]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=34</guid>

					<description><![CDATA[REST Services are awesome for performing basic CRUD operations on database tables, but they get even more exciting when you&#8230;<p><a href="https://kennethlange.com/how-to-model-workflows-in-rest-apis/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[<p>REST Services are awesome for performing basic CRUD operations on database tables, but they get even more exciting when you realize that they can also be used for modeling workflows and other advanced scenarios.</p>
<p>To show this point, let’s take the blog post workflow below and expose it as a <a href="https://www.kennethlange.com/what-are-restful-web-services/">RESTful Web Service</a>:</p>
<p><img decoding="async" class="img-responsive center-block" src="../images/blog_workflow.png"></p>
<p>There are lots of ways you can implement this, so in the following sections we will try three different approaches and take a look at the pro’s and con’s of each of them.</p>
<p>Let’s get started!</p>
<h1>1. Use an Attribute for the Workflow’s State</h1>
<p>The easiest way to model the blog workflow is just to store the workflow state as an attribute on the blog post resource:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="json">{
    "id": 54301,
    "status": "Draft",
    "title": "7 Things You Didn’t Know about Star Wars",
    "content": "George Lucas accidentally revealed that…"
}</pre>
<p>If a client wants to move the blog post to a new state, it just updates the <strong>status</strong> attribute to the desired state.</p>
<p>It’s an easy solution and the popular blogging software WordPress is basically using this approach in their <a href="http://v2.wp-api.org/reference/posts/" target="_blank" rel="noopener noreferrer">REST API</a>.</p>
<p>But when you start to dig deeper into it, you realized that it comes with some serious drawbacks.</p>
<p>The first is that the front-end engineer who writes the client code is forced to search through the API documentation to see what values can be used in the <strong>status</strong> attribute. This conflicts with the idea that REST Services should be self-describing and not relying on out-of-band documentation.</p>
<p>But this drawback can be fixed by adding a <a href="https://www.kennethlange.com/7-tips-for-designing-a-better-rest-api/">metadata service</a> where the client can get a list of all legal values for the status attribute.</p>
<p>A more serious drawback is that the engineer also needs to look in the API documentation to see what workflow transitions are possible (i.e. can you jump directly from <strong>Draft</strong> to <strong>Published</strong>?) and code all these workflow rules in the client code.</p>
<p>This means that business logic is leaking into the client, so if there are many different types of clients (mobile apps, websites, etc.) then each client will be forced to re-implement the workflow logic in their own code, which is not a cost-effective way to do software development.</p>
<p>But even worse, it breaks the fundamental software engineering principle of Don’t Repeat Yourself (DRY) and it violates the separation of concerns between the client and server, which makes it even harder to maintain and evolve the software.</p>
<h1>2. Use Hyperlinks for Workflow Transitions</h1>
<p>So what should you do if you have transition rules in your workflow, but you don’t want all the bad stuff I mentioned in the previous section?</p>
<p>An alternative approach is to model each workflow transition as a subresource and let clients to use HTTP’s <strong>POST</strong> method on these subresources to perform the transition. This is inspired by the action pattern in <a href="https://github.com/paypal/api-standards/blob/master/api-style-guide.md#complex-operation" target="_blank" rel="noopener noreferrer">PayPal’s API Standards</a>.</p>
<p>On top of the subresources, you add hyperlinks in the response to let the client know what workflow transitions are possible in the current state.</p>
<p>So with this approach, the response will look like this:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="json">{
    "id": 54301,
    "status": "Draft",
    "title": "7 Things You Didn’t Know about Star Wars",
    "content": "George Lucas accidentally revealed that…",
    "_links": {
        "sendToReview": {
            "description": "Send to Review",
            "href": "/posts/54301/review"
        }
    }
}</pre>
<p>The smart thing is that the <strong>_links</strong> section is automatically updated to show what workflow transitions are available in the current state. So in the example above, you can see that the blog post is in the <strong>Draft</strong> state, and from there you can make the <strong>Send to Review</strong> transition to move the post to the <strong>Review</strong> state.</p>
<p>So if you call <strong>POST /posts/54301/review</strong>, you move the blog post to the <strong>Review</strong> state, and then the server will update the <strong>_links</strong> section to show what workflow transitions are possible in this new state:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="json">{
    "id": 54301,
    "status": "Review",
    "title": "7 Things You Didn’t Know about Star Wars",
    "content": "George Lucas accidentally revealed that…",
    "_links": {
        "publishPost": {
            "description": "Publish Post",
            "href": "/posts/54301/publish"
        },
        "rejectPost": {
            "description": "Reject Post",
            "href":"/posts/54301/reject"
        }
    }
}</pre>
<p>The benefit of this solution is that clients no longer need to implement workflow logic in their own code, which means that business logic is no longer leaked into them.</p>
<p>It also reduces the risk of poorly constructed links in the client code — which is a frequent <a href="https://blogs.oracle.com/craigmcc/entry/why_hateoas" target="_blank" rel="noopener noreferrer">cause of defects in REST clients</a> — because the clients get the links from the server.</p>
<p>Another really cool thing is that if the client needs to display a <strong>Next Action</strong> menu, it can simply loop through the values in the <strong>_links</strong> section and use them as menu items.</p>
<p>Finally, it also fits nicely with REST’s goal of self-discovery and <a href="https://www.kennethlange.com/what-are-restful-web-services/">HATEOAS</a>.</p>
<p>The drawback compared to the approach in the previous section is that the response is bigger, because it includes the <strong>_links</strong> section. Another drawback is that the interaction between the client and server has become a little more chatty, because you now need two requests if you want to update a blog post and send it to review.</p>
<p>But I think both of these drawbacks are pretty minor compared to what you get out of it.</p>
<p>A more serious concern is that if you have an advanced workflow, you might end up with a massive number of subresources (i.e. one for each workflow state), which might look a bit messed up.</p>
<p>Another concern is that the server will need to know all states at design time to create subresources for them. This won’t be a problem for most workflows, but if you offer sophisticated workflow functionality where users can customize the states and transitions to fit their special needs it could be problematic.</p>
<h1>3. Use a Subresource for Workflow Transitions</h1>
<p>So how do you model customizable workflows?</p>
<p>For inspiration, let’s take a look at the issue-tracking tool JIRA, which allows (admin) users to configure their own workflows at runtime. How do they expose this in their <a href="https://docs.atlassian.com/jira/REST/latest/#api/2/issue-doTransition" target="_blank" rel="noopener noreferrer">REST API</a>?</p>
<p>On their <strong>issue</strong> resource, they added a <strong>transitions</strong> subresource where the client can get a list of possible transitions from the issue’s current state. The client can then take one of these possible states and make a <strong>POST</strong> to the same subresource to transit to that state.</p>
<p>I like their approach, but think it’s a little naughty that they use the same subresource for two different things (i.e. list potential states, and change the current state).</p>
<p>So to use this approach for our blog post workflow, you can add a subresource with potential transition changes (you could also call it “transactions“ or “actions“ depending on your preferences):</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">GET /posts/{id}/availableTransitions</pre>
<p>For a blog post in the <strong>Review</strong> state, it will return something like this:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">[
    {"transition":"Publish Post"},
    {"transition":"Reject Post"}
]</pre>
<p>If you want to do a transition, you grab one of the possible transitions from the array and <strong>POST</strong> it to the transitions subresource:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">POST /posts/{id}/transitions

{
    "transition": "Publish Post"
}</pre>
<p>A cool thing about this approach is that if you need more advanced workflow transitions, you can add more attributes to the transition subresource. For example, when you transit to the <strong>Review</strong> state, you might also want to specify a reviewer and a comment:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">POST /posts/{id}/transitions

{
    "transition": "Send to Review",
    "reviewer": "Han Solo",
    "comment": "Plz review this faster than you did the Kessel Run!"
}</pre>
<p>Another interesting possibility is that if the history of transitions is important (for audit), you could enable a <strong>GET</strong> method on the transitions subresource to get a full list of all transitions that have been performed on the resource.</p>
<p>You could also decide to execute the transitions asynchronous by returning a <strong>202 Accepted</strong> status code and a link where the client can poll the latest status. This could be useful in a money transfer between banks where the actual transfer happens in a nightly batch.</p>
<p><a href="https://www.thoughtworks.com/insights/blog/rest-api-design-resource-modeling" target="_blank" rel="noopener noreferrer">Prakash Subramaniam</a> even goes as far as playing with the idea that you should drop <strong>PUT</strong> all together, and only allow changing resources through a transition subresource. The good thing is that it neatly separates the interface into a query and command part (as per the <a href="http://martinfowler.com/bliki/CQRS.html" target="_blank" rel="noopener noreferrer">CQRS</a> pattern) and you have a strong audit trail of what has happened to the resource.</p>
<p>The drawback is that there are (many) scenarios where it’s total overkill to perform a transaction. For example, to edit the title of a blog post. A live blog post editor would probably end up doing so many transactions that it would overwhelm any kind of history log. But for something like a bank account, it makes good sense to make each update inside a transaction, so you have a complete audit trail.</p>
<h1>So which one should I pick?</h1>
<p>So we came to the unavoidable question: What approach is the best one?</p>
<p>As always, it depends on the context, but here are some quick guidelines:</p>


<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><strong>STYLE</strong></td><td><strong>USE WHEN:</strong></td></tr><tr><td><strong>1. State Attribute</strong></td><td>When there are no restrictions on the transitions. You can go from any state to any state at any time. The states are basically nothing more than a list of values.</td></tr><tr><td><strong>2. Transition Links</strong></td><td>There are limits to which states you can go to depending on the current state.</td></tr><tr><td><strong>3. Transition Subresource</strong></td><td>The workflow is configurable by users, so states and transitions among them are not fixed, but can be changed at runtime.</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">So use the Einstein rule (i.e. make things as simple as possible, but not simpler) and start with the first approach, and only consider number two or even number three if there is an undeniable need for them.</p>



<p class="wp-block-paragraph">That’s all for now. Thank you for reading!</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>4 Must-Read Articles on Developer Experience (DX)</title>
		<link>https://kennethlange.com/4-must-read-articles-on-developer-experience-dx/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Wed, 05 Oct 2016 07:49:15 +0000</pubDate>
				<category><![CDATA[Others]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=23</guid>

					<description><![CDATA[We live in an API Economy where APIs are more important to business success than ever before. Companies are digitalizing&#8230;<p><a href="https://kennethlange.com/4-must-read-articles-on-developer-experience-dx/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[<p>We live in an <a href="http://www.forbes.com/sites/ciocentral/2012/08/29/welcome-to-the-api-economy/" target="_blank" rel="noopener noreferrer">API Economy</a> where APIs are more important to business success than ever before. Companies are digitalizing their businesses at a breathtaking rate, and they use APIs to integrate customers and partners into their new digital business processes.</p>
<p>A result of this is that Developer Experience (DX) — which is all about using User Experience (UX) techniques to make life easier for third-party developers calling your public APIs — is fast becoming essential to remain competitive in the digital economy.</p>
<p>But how in the world do you apply UX techniques, such as personas, prototypes and usability testing, to the developer experience?</p>
<p>I personally think this is a really exciting topic and I’ve read hundreds of good articles about the topic, but if I had to choose the best of the best, I would pick these four:</p>
<ol>
<li><a href="http://nordicapis.com/why-api-developer-experience-matters-more-than-ever/" target="_blank" rel="noopener noreferrer">Why API Developer Experience Matters More Than Ever</a> — This is the best intro that I have seen to developer experience.</li>
<li><a href="https://www.mnot.net/blog/2012/04/14/user_personas_for_http_apis" target="_blank" rel="noopener noreferrer">User Personas for HTTP APIs</a> — A collection of example personas for a <a href="https://www.kennethlange.com/what-are-restful-web-services/">REST API</a>. It is really an eye opener to see how many different types of users there can be of a single API, and how different their needs are.</li>
<li><a href="http://softwareas.com/patterns-of-developer-experience/" target="_blank" rel="noopener noreferrer">Patterns of Developer Experience</a> — Great post about the principles and patterns for effective DX. The DX Pattern collection at the end of the post is a must-have reference library.</li>
<li><a href="https://www.3scale.net/2015/06/building-effective-api-programs-developer-experience-dx/" target="_blank" rel="noopener noreferrer">Building Effective API Programs: Developer Experience (DX)</a> — If you want to go all the way and create a Developer Program then this article lists what such a program should include and gives an example of what it looks like in the real world.</li>
</ol>
<p>Happy reading!</p>
<p><small>Image credit: <a href="https://www.flickr.com/photos/oinopion/12548904723/" target="_blank" rel="noopener noreferrer">Tomek Paczkowski</a></small></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Creating a Web App in Angular 2.0</title>
		<link>https://kennethlange.com/creating-a-web-app-in-angular-2-0/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Thu, 25 Aug 2016 07:50:31 +0000</pubDate>
				<category><![CDATA[Others]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=26</guid>

					<description><![CDATA[Angular is a popular framework for developing dynamic web applications. It’s developed and maintained by Google and a community of&#8230;<p><a href="https://kennethlange.com/creating-a-web-app-in-angular-2-0/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[<p>Angular is a popular framework for developing dynamic web applications. It’s developed and maintained by <a href="http://www.google.com" target="_blank" rel="noopener noreferrer">Google</a> and a community of open-source developers.</p>
<p>The framework greatly simplifies front-end development work, increases developer productivity, and it’s even fun to program in!</p>
<h1>What’s so different about Angular 2.0?</h1>
<p>The next major version of Angular will not just be an upgrade, but a complete rewrite of the entire framework, and it will <em>not</em> be backwards compatible with previous versions of Angular.</p>
<p>It’s never a popular decision to break backwards compatibility, and the Angular community has not hold themselves back from telling Google this… repeatedly!</p>
<p>So why did the “<a href="https://en.wikipedia.org/wiki/Don%27t_be_evil" target="_blank" rel="noopener noreferrer">don’t be evil</a>” folks at Google decide to do it anyway?</p>
<p>The short story is that the web has evolved a lot since Angular was conceived in 2009, so there are a lot of new web standards (e.g. <a href="http://es6-features.org/" target="_blank" rel="noopener noreferrer">ECMAScript 6</a>, <a href="https://www.typescriptlang.org/" target="_blank" rel="noopener noreferrer">TypeScript</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers" target="_blank" rel="noopener noreferrer">Web Workers</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/Web_Components" target="_blank" rel="noopener noreferrer">Web Components</a>) that Angular v1 is not using…</p>
<p>So instead of trying to force these new standards into an old framework, the Angular team thought it would be better to redesign the framework from scratch to truly embrace the new standards and reap all the benefits (e.g. speed of development, better support for large code bases, faster applications) and at the same time also rethink some of the less attractive elements of the framework (e.g. Angular v1 has 5 different ways to model a service and nobody really understands why).</p>
<h1>Goodbye MVC! Hello Components!</h1>
<p>One of the really big changes in Angular 2.0 is that it’s no longer based on the <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller" target="_blank" rel="noopener noreferrer">MVC architecture</a>, but has moved on to a <a href="https://angular.io/docs/ts/latest/guide/architecture.html" target="_blank" rel="noopener noreferrer">component-based architecture</a>.</p>
<p>What does that mean?</p>
<p>In a component-based architecture you vertically divide your application into (UI) <strong>components</strong>. For example, in Facebook the Timeline could be one component, and the Chat Sidebar could be another one.</p>
<p>The idea is that each component contains all the stuff you would normally put in the different parts of the MVC.</p>
<p>Components can also be <strong>nested</strong>. So the Timeline component could be a root component, and then under it there could be a component for showing the posts on the timeline, and another component for showing a box to post new messages to the timeline.</p>
<p>Beside components, there are also <strong>modules</strong> for grouping a number of related components. For example, to represent a functional area within your application.</p>
<p>Finally, there are <strong>services</strong> (not to be confused with web services) that provides advanced functionality to the components. For example, handling communication back and forth with a <a href="https://www.kennethlange.com/what-are-restful-web-services/">REST Service</a>.</p>
<h1>Our Simple App</h1>
<p>To get some hands-on experience, I thought it’d be fun to re-implement the <a href="http://movieapp-sitepointdemos.rhcloud.com/" target="_blank" rel="noopener noreferrer">Movie App</a> in Angular 2.0. I have previously implemented the same app in <a href="oracle_jet.html">Oracle JET</a>, and Sandeep Panda originally coded it in <a href="http://www.sitepoint.com/creating-crud-app-minutes-angulars-resource/" target="_blank" rel="noopener noreferrer">Angular 1.3</a>.</p>
<p>The Movie App is a simple CRUD web app where you can maintain your movie database. While it’s obviously a demo app, which could easily be beaten by an Excel spreadsheet, I think that for demo purposes it has several interesting features:</p>
<ul>
<li>A Single Page App (SPA) with multiple states (i.e. pages).</li>
<li>Reuse of functionality across states.</li>
<li>Passing parameters between states.</li>
<li>Integration with <a href="https://www.kennethlange.com/what-are-restful-web-services/">RESTful web services</a>.</li>
</ul>
<p>You can see a screenshot below of the Movie App implemented in Angular 2:</p>
<p><img decoding="async" class="img-responsive img-thumbnail center-block" src="../images/movie-app.png"></p>
<p>I have used <a href="http://getbootstrap.com/" target="_blank" rel="noopener noreferrer">Twitter Bootstrap</a> for the (minimal) UI. The simple reason is that <a href="https://material.angular.io/" target="_blank" rel="noopener noreferrer">Material Design</a> (which is Google’s CSS/UI framework) for Angular 2.0 is still in alpha state, which is still a bit too early for me… Yes, I’m a chicken <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h1>Getting Started</h1>
<p>I used Angular 2.0 Release Candiate 5, which was the latest version at the point of writing.</p>
<p>For writing the code, I used the (free) <a href="https://code.visualstudio.com/" target="_blank" rel="noopener noreferrer">Visual Studio Code</a> editor, because it has excellent support for <a href="https://www.typescriptlang.org/" target="_blank" rel="noopener noreferrer">TypeScript</a>, which is the default language for Angular 2.0.</p>
<p>If you want to run the Movie App example from this post, just follow these steps:</p>
<ol>
<li>Download and install <a href="https://nodejs.org/en/download/" target="_blank" rel="noopener noreferrer">Node.js and NPM</a> (if you don’t already have them). I’m using Node.js 4.5.0 and NPM 2.15.9</li>
<li>Download <a href="../resources/angular2-movie-app.zip">Angular2-movie-app.zip</a> and extract it to a local folder.</li>
<li>Open a command prompt and go to the <strong>angular2-movie-app</strong> folder.</li>
<li>Run <strong>npm install</strong> in the command prompt.</li>
<li>Run <strong>npm start</strong> in the command prompt.</li>
</ol>
<p>And the Movie App should be automatically opened in your browser.</p>
<h1>Designing the Movie App in Angular 2.0</h1>
<p>The code structure of the Movie App is shown below:</p>
<pre>/app
  main.ts
  movie.component.ts
  movie.module.ts
  movie.routing.ts
  /movies-overview
    movies-overview.component.ts
    movies-overview.component.html
  /movie-creator
    movie-creator.component.ts
    movie-creator.component.html
  /movie-editor
    movie-editor.component.ts
  /movie-viewer
    movie-viewer.component.ts
    movie-viewer.component.html
  /shared
    movie.ts
    movie-data.service.ts 
</pre>
<p>The app is placed in a folder called <strong>app</strong> and inside it there’s a <strong>main.ts</strong> class as the entry point to the application.</p>
<p>There is also the movie root component (<strong>movie.component.ts</strong>), a routing file (<strong>movie.routing.ts</strong>) that handles navigation between the components, and a module (<strong>movie.module.ts</strong>) for storing the components.</p>
<p>There are four subfolders for components (i.e. <strong>/movies-overview</strong>, <strong>/movie-creator</strong>, <strong>/movie-editor</strong>, and <strong>/movie-viewer</strong>).</p>
<p>The <strong>/shared</strong> subfolder is for stuff that’s used by several components. In this case, it’s the <strong>movie.ts</strong> file, which is a class that represents a movie, and <strong>movie-data.service.ts</strong>, which is a service class that handles communication with the REST service.</p>
<h3>The Movie Class</h3>
<p>The first step in creating the Movie App is to create a Movie class (<strong>movie.ts</strong>):</p>
<pre class="EnlighterJSRAW" data-enlighter-language="typescript">export class Movie {
  _id: number;
  title: string;
  releaseYear: string;
  director: string;
  genre: string;
}</pre>
<p>This step was <em>not</em> needed in Angular v1, but the benefit of explicitly defining the class (and its properties) is that it gives the IDE the information it needs to provide auto-completion, compile-time checking and other cool stuff.</p>
<h1>Calling a REST Service</h1>
<p>The next step is to create the MovieDataService class (<strong>movie-data.service.ts</strong>), which handles communication with the <a href="http://movieapp-sitepointdemos.rhcloud.com/api/movies" target="_blank" rel="noopener noreferrer">Movie REST Service</a>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="typescript">import { Injectable } from '@angular/core';
import { Headers, Response, Http } from '@angular/http';

import 'rxjs/add/operator/toPromise';

import { Movie } from './movie';

@Injectable()
export class MovieDataService {
  private moviesUrl = 'http://movieapp-sitepointdemos.rhcloud.com/api/movies';

  constructor(private http: Http) { }

  getMovies(): Promise&lt;movie[]&gt; {
    return this.http.get(this.moviesUrl).toPromise().then(response =&gt; response.json() as Movie[]).catch(this.handleError);
  }

  getMovie(id: number) {
    return this.getMovies().then(movies =&gt; movies.find(movie =&gt; movie._id === id));
  }

  private post(movie: Movie): Promise {
    let headers = new Headers({'Content-Type': 'application/json'});
    return this.http.post(this.moviesUrl, JSON.stringify(movie), {headers: headers}).toPromise().then(res =&gt; res.json().data).catch(this.handleError);
  }

  private put(movie: Movie) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    let url = `${this.moviesUrl}/${movie._id}`;
    return this.http.put(url, JSON.stringify(movie), {headers: headers}).toPromise().then(() =&gt; movie).catch(this.handleError);
  }

  delete(movie: Movie): Promise {
    let url = `${this.moviesUrl}/${movie._id}`;
    return this.http.delete(url).toPromise().catch(this.handleError);
  }

  save(movie: Movie): Promise {
    if(movie._id) {
      return this.put(movie); 
    } else { 
      return this.post(movie); 
    }
  }

  private handleError(error: any) {
    console.log('An error occured: ', error);
    return Promise.reject("error message: " + error);
  }
}</pre>
<p>The code itself is pretty straight forward. It provides some CRUD methods to call the REST service, and each method returns a <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise" target="_blank" rel="noopener noreferrer">promise</a>, so service calls can be asynchronous.</p>
<p>But I really missed the nice <a href="https://docs.angularjs.org/api/ngResource/service/$resource" target="_blank" rel="noopener noreferrer">$resource</a> service in earlier versions of Angular where we got the same functionality in just a few lines of code:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">angular.module('movieApp.services', []).factory('Movie', function($resource) {
  return $resource('http://movieapp-sitepointdemos.rhcloud.com/api/movies/:id', { id: '@_id' }, {
    update: { method: 'PUT' }
  });
});</pre>
<p>It’s not a big deal to write the service class by hand, it just makes the road towards the code you actually want to write a little bit longer. But hopefully a <strong>$resource</strong> replacement is on the way for Angular 2.0.</p>
<h1>Develop a Component</h1>
<p>Now that we have the Movie and MovieDataService classes ready, we can start developing components.</p>
<p>Let’s take a closer look at MovieCreatorComponent (<strong>Movie-Creator.component.ts</strong>), which is used for adding new movies to the app.</p>
<p>But before we dive into the code, let’s have a quick look to see how the component looks from a UI perspective:</p>
<p><img decoding="async" class="img-responsive img-thumbnail" src="../images/movie-creator.png"></p>
<p>From a technical point of view, the component is just a class with the <strong>@Component</strong> decorator (kind of like annotations in Java):</p>
<pre class="EnlighterJSRAW" data-enlighter-language="typescript">import { Component } from '@angular/core';
import { Router } from '@angular/router';

import { Movie } from '../shared/movie';
import { MovieDataService } from '../shared/movie-data.service';

@Component({
  templateUrl: 'app/movie-creator/movie-creator.component.html'
})
export class MovieCreatorComponent { 
  movie: Movie = new Movie();

  constructor(private router: Router, private movieDataService: MovieDataService) { }

  saveMovie() {
    this.movieDataService.save(this.movie);
    this.router.navigate(['/movies']);
  }
}</pre>
<p>In the constructor, we say that a <strong>router</strong> (for navigating to other components) and a <strong>movieDataService</strong> (for calling the REST Service) should be injected into the component, and stored in two private variables, which we don’t need to declare explicitly.</p>
<p>In the <strong>saveMovie</strong> methods, we save the movie using the REST Service, and navigates back to the movie overview.</p>
<p>In the <strong>@Component</strong> decorator, we use the <strong>templateUrl</strong> property to say what template should be used for the component.</p>
<p>You can see the content of <strong>movie-creator.component.html</strong> below:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;div class="form-group"&gt;
  &lt;label for="title"&gt;Title&lt;/label&gt;
  &lt;input type="text" [(ngModel)]="movie.title" class="form-control" id="title" placeholder="Movie Title Here"/&gt;
&lt;/div&gt;
&lt;div class="form-group"&gt;
  &lt;label for="year"&gt;Release Year&lt;/label&gt;
  &lt;input type="text" [(ngModel)]="movie.releaseYear" class="form-control" id="year" placeholder="When was the movie released?"/&gt;
&lt;/div&gt;
&lt;div class="form-group"&gt;
  &lt;label for="director"&gt;Director&lt;/label&gt;
  &lt;input type="text" [(ngModel)]="movie.director" class="form-control" id="director" placeholder="Who directed the movie?"/&gt;
&lt;/div&gt;
&lt;div class="form-group"&gt;
  &lt;label for="genre"&gt;Movie Genre&lt;/label&gt;
  &lt;input type="text" [(ngModel)]="movie.genre" class="form-control" id="genre" placeholder="Movie genre here"/&gt;
&lt;/div&gt;
&lt;div class="form-group"&gt;
  &lt;input (click)="saveMovie()" type="submit" class="btn btn-primary" value="Save Movie"/&gt;
&lt;/div&gt;</pre>
<p>The template is basically HTML with a couple of Angular extensions:</p>
<p>We use <strong>[(ngModel)]</strong> to bind an HTML input field to a property in the component class, so that the property in the component class is automatically updated when a user enters something in the input field.</p>
<p>For example, <strong>[(ngModel)]=&#8221;movie.title&#8221;</strong> will bind HTML input field to the <strong>title</strong> of the <strong>movie</strong> property in the component class, so when a user enters a title it is automatically stored in <strong>movie.title</strong> property.</p>
<p>In the same way, we use <strong>(click)</strong> to bind an HTML button to a method in the component class.</p>
<p>For example, <strong>(click)=&#8221;saveMovie()&#8221;</strong> makes sure that when a user clicks the “Save Movie” button then the component’s <strong>saveMovie()</strong> method will be automatically called.</p>
<p>In my opinion, the component approach feels really nice to work with, but it’s hard to explain why, it just feels “brain-friendly”. Maybe it’s because the code structure follows the UI structure you see on the screen.</p>
<h1>Conclusion</h1>
<p>My first impression of Angular 2.0 was that I was surprised by the upfront costs (e.g. installing npm packages, setting up configuration files) compared to the earlier versions where I just linked to a <a href="https://docs.angularjs.org/misc/downloading" target="_blank" rel="noopener noreferrer">CDN</a> and then I was ready to start coding.</p>
<p>On top of that, I also needed to create classes and hand-code the calls to the REST Service, which also felt like a hassel when your fingers are aching to start coding all the fun stuff!</p>
<p>But once you have made this initial investment, it starts to pay off (easier to rename classes, typos in the code are spotted instantly, really nice and fast auto-completion), which was extremely helpful when I started coding the components.</p>
<p>The components were the most positive surprise. It just felt like a much nicer way to structure the code compared to the old MVC approach.</p>
<p>If you want to get started with Angular 2, I can recommend the <a href="https://angular.io/docs/ts/latest/guide/architecture.html" target="_blank" rel="noopener noreferrer">architecture overview</a> document for a quick overview of the framework, the <a href="https://angular.io/docs/ts/latest/quickstart.html" target="_blank" rel="noopener noreferrer">5 Min Quickstart</a> to learn how to install the framework from scratch, and the <a href="https://angular.io/docs/ts/latest/tutorial/" target="_blank" rel="noopener noreferrer">Tour of Heroes tutorial</a> as a great way to learn a lot about the functionality that the framework offers.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>The Rise and Fall of Napoleon</title>
		<link>https://kennethlange.com/the-rise-and-fall-of-napoleon/</link>
					<comments>https://kennethlange.com/the-rise-and-fall-of-napoleon/#comments</comments>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Tue, 31 May 2016 07:56:11 +0000</pubDate>
				<category><![CDATA[History]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=243</guid>

					<description><![CDATA[They called him Napoleon the Great. His list of achievements is staggering: He restored order in post-Revolutionary France. He abolished&#8230;<p><a href="https://kennethlange.com/the-rise-and-fall-of-napoleon/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">They called him <a href="https://www.intelligent-quotes.com/napoleon" data-type="link" data-id="https://www.intelligent-quotes.com/napoleon" target="_blank" rel="noreferrer noopener">Napoleon the Great</a>.</p>



<p class="wp-block-paragraph">His list of achievements is staggering: He restored order in post-Revolutionary France. He abolished feudalism and serfdom, established legal equality and religious tolerance, and created an Egalitarian system based on the highly controversial idea that government jobs should go to the most qualified!</p>



<p class="wp-block-paragraph">He was a military genius who reinvented the art of warfare, won some forty battles, and came dangerously close to total domination of Europe.</p>



<p class="wp-block-paragraph">So how did Monsieur Bonaparte achieve all this?</p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="750" height="568" src="https://www.kennethlange.com/wp-content/uploads/2019/02/revolution.jpg" alt="" class="wp-image-246" srcset="https://kennethlange.com/wp-content/uploads/2019/02/revolution.jpg 750w, https://kennethlange.com/wp-content/uploads/2019/02/revolution-300x227.jpg 300w, https://kennethlange.com/wp-content/uploads/2019/02/revolution-624x473.jpg 624w" sizes="auto, (max-width: 750px) 100vw, 750px" /><figcaption class="wp-element-caption">Napoleon leading his troops (Image credit: <a rel="noreferrer noopener" target="_blank" href="https://commons.wikimedia.org/wiki/File:La_Bataille_du_Pont_d%27Arcole.jpg">Wikimedia Commons</a>)</figcaption></figure>



<p class="wp-block-paragraph">The most important thing to remember about Napoleon’s rise to power is that it would never have happened, if it hadn’t been for the French Revolution.</p>



<p class="wp-block-paragraph">Napoleon was a nobody from Corsica, a Mediterranean island that had recently acquired by France, and in pre-Revolutionary France only men from the French aristocracy were allowed to rise to the upper echelons of the military.</p>



<p class="wp-block-paragraph">But fortunately for Napoleon (and less fortunate for the French aristocrats!) the revolution broke out and it presented Napoleon with a once in a lifetime opportunity to break through the glass ceiling.</p>



<p class="wp-block-paragraph">He seized the moment and supported the revolution from the beginning. His brilliant talent for winning battles meant that he quickly rose through the military ranks as he beat the Royalists again and again.</p>



<p class="wp-block-paragraph">His success as a military man gave him political clout. He used his influence to first become consul, then consul for life, and finally nothing less than “His Imperial Majesty the Emperor of the French”.</p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="728" height="629" src="https://www.kennethlange.com/wp-content/uploads/2019/02/napoleon2.jpg" alt="" class="wp-image-248" srcset="https://kennethlange.com/wp-content/uploads/2019/02/napoleon2.jpg 728w, https://kennethlange.com/wp-content/uploads/2019/02/napoleon2-300x259.jpg 300w, https://kennethlange.com/wp-content/uploads/2019/02/napoleon2-624x539.jpg 624w" sizes="auto, (max-width: 728px) 100vw, 728px" /><figcaption class="wp-element-caption">“His Imperial Majesty the Emperor of the French” (Image credit: <a rel="noreferrer noopener" target="_blank" href="https://commons.wikimedia.org/wiki/File:Napoleon_Groot.jpg">Wikimedia Commons</a>)</figcaption></figure>



<p class="wp-block-paragraph">So what can we learn from this?</p>



<p class="wp-block-paragraph">The first lesson is that skills are everything, and without skills you are going nowhere.</p>



<p class="wp-block-paragraph">Napoleon used all his pre-revolutionary career to build his incredible military skills. Even if the French Revolution had never happened, Napoleon could still have had a decent (but less memorable) career by growing his talents into incredible strengths.</p>



<p class="wp-block-paragraph">The second lesson is that turbulent times always bring new opportunities with them, because they shake up the status quo.</p>



<p class="wp-block-paragraph">Yes, turbulence is often frightening (as the French Revolution without doubts was) and many people will be paralyzed by fear and be involuntary pulled along by an unstoppable force of change. But Napoleon seized the changes, jumped to the front and let the forces push him forward.</p>



<p class="wp-block-paragraph">So what can we learn from this? That you should just take it easy, enjoy the good life, and hope that opportunity will someday come knocking on your door?</p>



<p class="wp-block-paragraph">No, my friend!</p>



<p class="wp-block-paragraph">It’s true that the future is so hard to predict that it’s almost impossible to know what opportunities will come by or when. To paraphrase Monty Python: “Nobody expects the French Revolution!”</p>



<p class="wp-block-paragraph">But it’s also true that turbulent times almost always bring new opportunities with them.</p>



<p class="wp-block-paragraph">So in turbulent times you should rely less on long-term planning, but instead learn to lookout for opportunities. For opportunities are easily missed because, as Edison said, they are often dressed in overalls and look like hard work.</p>



<p class="wp-block-paragraph">So what should you do while scanning for opportunities?</p>



<p class="wp-block-paragraph">You should get to know your talents and practice them until you reach mastery, like Napoleon did with his military talents. So when the opportunity arrives, you know exactly how a person with your strengths should chase it and you can seize it with everything you got!</p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="750" height="475" src="https://www.kennethlange.com/wp-content/uploads/2019/02/waterloo.jpg" alt="" class="wp-image-250" srcset="https://kennethlange.com/wp-content/uploads/2019/02/waterloo.jpg 750w, https://kennethlange.com/wp-content/uploads/2019/02/waterloo-300x190.jpg 300w, https://kennethlange.com/wp-content/uploads/2019/02/waterloo-624x395.jpg 624w" sizes="auto, (max-width: 750px) 100vw, 750px" /><figcaption class="wp-element-caption">Napoleon’s disastrous defeat at Waterloo (Image credit: <a rel="noreferrer noopener" target="_blank" href="https://commons.wikimedia.org/wiki/File:El_barranco_de_Waterloo_(Ulpiano_Checa).jpg">Wikimedia Commons</a>)</figcaption></figure>



<p class="wp-block-paragraph">Now, as you might know, one of Napoleon’s more recent honors has been to be immortalized in an ABBA song. But wait a minute, you might think, wasn’t this song about his defeat and surrender at Waterloo?</p>



<p class="wp-block-paragraph">How did an extraordinarily gifted man, who followed the first two lessons to the letter, end up being utterly defeated by his enemies?</p>



<p class="wp-block-paragraph">The short version is that Napoleon’s brilliant victories in the first part of his career gave him a false sense of invincibility and this made him arrogant and sloppy. He started wars that he should have stayed out of, and he no longer applied his tactical genius with the same vigor as in his earlier battles.</p>



<p class="wp-block-paragraph">So the final lesson from Napoleon’s amazing life is that when you have become successful, you must be wary of the arrogance that success often breed, and remember that &#8220;all glory is fleeting&#8221; as they used to say to victorious generals in Ancient Rome.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://kennethlange.com/the-rise-and-fall-of-napoleon/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Write Beautiful REST Documentation with Swagger</title>
		<link>https://kennethlange.com/write-beautiful-rest-documentation-with-swagger/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Tue, 31 May 2016 07:52:41 +0000</pubDate>
				<category><![CDATA[API Engineering]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=28</guid>

					<description><![CDATA[Swagger is the most widely used standard for specifying and documenting REST Services. The real power of the Swagger standard&#8230;<p><a href="https://kennethlange.com/write-beautiful-rest-documentation-with-swagger/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[<p>Swagger is the most widely used <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md" target="_blank" rel="noopener noreferrer">standard</a> for specifying and documenting <a href="https://www.kennethlange.com/what-are-restful-web-services/">REST Services</a>.</p>
<p>The real power of the Swagger standard comes from the ecosystem of powerful tools that surrounds it.</p>
<p>For example, there’s <a href="http://swagger.io/swagger-editor/" target="_blank" rel="noopener noreferrer">Swagger Editor</a> for writing the Swagger spec, <a href="http://swagger.io/swagger-codegen/" target="_blank" rel="noopener noreferrer">Swagger Codegen</a> for automatically generating code based on your Swagger spec, and <a href="http://swagger.io/swagger-ui/" target="_blank" rel="noopener noreferrer">Swagger UI</a> for turning your Swagger spec into beautiful documentation that your API users will love to read.</p>
<h1>Why use Swagger?</h1>
<p>But why not use another standard (like <a href="http://raml.org/" target="_blank" rel="noopener noreferrer">RAML</a>) or simply open your favorite word processor and start hitting the keys?</p>
<p>There are 5 good reasons for using Swagger:</p>
<ol>
<li><strong>Industry Standard:</strong> Swagger is the most widely adopted documentation and specification standard for REST Services. This means that it’s already used in real production APIs, so you don’t have to be the beta tester. It also means that the API user has probably already experience with Swagger, which dramatically reduces the learning curve.</li>
<li><strong>Designed for REST:</strong> Swagger is really easy to use, because it’s a single-purpose tool for documenting REST Services. So most of the complicated things, like security or reusing resource definitions across several methods, are already handled gracefully by the standard.</li>
<li><strong>Huge Community:</strong> There’s a great community around Swagger, so when you face a problem, you can usually just Google the solution.</li>
<li><strong>Beautiful Documentation:</strong> The customer-facing documentation looks really nice. Plus there is a built-in way to actually call the services, so the API user won’t need to use an external tool to play around with the services, but can just do it inside the documentation.</li>
<li><strong>Auto-generate Code:</strong> You can auto-generate client and server code (interface part) based on the Swagger spec, which makes sure that they are consistent. You could even make your own tools.</li>
</ol>
<h1>How to get started with Swagger?</h1>
<p>To start writing a Swagger spec, you simply open the online <a href="http://editor.swagger.io/#/" target="_blank" rel="noopener noreferrer">Swagger Editor</a> and start writing according to the <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md" target="_blank" rel="noopener noreferrer">Swagger specification</a>.</p>
<p>You can see a screenshot of the Swagger Editor below. You write your spec in the left-hand side, and you can see the resulting documentation in the right-hand side:</p>
<p><img decoding="async" class="img-responsive center-block" src="../images/swagger_editor.png"></p>
<p>For this post, I’ve created a Swagger specification for the <a href="http://movieapp-sitepointdemos.rhcloud.com/api/movies" target="_blank" rel="noopener noreferrer">Movie REST Service</a>, which Sandeep Panda developed as part of his <a href="https://www.sitepoint.com/creating-crud-app-minutes-angulars-resource/" target="_blank" rel="noopener noreferrer">post on Angular’s $resource</a>.</p>
<p>If you want to play with the example I use in this section:</p>
<ol>
<li>Open the <a href="http://editor.swagger.io/#/" target="_blank" rel="noopener noreferrer">Swagger Editor</a>.</li>
<li>Open the &#8220;File&#8221; menu, and select &#8220;Import URL…&#8221;</li>
<li>Enter <strong>http://www.kennethlange.com/resources/movie_swagger.yaml</strong> in the box.</li>
</ol>
<p>Now let’s walkthrough the example spec!</p>
<h1>Part 1: General Information</h1>
<p>The first thing that you will notice is that Swagger is written in <a href="https://en.wikipedia.org/wiki/YAML" target="_blank" rel="noopener noreferrer">YAML</a>, which is a format that is very easy to read — even for non-technical people.</p>
<p>In the top part of the Swagger specification, you write all the general stuff about your API:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="yaml">swagger: '2.0'

############################################################################
#&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;API Information&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;#
############################################################################
info:
  version: "v1"
  title: REST API for 'The Movie App'
  description: |
    The is a demo Swagger Spec for the sample REST API used by The Movie App that Sandeep Panda developed as part of his great blog post [Creating a CRUD App in Minutes with Angular's $resource](http://www.sitepoint.com/creating-crud-app-minutes-angulars-resource/).

host: movieapp-sitepointdemos.rhcloud.com
basePath: /api</pre>
<p>Here is an explanation of some of the properties:</p>
<ul>
<li><strong>swagger:</strong> This is to say we use Swagger 2.0. It should always be &#8220;2.0&#8221;.</li>
<li><strong>title:</strong> The title of your API documentation.</li>
<li><strong>description:</strong> A description of your API. It is always nice with examples.</li>
<li><strong>version:</strong> The version of your API (remember that for APIs a low version number is always more attractive, because a high number indicates an unstable interface and hence an extra burden on the clients using it.)</li>
<li><strong>host:</strong> The server where your REST API is located.</li>
<li><strong>basePath:</strong> The path on the server where your REST API is located.</li>
</ul>
<h1>Part 2: REST Services</h1>
<p>In the middle part, you define the paths and HTTP Methods.</p>
<p>I have only included <strong>PUT</strong> below, but you can see the rest in <a href="../resources/movie_swagger.yaml">my Swagger file</a>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="yaml">############################################################################
#                                     Paths                                #
############################################################################
paths:
  /movies/{id}:
    put:
      summary: Update a movie
      consumes:
        - application/json
      produces:
        - application/json
      parameters:
        - in: path
          name: id
          type: number
          description: The id of the movie you want to update.
          required: true
        - in: body
          name: movie
          description: The movie you want update with.
          required: true
          schema:
            $ref: '#/definitions/Movie'
      responses:
        200:
          description: The movie has been successfully updated.
          schema: $ref: '#/definitions/Message'</pre>
<p>Below <strong>paths</strong> you define a path (e.g. <strong>/movies/{id}</strong>) and then you define the HTTP methods (e.g. <strong>PUT</strong>) that the path can be used with.</p>
<ul>
<li><strong>summary:</strong> A short description of the service. There is also a <strong>description</strong> property for a more lengthy description, if necessary.</li>
<li><strong>consumes:</strong> The content type of the data that the service consumes (you can have multiple types). The most common is <strong>application/json</strong>.</li>
<li><strong>produces:</strong> The content type of the data that the service produces (you can have multiple types). The most common is <strong>application/json</strong>.</li>
<li><strong>parameters:</strong> The different parameters that the service accepts. It is both parameters in the HTTP header, URI path, query string and HTTP request body.
<ul>
<li><strong>in:</strong> Where is the parameter located? In the path, in the body, in a header, or somewhere else?</li>
<li><strong>name:</strong> The name of the parameter.</li>
<li><strong>type:</strong> The data type of the parameter. The common types are number and string.</li>
<li><strong>description:</strong> A short, user-friendly description of the parameter.</li>
<li><strong>required:</strong> Is the parameter required or optional?</li>
</ul>
</li>
<li><strong>responses:</strong> The possible responses that the service can return.
<ul>
<li><strong>(HTTP Status Code):</strong> You first specify the HTTP Status Code (e.g. <strong>200</strong>).
<ul>
<li><strong>description:</strong> A short description of when this response happens.</li>
<li><strong>schema:</strong> A definition of the response object (see next section for details).</li>
</ul>
</li>
</ul>
</li>
</ul>
<h1>Part 3: Resource Definitions</h1>
<p>In the last part of the Swagger spec, you have shared resource definitions.</p>
<p>Given that the movie resource representation is used in almost all methods, it makes sense to write the resource definition in a single place and reuse it across the methods.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="yaml">############################################################################
#                               Definitions                                #
############################################################################
definitions:
  Movie:
    type: object
    properties:
      _id:
        type: number
        description: A unique identifier of the movie. Automatically assigned by the API when the movie is created.
      title:
        type: string
        description: The official title of the movie. 
      releaseYear:
        type: string
        description: The year that the movie was released.
      director:
        type: string
        description: The director of the movie.
      genre:
        type: string
        description: The genre of the movie.
      __v:
        type: number
        description: An internal version stamp. Not to be updated directly.</pre>
<p>Below <strong>definitions</strong> you define a resource type (i.e. <strong>Movie</strong>) and then you define its properties below:</p>
<ul>
<li><strong>type:</strong> The data type of the property. The common ones are string and number. The advanced types are objects and arrays.</li>
<li><strong>description:</strong> A description of the property.</li>
<li><strong>properties:</strong> If the data type is an object, you specify the object’s properties below.</li>
</ul>
<p>If you need to define complex JSON objects, you can be inspired by the great examples found in <a href="http://editor.swagger.io/#/" target="_blank" rel="noopener noreferrer">Swagger Editor</a>. You can find them by opening the “File” menu, and select “Open Example…”</p>
<h1>How to turn your Swagger spec into API Documentation</h1>
<p>Once your Swagger spec is stable — and your REST API is operational — you can publish your Swagger spec as customer-facing documentation.</p>
<p>For this purpose you can use <a href="http://swagger.io/swagger-ui/" target="_blank" rel="noopener noreferrer">Swagger UI</a>, which converts your Swagger spec into a beautiful, interactive API documentation (you can see an online example <a href="http://petstore.swagger.io/#/pet" target="_blank" rel="noopener noreferrer">here</a>).</p>
<p>You can download Swagger UI from <a href="https://github.com/swagger-api/swagger-ui/releases" target="_blank" rel="noopener noreferrer">here</a>. It is just a bundle of HTML, CSS and JS files, which doesn’t require a framework or anything, so they can be installed in a directory on any HTTP server.</p>
<p>Once you have downloaded it, you put your <strong>swagger.yaml</strong> file into the <strong>dist</strong> directory — and open <strong>index.html</strong> and change it to point at your swagger file instead of <strong>http://petstore.swagger.io/v2/swagger.json</strong>.</p>
<p>Then you can open <strong>index.html</strong> in your browser, and see your new beautiful, interactive API documentation:</p>
<p><img decoding="async" class="img-responsive center-block" src="../images/swagger_ui.png"></p>
<p>That’s it! Now you have learned all the basic elements of Swagger. Don’t forget to read <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md" target="_blank" rel="noopener noreferrer">Swagger specification</a> if you really want to become a Swagger expert.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>The SQL Developer&#8217;s Guide to REST Services</title>
		<link>https://kennethlange.com/the-sql-developers-guide-to-rest-services/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Fri, 22 Apr 2016 07:54:03 +0000</pubDate>
				<category><![CDATA[API Engineering]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=30</guid>

					<description><![CDATA[This is a practical guide (with lots of examples) to help SQL developers quickly learn the basics of RESTful Web&#8230;<p><a href="https://kennethlange.com/the-sql-developers-guide-to-rest-services/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[<p>This is a practical guide (with lots of examples) to help SQL developers quickly learn the basics of <a href="what-are-restful-web-services/">RESTful Web Services</a>.</p>
<h2>Data Storage: Tables versus Resources</h2>
<p>Both SQL and RESTful Web Services are centered around data.</p>
<p>In SQL, data is normally stored in <strong>tables</strong>, but in REST Services it is stored in <strong>resources</strong>.</p>
<p>For example, in a database you could have a <code class="" data-line="">customer</code> table:</p>
<pre>SQL&gt; SELECT * FROM customer;

ID FIRST_NAME LAST_NAME OCCUPATION
-- ---------- --------- -----------
1  Luke       Skywalker Jedi Master
2  Leia       Organa    Princess
</pre>
<p>In REST Services, you would have a <code class="" data-line="">/customers</code> resource instead of a customer table.</p>
<p>For example, if you want to get all customers (similar to the SQL statement above), you do it like this:</p>
<pre>GET /customers
</pre>
<p>The response to this request would be a <a href="http://www.w3schools.com/json/" target="_blank" rel="noopener noreferrer">JSON</a> array with an object for each customer:</p>
<pre>[
  {
    "id": 1,
    "firstName": "Luke",
    "lastName": "Skywalker",
    "occupation": "Jedi Master"
  },
  {
    "id": 2,
    "firstName": "Leia",
    "lastName": "Organa",
    "occupation": "Princess"
  }
]
</pre>
<h2>CRUD Operations</h2>
<p>The HTTP methods, which are used for RESTful Web Services, map neatly to the common SQL statements:</p>
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>CRUD Operation</th>
<th>HTTP Method</th>
<th>SQL Statement</th>
</tr>
</thead>
<tbody>
<tr>
<td>Create</td>
<td><span class="label label-success">POST</span></td>
<td><code class="" data-line="">INSERT</code></td>
</tr>
<tr>
<td>Read</td>
<td><span class="label label-primary">GET</span></td>
<td><code class="" data-line="">SELECT</code></td>
</tr>
<tr>
<td>Update</td>
<td><span class="label label-warning">PUT</span> <span class="label label-warning">PATCH</span></td>
<td><code class="" data-line="">UPDATE</code></td>
</tr>
<tr>
<td>Delete</td>
<td><span class="label label-danger">DELETE</span></td>
<td><code class="" data-line="">DELETE</code></td>
</tr>
</tbody>
</table>
</div>
<p>The following sections will explain each of them in more details.</p>
<h3>Create</h3>
<p>To create a new customer, you use the <code class="" data-line="">INSERT</code> statement in SQL. For example:</p>
<pre>INSERT INTO customer (first_name, last_name, occupation) 
     VALUES ("Han", "Solo", "Smuggler");
</pre>
<p>In REST, you create a new customer by sending a <code class="" data-line="">POST</code> request with the new customer as a JSON object:</p>
<pre>POST /customers

{
  "firstName": "Han",
  "lastName": "Solo",
  "occupation": "Smuggler"
}
</pre>
<h3>Read</h3>
<p>To read data in SQL, you use the <code class="" data-line="">SELECT</code> statement.</p>
<p>For example, to get a complete list of all customers, you simply call:</p>
<pre>SELECT * FROM customer;</pre>
<p>The corresponding HTTP command is <code class="" data-line="">GET</code>, which you can call like this to the same result:</p>
<pre>GET /customers</pre>
<p>If you want to lookup a specific customer using the primary key, you would do it like this in SQL:</p>
<pre>SELECT * FROM customer</pre>
<p><strong>WHERE id = 2;</strong></p>
<p>In REST you would append the <code class="" data-line="">id</code> to the REST resource:</p>
<pre>GET /customers</pre>
<p><strong>/2</strong></p>
<p>But what if you want to lookup something using a non-primary key?</p>
<p>In SQL you would just add a <code class="" data-line="">WHERE</code> clause to your <code class="" data-line="">SELECT</code> statement:</p>
<pre>SELECT * FROM customer</pre>
<p><strong>WHERE first_name = &#8220;Luke&#8221;;</strong></p>
<p>In REST, you append a query parameter to the <code class="" data-line="">GET</code> statement:</p>
<pre>GET /customers</pre>
<p><strong>?firstName=Luke</strong></p>
<p>Note: The specific query parameters available depend on the REST service you are using.</p>
<p>You may want to limit the number of fields returned by a query, because you don’t need to display all the fields, or because you want to improve performance.</p>
<p>In SQL, you just specify what columns should be returned:</p>
<pre>SELECT</pre>
<p><strong>first_name, last_name</strong></p>
<pre> FROM customer;</pre>
<p>In REST, you request a partial response:</p>
<pre>GET /customers</pre>
<p><strong>?fields=firstName,lastName</strong></p>
<p>Note: Partial responses are not available in all RESTful Web Services, but usually in those where performance is key. For example, mobile apps that may need to operate in an environment with limited bandwidth.</p>
<h3>Update</h3>
<p>If you want to update all columns on a customer via SQL, you use the <code class="" data-line="">UPDATE</code> statement:</p>
<pre>UPDATE customer
   SET id = 2, 
       first_name = "Leia", 
       last_name = "Organa", 
       occupation = "General"
 WHERE id = 2;
</pre>
<p>In REST, you do the same by using the <code class="" data-line="">PUT</code> method:</p>
<pre>PUT /customers/2

{
  "id": 2, 
  "firstName": "Leia", 
  "lastName": "Organa", 
  "occupation": "General"
}
</pre>
<p>But what if you only want to update some of the fields?</p>
<p>In SQL you simply limit the fields to those you want to update:</p>
<pre>UPDATE customer
   SET occupation = "General"
 WHERE id = 2;
</pre>
<p>In REST, you use the <code class="" data-line="">PATCH</code> method:</p>
<pre>PATCH /customers/2

{
  "occupation": "General"
}
</pre>
<p>Note: The difference between <code class="" data-line="">PUT</code> and <code class="" data-line="">PATCH</code> is that <code class="" data-line="">PUT</code> must update all fields to make it <i>idempotent</i>. This fancy word basically means that you must always get the same result no matter how many times it is executed. This is important in network traffic, because if you’re in doubt whether your request has been lost during transmission, you can just send it again without worrying about messing up the resource’s data.</p>
<h3>Delete</h3>
<p>If you need to delete a customer, you use the <code class="" data-line="">DELETE</code> statement in SQL:</p>
<pre>DELETE FROM customer WHERE id = 2;</pre>
<p>Similar, in REST you use the <code class="" data-line="">DELETE</code> method:</p>
<pre>DELETE /customers/2</pre>
<p>That’s it! This is my attempt to map the key concepts in RESTful Web Services to the corresponding key concepts in SQL. If you understand these, you already got a pretty good headstart towards learning REST Services.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>What are RESTful Web Services?</title>
		<link>https://kennethlange.com/what-are-restful-web-services/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Sat, 27 Feb 2016 08:59:36 +0000</pubDate>
				<category><![CDATA[API Engineering]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=36</guid>

					<description><![CDATA[To put it mildly, the World Wide Web was an unexpected success. What had started out as a convenient way&#8230;<p><a href="https://kennethlange.com/what-are-restful-web-services/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[<p>To put it mildly, the World Wide Web was an unexpected success.</p>
<p>What had started out as a convenient way for research labs to connect with each other suddenly exploded in size. <a href="https://www.nngroup.com/articles/100-million-websites/" target="_blank" rel="noopener noreferrer">Jakob Nielsen</a> estimated that between 1991 and 1997 the number of web sites grew with a staggering 850% per year each year!</p>
<p>This incredible growth worried some of the early web pioneers, because they knew that the underlying software was never designed with such massive amount of users in mind.</p>
<p>So they set out to define the web standards more clearly, and enhance them so that the web would continue to flourish in this new reality where it was suddenly the world’s most popular network.</p>
<p>One of these web pioneers was <a href="http://roy.gbiv.com/" target="_blank" rel="noopener noreferrer">Roy Fielding</a>, who set out to look at what made the internet software so successful in the first place and where it was lacking, and in his fascinating <a href="https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm" target="_blank" rel="noopener noreferrer">PhD dissertation</a> he formalized his findings into six constraints, which he collectively called REpresentional State Transfer (REST).</p>
<p>Fielding’s observation was that if your architecture satisfies these six constraints then it will exhibit a number of <a href="https://www.ics.uci.edu/~fielding/pubs/dissertation/net_app_arch.htm#sec_2_3" target="_blank" rel="noopener noreferrer">desirable properties</a> (like scalability, decoupling, simplicity), which are absolutely essential in an Internet-sized system.</p>
<p>His idea was that the constraints should be used as a checklist to evaluate new potential web standards, so that poor design could be spotted early, and way before it was suddenly deployed to millions of web servers.</p>
<p>He successfully used the constraints to evaluate new web standards, such as <a href="https://www.ietf.org/rfc/rfc2616.txt" target="_blank" rel="noopener noreferrer">HTTP 1.1</a> (where he was one of the principal authors) and <a href="https://www.ietf.org/rfc/rfc2396.txt" target="_blank" rel="noopener noreferrer">URI</a> (where he was also one of the authors). These standards have both stood the test of time, despite the immense pressure of being essential protocols on the web and used by billions of people each day.</p>
<p>So a natural question to ask is that if following these REST constraints lead to such great systems, why only used them for browsers and web sites? Why not also create web services that conform to them, so we can enjoy the desirable properties that they lead to?</p>
<p>This thinking led to the idea of RESTful Web Services, which are basically web services that satisfy the REST constraints, and are therefore well-suited for Internet-scale systems.</p>
<p>So what are these 6 REST constraints?</p>
<h3>1. Client-Server</h3>
<p>The first constraint is that the system must be made up of clients and servers.</p>
<p>Servers have resources that clients want to use. For example, a server has a list of stock prices (i.e. a resource) and the client would like to display these prices in some nice graphs.</p>
<p>There is a clear separation of concerns between the two. The server takes care of the back-end stuff (data storage, business rules, etc.) and the client handles the front-end stuff (user interfaces).</p>
<p>The separation means that there can be many different types of clients (web portals, mobile apps, BPM engines, etc.) that access the same server, and each of these can evolve independently of the other clients and the server (assuming that the interface between the clients and server is stable).</p>
<p>The separation also seriously reduces the complexity of the server, as it doesn’t need to deal with UI stuff, which improves scalability.</p>
<p>This is probably the least controversial constraint of REST as client-server is so ubiquitous today that we almost forget that there are other styles to consider (like event-based protocols).</p>
<p>It important to note that while HTTP is almost always used when people develop RESTful Web Services, there is no constraint that forces us to use it. We could use FTP as the underlying protocol, if we really wanted. Even though intellectual curiosity is probably the only good reason for trying that.</p>
<h3>2. Stateless</h3>
<p>To further simplify interactions between clients and servers, the second constraint is that the communication between them must be stateless.</p>
<p>This means that all information about the client’s session is kept on the client, and the server knows nothing of it (so no cookies, session variables, or other naughty stuff!) The consequence is that each request must contain all information necessary to perform the request (i.e. it cannot rely on any context information).</p>
<p>The stateless constraint simplifies the server as it no longer needs to keep track of client sessions, resources between requests, and it does wonders for scalability because the server can quickly free resources after requests have been finished.</p>
<p>It also makes the system easier to reason about as you can easily see all the input data for a request and what output data it resulted in. You no longer need to lookup session variables and other stuff that makes the system harder to understand.</p>
<p>In addition, it will also be easier for the client to recover from failures, as the session context on the server has not suddenly gotten corrupted or out of sync with the client. Roy Fielding even goes as far as writing in an old <a href="https://groups.yahoo.com/neo/groups/rest-discuss/conversations/topics/3583" target="_blank" rel="noopener noreferrer">newsgroup post</a> that reliance on server-side sessions is one of the primary reasons behind failed web applications and on top of that it also ruins scalability.</p>
<p>So far nothing too controversial in the constraints. Many <a href="https://en.wikipedia.org/wiki/Remote_procedure_call" target="_blank" rel="noopener noreferrer">RPC</a> implementations could probably satisfy both the Client-Server and Stateless constraints.</p>
<h3>3. Cache</h3>
<p>The last constraint on the client-server communication is that responses from servers must be marked as <a href="Boost-Your-REST-API-with-HTTP-Caching.html">cacheable</a> or non-cacheable.</p>
<p>An effective cache can reduce the number of client-server interactions, which contributes positively to the performance of the system. At least, from a user’s point of view.</p>
<p>Protocols, like SOAP, that only uses HTTP as a convenient way to get through firewalls (by using POST for all requests) miss out on the improved performance from HTTP caching, which reduces their performance (and also slightly undermines the basic purpose of a firewall.)</p>
<h3>4. Uniform Interface</h3>
<p>What really separate REST from other architectural styles is the <strong>Uniform Interface</strong> enforced by the fourth constraint.</p>
<p>We don’t usually think about it, but it’s pretty amazing that you can use the same Internet browser to read the news, and to do your online banking. Despite these being fundamentally different applications. You don’t even need an extension to the browser to do any of this!</p>
<p>We can do this because the Uniform Interface decouples the interface from the implementation, which makes interactions so simple that it’s easy for somebody familiar with the style to understand it, even automatically (like <a href="https://en.wikipedia.org/wiki/Googlebot" target="_blank" rel="noopener noreferrer">Googlebot</a>).</p>
<p>The Uniform Interface constraint is made up of 4 sub-constraints:</p>
<p><strong>4.1. Identification of Resources</strong></p>
<p>The REST style is centered around resources. This is unlike SOAP and other RPC styles that are modeled around procedures (or methods).</p>
<p>So what is a resource? A resource is basically anything that can be named. From static picture to a feed with real-time stock prices.</p>
<p>But in enterprise software the resources are usually the entities from the business domain (i.e. customers, orders, products, etc.) On an implementation level, it is often the database tables (with business logic on top) that are exposed as resources. But you can also model a business process or workflow as resource.</p>
<p>Each resource in a RESTful design must be uniquely identifiable via an URI (Uniform Resource Identifier) and the identifier must be stable even when the underlying resource is updated (i.e. “<a href="https://www.w3.org/Provider/Style/URI.html" target="_blank" rel="noopener noreferrer">Cool URIs don’t change</a>”).</p>
<p>This means that each resource you want to expose through a RESTful web service must have its own URI. Normally, you would use the first URI below to access a collection of resources (i.e. several customers) and the second URI to access a specific resource inside that collection (i.e. a specific customer):</p>
<pre>1) https://api.example.com/customers
2) https://api.example.com/customers/932612
</pre>
<p>Some well-known APIs that claim to be RESTful fail this sub-constraint. For example, <a href="https://dev.twitter.com/rest/public" target="_blank" rel="noopener noreferrer">Twitter’s REST APIs</a> uses RPC-like URIs like <strong>statuses/destroy/:id</strong> and it’s the same with <a href="https://www.flickr.com/services/api/explore/flickr.galleries.addPhoto" target="_blank" rel="noopener noreferrer">Flickr</a>.</p>
<p>The problem is that they break the Uniform Interface requirement, which adds unnecessary complexity to their APIs.</p>
<p><strong>4.2 Manipulation of Resources through Representations</strong></p>
<p>The second sub-constraint in the Uniform Interface is that resources are manipulated through representations.</p>
<p>This means that the client does not interact directly with the server’s resource. For example, we don’t allow the client to run SQL statements against our database tables.</p>
<p>Instead, the server exposes a representation of the resource’s state. It can sound complicated, but it’s not.</p>
<p>It just means that we show the resource’s data (i.e. state) in a neutral format. This is similar to how the data for a web page can be stored in a database, but is always send to the browser in HTML.</p>
<p>The most common format for RESTful web services is <a href="http://www.w3schools.com/json/" target="_blank" rel="noopener noreferrer">JSON</a>, which is used in the body of the HTTP requests and responses:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="json">{
  "id": 12,
  "firstname": "Han",
  "lastname":"Solo"
}</pre>
<p>When a client wants to update the resource, it gets a representation of that resource from the server, updates the representation with the new data, send the updated representation to the server, and ask the server to update its resource so it corresponds with the new representation.</p>
<p>The benefit is that you avoid a strong coupling between the client and server (like with <a href="https://en.wikipedia.org/wiki/Java_remote_method_invocation" target="_blank" rel="noopener noreferrer">RMI</a> in Java), so you can change the underlying implementation without affecting the clients. It also makes it easier for clients as they don’t need to understand the underlying technology used by each server that they interact with.</p>
<p><strong>4.3 Self-Descriptive Messages</strong></p>
<p>The third constraint in the Uniform Interface is that each message (i.e. request/response) must include enough information for the receiver to understand it in isolation.</p>
<p>Each message must have a media type (for instance, <strong>application/json</strong> or <strong>application/xml</strong>) that tells the receiver how the message should be parsed.</p>
<p>HTTP is <i>not</i> formally required for RESTful web services, but if you use the HTTP methods you should follow their <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html" target="_blank" rel="noopener noreferrer">formal meaning</a>, so the user won’t rely on out of band information to understand them (i.e. don’t use <strong>POST</strong> to retrieve data, or <strong>GET</strong> to save data).</p>
<p>So for the Customer URIs, which we defined earlier, we can expose the following methods for the client to use:</p>
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>Task</th>
<th>Method</th>
<th>Path</th>
</tr>
</thead>
<tbody>
<tr>
<td>Create a new customer</td>
<td><span class="label label-success">POST</span></td>
<td>/customers</td>
</tr>
<tr>
<td>Delete an existing customer</td>
<td><span class="label label-danger">DELETE</span></td>
<td>/customers/{id}</td>
</tr>
<tr>
<td>Get a specific customer</td>
<td><span class="label label-primary">GET</span></td>
<td>/customers/{id}</td>
</tr>
<tr>
<td>Search for customers</td>
<td><span class="label label-primary">GET</span></td>
<td>/customers</td>
</tr>
<tr>
<td>Update an existing customer</td>
<td><span class="label label-warning">PUT</span></td>
<td>/customers/{id}</td>
</tr>
</tbody>
</table>
</div>
<p>The benefit is that the four HTTP methods are clearly defined, so an API user who knows HTTP, but doesn’t know our system can quickly guess what the service is doing by only looking at the HTTP method and URI path (i.e. if you hide the first column, a person who knows HTTP can guess what it says based on the two new columns).</p>
<p>Another cool thing about self-descriptive message is that (similar to statelessness) you can understand and reason about the message in isolation. You don’t need some out-of-band information to decipher it, which again simplifies things.</p>
<p><strong>4.4 Hypermedia as the Engine of Application State</strong></p>
<p>The fourth and final sub-constraint in the Uniform Interface is called Hypermedia as the Engine of Application State (HATEOAS). It sounds a bit overwhelming, but in reality it’s a simple concept.</p>
<p>A web page is an instance of application state, hypermedia is text with hyperlinks. The hypermedia drives (i.e. engine) the application state. In other words, we click on links to move to new pages (i.e. application states).</p>
<p>So when you are surfing the web, you are using hypermedia as the engine of application state!</p>
<p>So it basically means that we should use links (i.e. hypermedia) to navigate through the application. The opposite would be to take an Customer ID from one service call, and then use it as an input parameter to another service call.</p>
<p>It should work like a good web site where you just enter the URI and then you just follow the links that are provided on the web pages. You don’t need to know more than the initial URI.</p>
<p>For example, inside a customer representation there could be a links section with links to the customer’s orders:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="json">{
  "id":12,
  "firstname":"Han",
  "lastname":"Solo",
  "_links": {
    "self": {
      "href":"https://api.example.com/customers/12"
    },
    "orders": {
      "href":"https://api.example.com/customers/12/orders"
    }
  }
}</pre>
<p>The service can also provide the links in the <a href="http://tools.ietf.org/html/rfc5988" target="_blank" rel="noopener noreferrer">Link</a> HTTP header, and W3C is working on a standard definition for the <a href="http://www.iana.org/assignments/link-relations/link-relations.xhtml" target="_blank" rel="noopener noreferrer">relation types</a>, so we can use standardized meanings which further helps the user.</p>
<p>An enormous benefit is that the API user doesn’t need to look in the API documentation to see how to find the customer’s orders, so he or she can easily explore while developing without having to refer to out-of-band API documentation.</p>
<p>It also means that the API user doesn’t need to hardcode (and manually construct) the URIs that he or she wants to call. It might sound like a trivial thing, but Craig McClanahan (co-designer of <a href="https://kenai.com/projects/suncloudapis/pages/Home" target="_blank" rel="noopener noreferrer">The Sun Cloud API</a>) wrote in an informative <a href="https://blogs.oracle.com/craigmcc/entry/why_hateoas" target="_blank" rel="noopener noreferrer">blog post</a> that in his experience 90% of client defects were caused by badly constructed URIs.</p>
<p>Roy Fielding didn’t write that much about the hypermedia sub-constraint in his PhD dissertation (due to lack of time), but he later wrote a <a href="http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven" target="_blank" rel="noopener noreferrer">blog post</a> where he clarified some of the details.</p>
<h3>5. Layered System</h3>
<p>The fifth constraint is another constraint on top of the Uniform Interface, which says that the client should only know the immediate layer it is communicating with, and not be aware of any layers behind it.</p>
<p>This means that the client doesn’t know if it’s talking with an intermediate, or the actual server. So if we place a proxy or load balancer between the client and server, it wouldn’t affect their communications and we wouldn’t need to update the client or server code.</p>
<p>It also means that we can add security as a layer on top of the web services, and then clearly separate business logic from security logic.</p>
<h3>6. Code-On-Demand (optional)</h3>
<p>The sixth and final constraint is the only optional constraint in the REST style.</p>
<p>Code-On-Demand means that a server can extend the functionality of a client on runtime, by sending code to it that it should execute (like Java Applets, or JavaScript).</p>
<p>I have not heard of any RESTful web services that actually send code from the server to the client (after deployment) and gets it executed on the client, but could be a powerful way to beef up the client.</p>
<p>A really nice feature of the simplicity that is enforced by these six constraints (especially, uniform interface and stateless interactions) is that the client code becomes really easy to write.</p>
<p>Most modern web framework can figure out what to do, if we follow the conventions above and they can take care of most of the boilerplate code for us.</p>
<p>For example, in the new <a href="oracle_jet.html">Oracle JET</a> toolkit, we simply need the JavaScript below to create a customer (and it would be just as easy in <a href="http://www.sitepoint.com/creating-crud-app-minutes-angulars-resource/" target="_blank" rel="noopener noreferrer">AngularJS</a>):</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">// Only code needed to configure the RESTful Web Service
var Customer = oj.Model.extend({
  urlRoot: "http://api.example.com/customers",
  idAttribute: "id"
});

// Create a new customer representation
var customer = new Customer();
customer.attributes.firstName = "Han";
customer.attributes.lastName  = "Solo";

// Ask the server to save it
customer.save().then(function() {
  console.log("Saved!");
});</pre>
<p>And it’s just as easy to call the other HTTP methods.</p>
<p>So the front-end engineer just need to add a few more lines to add an HTML form where the user can enter the values, and voila we have a basic web app!</p>
<p>And if we use one of the many gorgeous UI frameworks (like <a href="http://getbootstrap.com/" target="_blank" rel="noopener noreferrer">Twitter’s Bootstrap</a> or <a href="http://materializecss.com/about.html" target="_blank" rel="noopener noreferrer">Google’s Materialize</a>), we can quickly develop something really nice looking in a really short time.</p>
<p>That’s it for now. Thank you for reading and take good care until next time!</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Boost Your REST API with HTTP Caching</title>
		<link>https://kennethlange.com/boost-your-rest-api-with-http-caching/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Sat, 13 Feb 2016 09:00:53 +0000</pubDate>
				<category><![CDATA[API Engineering]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=38</guid>

					<description><![CDATA[It’s a core part of the REST architectural style to use caching! That’s nice, you might think, but why should&#8230;<p><a href="https://kennethlange.com/boost-your-rest-api-with-http-caching/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[<p>It’s a core part of the REST architectural style to use caching!</p>
<p>That’s nice, you might think, but why should I use it?</p>
<p>Because it will allow you to show off against other API Designers by claiming that your REST services are twice as RESTful as theirs <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>But more seriously, <a href="http://roy.gbiv.com/" target="_blank" rel="noopener noreferrer">Roy Fielding</a>, who invented the REST architectural style, didn’t add caching as a requirement just for the fun it! He added it because it can seriously boost performance, which is also shown in the numbers in Tom Christie’s <a href="http://www.dabapps.com/blog/api-performance-profiling-django-rest-framework/" target="_blank" rel="noopener noreferrer">great post</a> on performance tuning of Django REST services.</p>
<p>So, how do you get started with HTTP caching?</p>
<h3>It’s only for HTTP GET requests!</h3>
<p>At first it may seem like an overwhelming task to implement HTTP Caching; especially if you have already developed a huge number of services.</p>
<p>The good news is that it’s only <strong>GET</strong> methods where you need to think about caching as it doesn’t really make much sense to cache <strong>POST</strong>, <strong>PUT</strong> or <strong>DELETE</strong> responses.</p>
<p>The even better news is that if you simply specify the right HTTP header then the browser will do all the heavy lifting for you!</p>
<h3>Code, please!</h3>
<p>That’s all very nice! But can you please show us the code?</p>
<p>Definitely, but the only code you need is the <strong>Cache-Control</strong> header in your HTTP response. There are a number of directives in this header you can use to control the caching:</p>
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>Directive</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<th><span class="label label-success">max-age</span></th>
<td>The maximum time that the cached response should be used (in seconds). The maximum value is 1 year.</p>
<p>Example:</p>
<pre>Cache-Control: max-age=3600</pre>
<p><a href="http://www.mobify.com/blog/beginners-guide-to-http-cache-headers/" target="_blank" rel="noopener noreferrer">Kyle Young</a> writes that a rule of thumb is to use between 60 seconds and 1 hour for most content, but for pseudo dynamic content, use less than 60 seconds (or don’t cache it at all).</td>
</tr>
<tr>
<th><span class="label label-success">s-max-age</span></th>
<td>This directive overrides <strong>max-age</strong> for shared cache, such as proxy servers. You usually have more control over the proxy cache than the client’s local cache, so you can add longer values here.</p>
<p>Example:</p>
<pre>Cache-Control: max-age=0, s-max-age=3600</pre>
<p><a href="http://techblog.thescore.com/2014/11/19/are-your-cache-control-directives-doing-what-they-are-supposed-to-do/" target="_blank" rel="noopener noreferrer">Thuva Tharma</a> has some interesting thoughts on why <strong>s-max-age</strong> may be better than <strong>max-age</strong>.</td>
</tr>
<tr>
<th><span class="label label-danger">public</span> <span class="label label-danger">private</span></th>
<td>Is the response specific to the client, so it cannot be used for other clients? For example, <strong>/tasks/myTasks</strong> is client-specific.</p>
<p>If the response is client-specific, use <strong>private</strong>. Otherwise, use <strong>public</strong>, which is also the default.</p>
<p>Examples:</p>
<pre>Cache-Control: private, max-age=3600</pre>
<pre>Cache-Control: public, max-age=3600</pre>
</td>
</tr>
<tr>
<th><span class="label label-primary">no-store</span></th>
<td>This is used for sensitive data (like credit card details) that must not be stored in caches or proxies under any circumstances.</p>
<p>Example:</p>
<pre>Cache-Control: no-store</pre>
</td>
</tr>
<tr>
<th><span class="label label-primary">no-cache</span></th>
<td>The client must not use cached responses. Unless, it first sends a conditional <strong>GET</strong> (with an <a href="rest_api_etags.html">ETag</a>) to the server to check if the data has been updated in the meantime.</p>
<p>Example:</p>
<pre>Cache-Control: no-cache</pre>
</td>
</tr>
<tr>
<th><span class="label label-warning">must-revalidate</span></th>
<td>If the cached response has expired, it must be revalidated at the server.</p>
<p>HTTP might under some circumstances serve cached responses that have expired (for instance, under poor network connectivity), but using this directive ensures that this won’t happen.</p>
<p>Example:</p>
<pre>Cache-Control: max-age=3600, must-revalidate</pre>
</td>
</tr>
<tr>
<th><span class="label label-warning">proxy-revalidate</span></th>
<td>Same as <strong>must-revalidate</strong>, but for proxy servers.</p>
<p>Example:</p>
<pre>Cache-Control: s-max-age=3600, proxy-revalidate</pre>
</td>
</tr>
</tbody>
</table>
</div>
<p>So let’s say that the client sends a request for some metadata, and we want the client to cache it for 1 hour:</p>
<pre>GET /customers/metadata HTTP/1.1
Host: api.example.com
Accept: application/json
Accept-Language: en
</pre>
<p>To do this, we just add the <strong>Cache-Control</strong> header to our response:</p>
<pre>HTTP/1.1 200 OK
Content-Type: application/json
</pre>
<p><strong>Cache-Control: max-age=3600</strong></p>
<pre>Content-Length: 88
Etag: "6d82cbb050ddc7fa9cbb659014546e59"

{
  "languageCodes": [
    {"da":"Danish"},
    {"no":"Norwegian"},
    {"en":"English"}
  ]
}</pre>
<p>As you can see it’s pretty easy to add caching to your RESTful services…</p>
<p>So if you have performance issues then HTTP caching could be the power tool you are looking for to seriously reduce your response times!</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Avoid Data Corruption in Your REST API with ETags</title>
		<link>https://kennethlange.com/avoid-data-corruption-in-your-rest-api-with-etags/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Sat, 30 Jan 2016 09:02:50 +0000</pubDate>
				<category><![CDATA[API Engineering]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=40</guid>

					<description><![CDATA[There are few things worse than a really nasty data corruption issue. Especially if it has occurred silently over a&#8230;<p><a href="https://kennethlange.com/avoid-data-corruption-in-your-rest-api-with-etags/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[<p>There are few things worse than a really nasty data corruption issue.</p>
<p>Especially if it has occurred silently over a long period of time, so when it’s discovered it’s too late to rollback to a backup before the defect was introduced. It’s even worse if it has also occurred randomly, so there is no pattern to base your fix upon.</p>
<p>Yet an awful lot of <strong>REST APIs</strong> ignore <strong>concurrency control</strong>, so if they are used by multiple clients who modify the same data at the same time then it can lead to <strong>lost updates</strong> and <strong>stalled deletes</strong>, which slowly ruins the data in the database.</p>
<p>This is totally unacceptable in most enterprise applications where data integrity is something you just don’t fool around with…</p>
<p>So how can you avoid this messed up situation?</p>
<p>You use the concurrency control designed into the <strong>HTTP protocol</strong> as a simple, yet effective way to protect the integrity of your data.</p>
<h3>Meet the ETag Header</h3>
<p>If you want to use the concurrency control in the <strong>HTTP Protocol</strong>, you need to use the optional <strong>Entity Tag</strong> (ETag) header in the <strong>HTTP request</strong>.</p>
<p>The <strong>ETag</strong> is kind of like a version stamp for a resource and it’s returned as part of the <strong>HTTP response</strong>.</p>
<p>For example, if you send a request to get a specific customer:</p>
<pre>GET /customers/987123 HTTP/1.1</pre>
<p>Then the <strong>ETag</strong> (if used) is included in the header in the response:</p>
<pre>HTTP/1.1 200 OK
Date: Sat, 30 Jan 2016 09:38:34 GMT
</pre>
<p><strong>ETag: &#8220;1234&#8221;</strong></p>
<pre>Content-Type: application/json

{
  "id":987123,
  "firstname":"Han",
  "lastname":"Solo",
  "job":"Smugler"
}
</pre>
<p>Each time the resource is updated on the server, the <strong>ETag</strong> header will be changed to reflect the content of the new version of the resource.</p>
<p>So to avoid lost updates, you simply take the value of the <strong>ETag</strong> header and put into the <strong>If-Match</strong> header on the <strong>PUT</strong> request:</p>
<pre>PUT /customers/987123 HTTP/1.1

</pre>
<p><strong>If-Match: &#8220;1234&#8221;</strong></p>
<pre>Content-Type: application/json

{
  "id":987123,
  "firstname":"Han",
  "lastname":"Solo",
</pre>
<p><strong>&#8220;job&#8221;:&#8221;General&#8221;</strong></p>
<pre>}
</pre>
<p>The <strong>PUT</strong> request above says that you want to update the customer resource on the server, but only if the <strong>ETag</strong> matches <strong>1234</strong> to make sure that the customer hasn’t been updated since you sent the <strong>GET</strong> request. In this way, your request won’t incidentally overwrite other users’ updates.</p>
<h3>Over at the Server</h3>
<p>When the server gets the <strong>PUT</strong> request, it will execute the logic below:</p>
<p><img decoding="async" class="img-responsive center-block" src="../images/etag.png"></p>
<p>First, the server checks that the <strong>If-Match</strong> header is included in the request. If not, it will tell the client that you cannot update this resource without the <strong>If-Match</strong> header.</p>
<p>Second, the server checks if the resource actually exists as it must exists before it can be updated.</p>
<p>Third, it checks if the <strong>ETag</strong> supplied in the <strong>If-Match</strong> header is the same as the latest <strong>ETag</strong> on the resource. If not, it tells the client that the precondition has failed.</p>
<p>Finally, if the request passes the three validations, then the server updates its resource.</p>
<p>If the server uses the same approach on <strong>DELETE</strong> request, you can also avoid stalled deletes.</p>
<p>Note: The logic above assumes that the server doesn’t allow you to create new resources with a <strong>PUT</strong> request. If this is allowed then the first step should be to check if the resource exists, and if not then branch out and create it and skip the other steps.</p>
<h3>Implementation Hints</h3>
<p>There are several ways to implement <strong>ETags</strong> on the server.</p>
<p>One way is to make a hash of the resource, and put in the <strong>ETag</strong> header. But you need to make sure that the hash includes all updatable fields in the response, be sure that there cannot be hash collisions, and find a hashing algorithm that doesn’t impact performance too much.</p>
<p>Another really simple way to implement <strong>ETags</strong> is to add a read-only etag column to the underlying database table and add a trigger that increases the value each time the row is updated. Of course, the server needs to be aware that the database changes this value behind the screen, so the server always uses the latest version.</p>
<h3>Why not timestamps instead of ETags?</h3>
<p>An easier way to implement concurrency control in <strong>HTTP</strong> is to use the <strong>Last-Modified</strong> and <strong>If-Unmodified-Since</strong> headers instead of <strong>ETag</strong> and <strong>If-Match</strong>. This difference is simply that these two headers use timestamps instead of <strong>ETags</strong>.</p>
<p>So, if it’s easier why not use it?</p>
<p>The problem is that the timestamps use seconds as their finest precision, so if you have fast, high-frequency updates then there is a risk that two updates occur within the same second and you lose one of them.</p>
<p>So in enterprise software where data integrity is an absolute requirement, <strong>Etags</strong> are the safe choice.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>7 Tips for Designing a Better REST API</title>
		<link>https://kennethlange.com/7-tips-for-designing-a-better-rest-api/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Sat, 16 Jan 2016 09:03:38 +0000</pubDate>
				<category><![CDATA[API Engineering]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=42</guid>

					<description><![CDATA[If you need to develop a REST API for a database-driven application, it’s almost irresistible not to use the database&#8230;<p><a href="https://kennethlange.com/7-tips-for-designing-a-better-rest-api/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">If you need to develop a REST API for a database-driven application, it’s almost irresistible <i>not</i> to use the database tables as REST resources, the four HTTP methods as CRUD operations, and then simply expose your thinly-wrapped database as a REST API:</p>



<figure class="wp-block-table is-style-stripes"><table class="has-fixed-layout"><thead><tr><th>Operation</th><th>HTTP</th><th>SQL</th></tr></thead><tbody><tr><td><strong>Create</strong></td><td><code class="" data-line="">POST</code></td><td><code class="" data-line="">INSERT</code></td></tr><tr><td><strong>Read</strong></td><td><code class="" data-line="">GET</code></td><td><code class="" data-line="">SELECT</code></td></tr><tr><td><strong>Update</strong></td><td><code class="" data-line="">PUT</code></td><td><code class="" data-line="">UPDATE</code></td></tr><tr><td><strong>Delete</strong></td><td><code class="" data-line="">DELETE</code></td><td><code class="" data-line="">DELETE</code></td></tr></tbody></table><figcaption class="wp-element-caption">The mapping between SQL and HTTP is deceptively simple.</figcaption></figure>



<p class="wp-block-paragraph">The problem is that one of the foundations of the REST architecture is that the client-facing representation of a resource must be independent of the underlying implementation, and implementations details should definitely <i>not</i> be leaked to the client, which is all too easy with the database-driven approach.</p>



<p class="wp-block-paragraph">It’s also important to ask yourself if an almost raw database is the best interface you can offer your API users? I mean there is already a near-perfect language for doing CRUD operations on database tables, it’s called SQL… And you probably have some business logic on top of those tables that your API users would appreciate not having to re-implement in their own code.</p>



<p class="wp-block-paragraph">So how do you move beyond this database-oriented thinking and closer to a more RESTful design for your API?</p>



<p class="wp-block-paragraph">Let’sThe mapping between SQL and HTTP is deceptively easy. find out…</p>



<h1 class="wp-block-heading">1. Begin with the API User in Mind</h1>



<p class="wp-block-paragraph">Bestselling author and architect <a href="http://samnewman.io/" target="_blank" rel="noopener noreferrer">Sam Newman’s</a> great book on <a href="http://samnewman.io/books/building_microservices/" target="_blank" rel="noopener noreferrer">microservices</a> provides a powerful alternative to the database-driven approach for designing REST web services. It’s useful even if you don’t plan to use microservices.</p>



<p class="wp-block-paragraph">Newman suggests that you divide your application into <strong>bounded contexts</strong> (similar to <a href="https://www.kennethlange.com/6-ways-to-increase-your-industry-knowledge/">business areas</a>). Each bounded context should provide an explicit interface for those who wish to interact with it. Implementation details of the bounded context that don’t need to be exposed to the outside world are hidden behind the interface.</p>



<p class="wp-block-paragraph">You should use this explicit interface as the basis for your API design. Start by asking yourself what business capabilities do the API user needs, rather than what data that should be shared. In other words, ask yourself <strong>what does this bounded context do?</strong> and then ask yourself <strong>what data does it need to do that?</strong></p>



<p class="wp-block-paragraph">The promise is that if you wait with thinking about shared data until you know what business capabilities you need to offer, it will lead to a less database-oriented design.</p>



<p class="wp-block-paragraph">I think his approach is a good way to jolt you out of the database-driven mindset, but you need to be careful that you don’t end up designing a REST-RPC hybrid.</p>



<p class="wp-block-paragraph">What I also like about this approach is that it minimizes the interface and doesn’t expose all data by default, but hides internal data (like logging and configuration tables) from the client and instead focuses on what the client actually needs.</p>



<p class="wp-block-paragraph">This also fits beautifully with veteran API designer <a href="https://twitter.com/joshbloch" target="_blank" rel="noopener noreferrer">Joshua Bloch’s</a> maxim saying that <strong>When in doubt, leave it out</strong> (from his highly popular <a href="http://www.infoq.com/articles/API-Design-Joshua-Bloch" target="_blank" rel="noopener noreferrer">presentation on API design</a>), and it also harmonizes with the REST principle that a representation of a resource doesn’t need to look like the underlying resource, but can be changed to make it easier for the client.</p>



<p class="wp-block-paragraph">So feel free to think about what would be the easiest interface for the API user, and then let your resource take data from multiple tables and leave out columns that are irrelevant to the job that clients need to perform.</p>



<h1 class="wp-block-heading">2. Use Subresources to Show Relationships</h1>



<p class="wp-block-paragraph">An attractive alternative to only using top-level resources is to use subresources to make the relationships between resources more obvious to the API user, and to reduce dependencies on keys inside the resource representation.</p>



<p class="wp-block-paragraph">So how do you decide what resources should be subresources? A rule of thumb is that if the resource is a <strong>part of</strong> another resource then it should be a subresource (i.e. composition).</p>



<p class="wp-block-paragraph">For example, if you have a <strong>customer</strong>, an <strong>order</strong> and an <strong>order line</strong> then an order line is a <strong>part of</strong> an order, but an order is not a part of a customer (i.e. the two exists independently and a customer is not made up of orders!)</p>



<p class="wp-block-paragraph">So the URIs would look like this:</p>



<pre class="wp-block-preformatted">/customers/{id}

/orders/{id}/lines/{id}</pre>



<p class="wp-block-paragraph">A different rule of thumb is to also include aggregations as subresources. That is, a <strong>belongs to</strong> relationship. If we use this rule then an order <strong>belongs to</strong> a customer, so the path would look like this:</p>



<pre class="wp-block-preformatted">/customers/{id}/orders/{id}/lines/{id}</pre>



<p class="wp-block-paragraph">So what rule should you pick?</p>



<p class="wp-block-paragraph">The idea with subresource is to make your API more readable. For example, even if you don’t know the API you can quickly guess that <code class="" data-line="">POST /customer/123/orders</code> will create a new order for customer 123.</p>



<p class="wp-block-paragraph">However, if you end up with more than about two levels then the URI starts to become really long and the readability is reduced.</p>



<p class="wp-block-paragraph">You also need to be aware that subresources cannot be used outside the scope of their parent resource. In the second example, you need a customer id before you can lookup a order, so if you want a list of all open orders (regardless of customer) then you cannot do it in the second example.</p>



<p class="wp-block-paragraph">Ehh, so what to pick?</p>



<p class="wp-block-paragraph">If you want a flexible API, aim for fewer subresources. If you want a more readable API, aim for more subresources.</p>



<p class="wp-block-paragraph">The important thing is that whatever rule of thumb you pick then be consistent about it. I mean the API user might disagree with your decision, but if you are using it consistently throughout your API, he or she will probably forgive you.</p>



<h1 class="wp-block-heading">3. Use Snapshots for Dashboard Data</h1>



<p class="wp-block-paragraph">A deal-breaker for using subresources is that the client might need to access data across subresources to get data for a dashboard or something similar. For example, a manager might want to get some statistics about orders across all customers.</p>



<p class="wp-block-paragraph">Before you go ahead and flatten your whole API, there are two alternatives you should consider.</p>



<p class="wp-block-paragraph">First, remember that there is nothing that prevents you from having multiple URIs that point to the same underlying resource, so beside <code class="" data-line="">/customers/{id}/orders/{id}</code>, you could add an extra URI to query orders outside of the customer scope:</p>



<pre class="wp-block-preformatted">/orders/{id}</pre>



<p class="wp-block-paragraph">To minimize the duplication of functionality, you can limit the top-level <code class="" data-line="">/orders</code> URI to only accept GET requests, so if clients want to create a new order, they will always do it in the context of a customer.</p>



<p class="wp-block-paragraph">Of course, you need to be careful not to duplicate resources unnecessarily, but if there is a customer need, then there is a customer need, and we need to find the best possible solution.</p>



<p class="wp-block-paragraph">In <a href="http://www.goodreads.com/book/show/7533499-restful-web-services-cookbook" target="_blank" rel="noopener noreferrer">RESTful Web Services Cookbook</a>, Chief Engineer at eBay (and former Yahoo Architect) <a href="https://www.subbu.org/" target="_blank" rel="noopener noreferrer">Subbu Allamaraju</a> suggests an alternative approach called <strong>snapshots</strong>.</p>



<p class="wp-block-paragraph">For example, if an order manager wants to see some specific statistics (5 latest orders, 5 biggest clients, etc.) then we can create a snapshot resource that finds and returns all these information:</p>



<pre class="wp-block-preformatted">/orders/snapshot</pre>



<p class="wp-block-paragraph">I personally like the snapshot approach better, because it doesn’t feel like querying a database. But with that said, the snapshot approach requires an intimate knowledge of the API user, and the extra order top-level resource will offer more flexibility.</p>



<h1 class="wp-block-heading">4. Use Links for Relationships</h1>



<p class="wp-block-paragraph">Another way to show relationships between resources, without falling back on using keys in an SQL-like manner, is to embed links inside your responses:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="json" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{
  "id": 123,
  "title": "Mr.",
  "firstname": "Han",
  "surname": "Solo",
  "emailPromotion": "No",
  "_links": {
    "self": {
      "href": "https://api.example.com/v1/customers/123"
    }, 
    "contactDetails": {
      "href": "https://api.example.com/v1/customers/123/contactDetails"
    },
    "orders": {
      "href": "https://api.example.com/v1/orders?customerId=123"
    }
  }
}</pre>



<p class="wp-block-paragraph">A cool thing about links is that they allow autodiscovery by clients! When the client gets the response back then it can see in the <code class="" data-line="">_link</code> section what other actions it can follow from here. This is just like when you are surfing the web where you come to a page and then you can follow its links to new pages.</p>



<p class="wp-block-paragraph">Another nice thing is that clients will have fewer hard-coded links in their code, which will make the code more robust. If the client wants to see the customer’s orders, it can just follow the orders link to get them.</p>



<p class="wp-block-paragraph">However, there are different opinions about if you should use links, or not…</p>



<p class="wp-block-paragraph"><a href="http://www.vinaysahni.com/" target="_blank" rel="noopener noreferrer">Vinay Sahni</a> writes in his excellent blog post <a href="http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api#hateoas" target="_blank" rel="noopener noreferrer">Best Practices for Designing a Pragmatic RESTful API</a> that links are a good idea, but we are not ready to use them yet. On the other hand, the <a href="http://www.crummy.com/writing/speaking/2008-QCon/act3.html" target="_blank" rel="noopener noreferrer">RESTful maturity model</a> says that when you start using links you have reached the highest level of REST maturity.</p>



<p class="wp-block-paragraph">So what to do?</p>



<p class="wp-block-paragraph">Well, Dr. Roy Fielding, an expert on software architectures and the inventor of REST architectural style, <a href="http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven" target="_blank" rel="noopener noreferrer">flatly said on his blog</a> that if you don’t use links it ain’t REST services, and he kindly encourages you to use another buzz word for your API!</p>



<h1 class="wp-block-heading">5. Hide Internal Codes</h1>



<p class="wp-block-paragraph">In an earlier post, I incidentally leaked internal codes in the <code class="" data-line="">job_id</code> column on the <code class="" data-line="">employees</code> table:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="json" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{
  "jobId": "SH_CLERK"
}</pre>



<p class="wp-block-paragraph">Needless to say, this is an implementation detail that gives away that we are using a relational database, and experienced Oracle users would instantly spot that it’s Oracle’s sample HR schema. This leaking makes it harder to switch to a document-oriented database, like <a href="https://en.wikipedia.org/wiki/MongoDB" target="_blank" rel="noopener noreferrer">MongoDB</a>, where there is no concept of foreign keys.</p>



<p class="wp-block-paragraph">But even if the chance of switching to MongoDB is zero, it still makes the response harder to read.</p>



<p class="wp-block-paragraph">So a better approach is to let the REST API translate the internal code to the human-readable value that the code represents (i.e. “Shipping Clerk”) and then also remove the <code class="" data-line="">Id</code> part of the field name.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="json" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{
  "job": "Shipping Clerk"
}</pre>



<p class="wp-block-paragraph">This version is definitely more readable, but a fair concern is if the service will be slower now that it needs to lookup the value? I used to be an avid reader of <a href="https://asktom.oracle.com/" target="_blank" rel="noopener noreferrer">Tom Kyte</a>, <i>the</i> Oracle DB expert, and still remember that you should always optimize from measurements. I mean there’s a good chance that the HTTP cache will help us out and make it less of a bottleneck than it appears at first glance.</p>



<p class="wp-block-paragraph">As a rule of thumb, if performance means everything to you (or you have a lot of lookup fields) then you might consider leaking the internal codes. Otherwise, you should provide a more readable API by hiding them.</p>



<h1 class="wp-block-heading">6. Translate Automatically</h1>



<p class="wp-block-paragraph">But what about translations? What if you have a multilingual application that has translations of the internal code in multiple languages? How do you handle that?</p>



<p class="wp-block-paragraph">Simple! You let the API user specify its preferred language in the <code class="" data-line="">Accept-Language</code> HTTP header. For example, <code class="" data-line="">Accept-Language: da</code> and then the REST API should automatically translate it into Danish:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="json" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{
  "job": "Shippingmedarbejder"
}</pre>



<h1 class="wp-block-heading">7. Create a Resource for Metadata</h1>



<p class="wp-block-paragraph">So what if the API user needs to show a drop-down list that shows all possible jobs? How will he or she get a complete list of all possible values for the job field?</p>



<p class="wp-block-paragraph">The easy solution for you is simply to write the list of possible values in your API documentation and then the API user can hardcode them in the drop-down list. But this will lead to fragile client apps that need to be updated when new job types are added, and it just doesn’t feel very web-like to rely on offline metadata.</p>



<p class="wp-block-paragraph">A more robust solution is to create a metadata subresource that provides list of values and other metadata that are needed when using the resource. For example, a <code class="" data-line="">/employees/metadata</code> subresource could provide the API user will all the metadata needed to interact with the employees resource.</p>



<p class="wp-block-paragraph">This solution is similar to how Atlassian is doing <a href="https://developer.atlassian.com/jiradev/jira-apis/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-example-discovering-meta-data-for-creating-issues" target="_blank" rel="noopener noreferrer">in the JIRA API</a>. If you make sure that the response from the metadata subresource is cached properly it shouldn’t affect performance adversely and you will provide a more flexible API that leads to more stable client apps.</p>



<p class="wp-block-paragraph">That’s it for now. I really hope that some of these tips will help you design better REST APIs. Thanks for reading and take good care until next time!</p>



<p class="wp-block-paragraph"></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>6 Ways to Increase Your Industry Knowledge</title>
		<link>https://kennethlange.com/6-ways-to-increase-your-industry-knowledge/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Tue, 10 Nov 2015 09:08:01 +0000</pubDate>
				<category><![CDATA[Others]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=48</guid>

					<description><![CDATA[Ever since the Tower of Babel, complicated projects have failed due to poor communication. If you have a basic understanding&#8230;<p><a href="https://kennethlange.com/6-ways-to-increase-your-industry-knowledge/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[<p>Ever since the Tower of Babel, complicated projects have failed due to poor communication. If you have a basic understanding of an industry, you can communicate much more effectively with business people, and reduce the risk of failure.</p>
<p>You can even create an attractive <a href="https://books.google.dk/books?id=hdHXAc030p4C&amp;lpg=PT98&amp;ots=AbQDH2COEp&amp;dq=tracey%20the%20publicist%20seth%20godin&amp;pg=PT98#v=onepage&amp;q&amp;f=false" target="_blank" rel="noopener noreferrer">niche brand</a> by combining your technical expertise with a deep understanding of how your industry works.</p>
<p>That’s nice, you might think, but how do you get this industry knowledge?</p>
<p>Here are six tips to get you started:</p>
<ol>
<li><strong>Create a mental model:</strong> Make a boxes and arrows diagram of your current mental model of the domain. The remaining tips are all about growing and refining your model.</li>
<li><strong>Google it:</strong> A simple Google search, like “domain knowledge banking”, will give you a lot of good reads to get started with.</li>
<li><strong>Find a mentor:</strong> Find someone who really understands the domain and listen curiously to what they say about their work. People usually enjoy talking about what they are good at.</li>
<li><strong>Follow the experts:</strong> Find out who are the thought leaders of the industry, and follow their Twitter accounts and blogs.</li>
<li><strong>Read the trade journal:</strong> Find out what the major publication is in the industry and read it.</li>
<li><strong>Watch an employee at work:</strong> See somebody perform one of the key jobs in that industry. For example, spending a few hours with a call center employee will give you a whole new understanding of their fast-paced job.</li>
</ol>
<p>The good news is that the fundamentals of most industries remain pretty stable over time, so once you have a basic understanding it won’t require a lot of maintenance.</p>
<p>And since most software engineers don’t bother to learn much about the industries they work in, you can easily get ahead with only a small investment of your time.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Boost Your Productivity</title>
		<link>https://kennethlange.com/how-to-boost-your-productivity/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Sat, 09 May 2015 08:05:05 +0000</pubDate>
				<category><![CDATA[Others]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=44</guid>

					<description><![CDATA[A simple yet effective way to increase your productivity is to divide your work into 90-minute blocks and take relaxing&#8230;<p><a href="https://kennethlange.com/how-to-boost-your-productivity/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[<p>A simple yet effective way to increase your productivity is to divide your work into 90-minute blocks and take relaxing breaks between them.</p>
<p>In each 90-minute block you focus intensely on a given task, so no social media, chatting, emailing, news reading, etc. You just work, work, work, and then work some more on the task at hand.</p>
<p>Some people has experienced that they can get as much done in a focused 90-minute block as they normally get done in a whole day!</p>
<p>Research shows that 90 minutes is the upper limit for how long we can stay focused. After that our minds start wandering and become less productive.</p>
<p>This is why you need a break after you have worked intensely for 90 minutes. It needs to be a real break away from the computer, so your brain can recover and become ready to performance at its maximum level again.</p>
<p>So how does such a 90-minute schedule looks in practice?</p>
<p>For a blogger it can look like this:</p>
<ul>
<li>08:00-09:30 Block 1: Bulldoze through first draft.</li>
<li>09:30-10:00 Break: Go for a run.</li>
<li>10:00-11:30 Block 2: Rewrite and make ready for publication.</li>
<li>11:30-12:00 Break: Enjoy lunch.</li>
<li>12:00-13:30 Block 3: Publish and promote.</li>
</ul>
<p>While 3&#215;90 minutes doesn’t sound like a lot, you must remember that this is highly effective work without any procrastination. Bestselling author Tony Schwartz wrote in <a href="https://hbr.org/2011/01/the-most-important-practice-i" target="_blank" rel="noopener noreferrer">Harvard Business Review</a> that he used to write for 12 hours each day and finish a book in about a year. He then switches to write in three 90-minute blocks per day and was able to finish a book in less than 6 months!</p>
<p>But if you really want to push it, personal development expert Steve Pavlina puts down the challenge of doing <a href="http://www.stevepavlina.com/blog/2014/12/do-a-full-days-work-in-90-minutes/" target="_blank" rel="noopener noreferrer">5&#215;90-minute blocks</a> per day to get a whole week’s work done in a single day!</p>
<p>For me it works best if I have a goal for each 90-minute block. It’s not needed with a specific and measurable goal, but just a rough idea of what I would like to achieve within the 90 minutes.</p>
<p>I also discovered that I need a physical kitchen clock with a countdown feature to make this work for me. At first I used the timer on my iPad, but after some time the screen goes dark, and I must be able to see the clock counting down all the time for maximum motivation.</p>
<p style="text-align: center;"><img decoding="async" src="../images/kitchen_timer.jpg" width="540px" /></p>
<p style="text-align: center;"><strong>My secret weapon, a kitchen timer!</strong></p>
<p>Another essential element for success is to take breaks seriously(!) So don’t sit down and “do” Facebook for half an hour. Take a real break and give your mind a chance to relax and renew itself.</p>
<p>Here’s a quick list of ideas for break activities:</p>
<ul>
<li>Take a run, stretch or some other exercise.</li>
<li>Go for a walk.</li>
<li>Meditate, pray or visualize.</li>
<li>Enjoy a healthy snack.</li>
<li>Take a nap.</li>
<li>Talk with a friend.</li>
</ul>
<p>If you work in a management position (or another job with many interruptions) it can be difficult to organize your work into uninterrupted 90-minute blocks. But you should still carve out one 90-minute block per day to get the important, but not (yet!) urgent, stuff done. Everybody can do that!</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>9 Tips for Effective One-on-Ones</title>
		<link>https://kennethlange.com/9-tips-for-effective-one-on-ones/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Fri, 01 May 2015 08:06:50 +0000</pubDate>
				<category><![CDATA[Others]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=46</guid>

					<description><![CDATA[The purpose of a one-on-one meeting is to listen to what your people has to say. In this way, you&#8230;<p><a href="https://kennethlange.com/9-tips-for-effective-one-on-ones/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[<p>The purpose of a one-on-one meeting is to listen to what your people has to say.</p>
<p>In this way, you can learn about potential issues before they turn into serious problems.</p>
<p>Your managerial reward of effective one-on-ones is a lack of drama in your team, which enables your people to spend their time on doing great work!</p>
<p>So how do you do effective one-on-ones? Here are 9 tips to get you started.</p>
<h3>1. Be consistent and never-ever cancel it</h3>
<p>You should schedule one-on-one meetings as a reoccurring event in your calendar. The meeting should be 30-60 minutes. You should schedule it for every week, but if you have more than 6 employees then consider scheduling it biweekly due to the time involved.</p>
<p>You should never-ever cancel it, as that will basically communicate that your people are not <em>that</em> important to you.</p>
<p>If you keep it consistent your people will know that this is the time to discuss issues. This will make your schedule more predictable as you are less likely to be interrupted at other times if your people know that there’s a one-on-one where they can bring up their concerns.</p>
<h3>2. Start with “How are you?”</h3>
<p>Michael Lopp, a veteran software engineering manager, writes in <a href="http://randsinrepose.com/archives/the-update-the-vent-and-the-disaster/" target="_blank" rel="noopener noreferrer">The Update, The Vent, The Disaster</a> that you start the one-on-one meeting with a simple, “<i>How are you?</i>”</p>
<p>It’s a soft opener, but the idea is that whatever the reply, you can learn something useful and take the conversation from there.</p>
<h3>3. Listen, Listen and Listen Some More</h3>
<p>The one-on-one should be a bottom-up meeting where your people share information with you, rather than a top-down where you are pushing information down their throats!</p>
<p>While most managers are extremely busy, and honestly don’t want to hear about more problems, which will only make them more busy and perhaps even shake the boat! But the hard truth is that the earlier a problem is detected, analyzed and dealt with, the cheaper it will be to solve. And all practical experience shows that ignoring problems will (unfortunately!) not make them disappear.</p>
<h3>4. It Ain’t a Status update!</h3>
<p>The one-on-one is <span style="text-decoration: underline;">not</span> for operational stuff. There are project meetings and stand-up meetings for handling the daily status of tasks.</p>
<p>One-on-ones are for strategic stuff; like, looking into how we are doing stuff and how we can do it better.</p>
<p>If your employee starts to go through status, interrupt after some 5 minutes and say, ”It sounds like you got the project/task under control, but how about the [insert strategic activity] that we talked about earlier?”</p>
<h3>5. Ask Powerful Questions</h3>
<p>Sometimes it can be difficult to get the conversations rolling. For example, when you have new people, or very quiet people, or people who have had a poor manager in the past.</p>
<p>So to get the talking started it always help to have some powerful questions prepared. For example:</p>
<ol>
<li>What excites you at work?</li>
<li>Do you have ideas for how we can do things better?</li>
<li>Where is your job satisfaction on a scale 1-10? Follow-up with: What would it take to make it a 10?</li>
<li>Do you have ideas for the next release of our product?</li>
<li>How’s the family?</li>
</ol>
<p>A one-on-one is also an excellent opportunity to debrief recent work. For example, to discuss what went well, what didn’t went well, and what are the lessons learned for next time.</p>
<h3>6. Ask for Gossip (really!)</h3>
<p>It’s always good to ask for gossip. Especially, if there has been a recent re-org or any other major event.</p>
<p>Ask your people about their opinion about the event, rather than starting with your own opinion. Then, afterwards, you can always come with your interpretation of the event and explain how it fits into the big picture.</p>
<h3>7. Follow-up (action speaks louder than words!)</h3>
<p>If there are any actions coming out of the meeting, be sure to follow-up and execute them.</p>
<p>If actions are agreed and nothing ever happens with them, it will destroy trust in the relationship.</p>
<p>Be the manager who shows that good ideas are acted upon. Show with your actions that what’s being said in a one-on-one is important to you. Build trustworthiness through your actions.</p>
<h3>8. A Dedicated Day for One-on-Ones</h3>
<p>Software development manager and blogger Ed Gibbs writes in <a href="http://edgibbs.com/2007/06/28/one-on-ones-in-a-single-day/" target="_blank" rel="noopener noreferrer">One-on-Ones in a Single Day</a> that he prefers to have all his one-on-ones in a single day (Wednesday).</p>
<p>The benefits are that it’s easier to defend a full day (than large chunks of time throughout the week), it frees large chunks of time on the other days for other activities, you are better prepared for the one-on-ones, and it gives you a better sense of how the whole team is doing.</p>
<h3>9. Try a Different Location</h3>
<p>Executive coach Beth Miller recommends in <a href="http://www.entrepreneur.com/article/238553" target="_blank" rel="noopener noreferrer">Revamp Your Approach to Monthly One-to-One Meetings</a> that you sometimes move away from the office to shake up the one-on-one, add a more casual theme to it and get to know your people on a different level.</p>
<p>For example, by going out for lunch or by going for a walk outside, which was a favorite of <a href="https://www.intelligent-quotes.com/steve-jobs" target="_blank" rel="noopener">Steve Jobs</a>.</p>
<p>At the end of the day, a one-on-one is an opportunity for your people to share their ideas, concerns and need for personal development. Your task as a manager is to ask good questions, listen to what is being said, provide sensible feedback, and follow-up constructively.</p>
<p>Some managers will undoubtedly read this and think that it sounds like a humongous time stealer from another dimension! But they must remember that their job is <i>management</i> and that one-on-ones are one of the most effective management tools out there.</p>
<p>In the words of Johanna Rothman, a bestselling author of software management books, “Managers who use one-on-one meetings consistently find them one of the most effective and productive uses of their management time.”</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Winston Churchill: A First-Class Writer</title>
		<link>https://kennethlange.com/winston-churchill-a-first-class-writer/</link>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Mon, 20 Aug 2012 08:12:04 +0000</pubDate>
				<category><![CDATA[History]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=261</guid>

					<description><![CDATA[Bernard Shaw wrote that, “the reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt&#8230;<p><a href="https://kennethlange.com/winston-churchill-a-first-class-writer/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Bernard Shaw wrote that, “<em>the reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt the world to himself. Therefore all progress depends on the unreasonable man.</em>” This statement is perhaps exemplified no place better than in the life of Winston Churchill, Shaw’s contemporary.</p>



<p class="wp-block-paragraph"><a href="https://www.intelligent-quotes.com/winston-churchill" data-type="link" data-id="https://www.intelligent-quotes.com/winston-churchill" target="_blank" rel="noreferrer noopener">Churchill</a> was born into an English aristocratic family with all the expensive habits of this class, but unfortunately his late father had failed to leave him a family fortune that is needed to sustain such a lifestyle. A reasonable man would have reduced his expenses to meet his actual income — but Churchill never thought small — so he decided to simply raise his income until it met his expenses and if his expenses outgrew his income again, he would simply grow his income even more.</p>



<p class="wp-block-paragraph">Now the curious reader will probably agree with Churchill’s logic in theory, but may ask if an English aristocrat in the 20th century was educated with lots of market-relevant skills that could actually produce an income? And on top of that a substantial income that could support an extravagance lifestyle with French champagne, Cuban cigars, world travels, country house, servants and so forth?</p>



<p class="wp-block-paragraph">To start from the beginning, when Churchill was a young officer in the British Army, he was desperate to seek out action as courage in battle was essential for promotion. So when a military expedition started in Northwestern India (today, Pakistan) to punish the local tribes, he wanted to join despite the travel expenses were more than what his mother’s endowment could support.  So he made an agreement with <em>The Daily Telegraph</em>, a newspaper, that he would write articles about the expedition to the newspaper in exchange for them paying his travel expenses.</p>


<div class="wp-block-image">
<figure class="aligncenter"><img loading="lazy" decoding="async" width="480" height="320" src="https://www.kennethlange.com/wp-content/uploads/2019/02/churchill_horse.jpg" alt="" class="wp-image-264" srcset="https://kennethlange.com/wp-content/uploads/2019/02/churchill_horse.jpg 480w, https://kennethlange.com/wp-content/uploads/2019/02/churchill_horse-300x200.jpg 300w" sizes="auto, (max-width: 480px) 100vw, 480px" /><figcaption class="wp-element-caption">Churchill as a young war correspondent (photo credit: <a rel="noreferrer noopener" target="_blank" href="http://commons.wikimedia.org/wiki/File:Churchill_gallery2.jpg">Wikimedia Commons)</a></figcaption></figure>
</div>


<p class="wp-block-paragraph">The series of articles showed that he had a talent for words and after the expedition had ended, he turned the articles into his first book, <a href="https://www.intelligent-quotes.com/winston-churchill/works/the-story-of-the-malakand-field-force" data-type="link" data-id="https://www.intelligent-quotes.com/winston-churchill/works/the-story-of-the-malakand-field-force" target="_blank" rel="noreferrer noopener">The Story of the Malakand Field Force</a>, which is still a highly readable book about his baptism of fire, which he describes as a delightful experience: “<em>Nothing in life is so exhilarating as to be shot at without result.</em>”</p>



<p class="wp-block-paragraph">Churchill quickly realized that his talent for words could be his road to financial freedom, so he continued to hone his writing skills and moved from journalism to more substantial literary works. He was never afraid of demanding a high fee for his writings and he refused to give in to anyone who wanted a low price. At some point the frugal Rockefeller family approached him to write the biography about the late John D. Rockefeller, supposedly the richest man in history, but the Rockefellers withdrew their offer in horror once they saw the fee that Churchill demanded for writing the biography. So Churchill never wrote the Rockefeller biography, but instead continued with other works supported by more generous sponsors.</p>



<h2 class="wp-block-heading">His Writing Habits</h2>



<p class="wp-block-paragraph">Obviously you can only demand unreasonable high fees, if your writings are of such an outstanding quality that people still think they get value for their money. And at the same time you need to produce them at a rapid pace, so your income stream doesn’t run dry. So how did Churchill manage to produce great works at a high speed while still having time for a political career?</p>



<p class="wp-block-paragraph">Churchill preferred <a rel="noreferrer noopener" target="_blank" href="http://www.winstonchurchill.org/learn/biography/the-wilderness/as-i-knew-him-churchill-in-the-wilderness">writing late in the evening</a> and usually started around 10 PM when dinner ended and continued writing until 2 AM. In these late-night writing sessions Churchill would be standing by his upright desk with a whisky soda in one hand and a cigar in the other while using his formidable oratory skills to turn historical events — for he wrote mostly about history and politics — into a captivating narrative that his sectary would dutifully write down. His research assistant would also be there ready to supply facts as needed and spot inaccuracies in the narrative.</p>


<div class="wp-block-image">
<figure class="aligncenter"><img loading="lazy" decoding="async" width="480" height="360" src="https://www.kennethlange.com/wp-content/uploads/2019/02/chartwell.jpg" alt="" class="wp-image-266" srcset="https://kennethlange.com/wp-content/uploads/2019/02/chartwell.jpg 480w, https://kennethlange.com/wp-content/uploads/2019/02/chartwell-300x225.jpg 300w" sizes="auto, (max-width: 480px) 100vw, 480px" /><figcaption class="wp-element-caption">Chartwell House: Churchill’s Victorian home where he wrote most of his books (photo credit: <a rel="noreferrer noopener" target="_blank" href="http://commons.wikimedia.org/wiki/File:Chartwell02.JPG">Wikimedia Commons</a>)</figcaption></figure>
</div>


<p class="wp-block-paragraph">As Churchill sharpened his writing skills over the years, he also developed a set of habits that he followed to produce his successful works:</p>



<ul class="wp-block-list">
<li><strong>Give the reader a good ride:</strong> When Churchill wrote <em>Marlborough: His Life and Times</em> he said to his research assistance, “<em>I aim to give the reader a good ride</em>”. This focus on telling a great story, rather than being overly analytical, is probably why his books are still a good read for the casual reader.</li>



<li><strong>Dictate, rather than write:</strong> Churchill dictated his words to his sectary, rather than writing them himself. The reason for this might be that speaking is the natural medium for a great orator, such a Churchill, so it gives the narrative a more natural flow. Another reason is that it’s faster to speak than to write, so he could simply get more done in less time by dictating.</li>



<li><strong>Use short words:</strong> Churchill said, “<em>Short words are best and the old words when short are best of all.</em>” Churchill knew that short English words (which are often derived from Anglo-Saxon, rather than Latin) have a more powerful effect on the reader. As noted in <a href="http://www.austincc.edu/history/inres10a4style.html" target="_blank" rel="noreferrer noopener">this style guide</a>, when Churchill asked for material help from America in the fight against Hitler, he didn’t say “<em>Deliver to us the implements, and we will complete the assignment</em>”, instead he simply said, “<em>Give us the tools, and we will finish the job.</em>“</li>



<li><strong>Seek feedback:</strong> When working on a manuscript Churchill was relentless in seeking feedback from others. For instance, when writing the Marlborough book he sent 308 letters asking for answers to specific questions, or for the recipient to review his manuscript.</li>



<li><strong>See it in print before it’s final:</strong> Churchill would always get his draft manuscript set up by a typographer and printed, so he could see what the final product might look like while he still had a chance to edit it — and this was before the computer, so it was a cumbersome process. Even if his publisher insisted that this was an unnecessary step in the creative process, Churchill would offer to pay for this out of his own pocket.</li>



<li><strong>Take a siesta:</strong> When Churchill was a young war correspondence in Cuba, he picked up two lifetime habits — the first being smoking Cuban cigars and the second being taking a siesta. At around 5 PM each day, he would sleep for 1½ hour and this was no power nap where he just sat in a chair. No, he would get his clothes off and go to a proper bed and sleep. Afterwards, he would take a bath and get dressed for dinner. Churchill said that taking a nap allowed him to work 1½ day in a single day and the nap was probably also needed to have the energy for his late-night writing sessions.</li>



<li><strong>Set a daily aim:</strong> While writing his biography on Marlborough and building a cottage, at the same time, Churchill had the aim of laying 200 bricks and writing 2,000 words per day. He knew if he managed to do both then it had been a good day.</li>
</ul>



<p class="wp-block-paragraph">Churchill followed these writing habits throughout most of his career and was a highly productive author who wrote 15 books — some of which were multi-volume works consisting of more than 4,000 pages — together with a vast amount of articles, speeches and letters. You can almost be surprised that he also had time for a political career…</p>



<h2 class="wp-block-heading">His Finest Hour</h2>



<p class="wp-block-paragraph">When Churchill was chosen as Prime Minister in 1940 to lead England in the war against Hitler, <a href="https://www.intelligent-quotes.com/winston-churchill/quote/walking-with-destiny" data-type="link" data-id="https://www.intelligent-quotes.com/winston-churchill/quote/walking-with-destiny" target="_blank" rel="noreferrer noopener">he wrote</a> in his diary, “<em>I felt as I was walking with destiny, and that all my past life had been but a preparation for this hour and for this trial.</em>”</p>



<p class="wp-block-paragraph">While his military and political careers had undoubtedly prepared him for this grand challenge, his mastery of words was an equally indispensible tool when he needed to strengthen the moral of the British people, which was seriously needed as Hitler continued to move from one aggressive triumph to another.</p>


<div class="wp-block-image">
<figure class="aligncenter"><img loading="lazy" decoding="async" width="480" height="422" src="https://www.kennethlange.com/wp-content/uploads/2019/02/coventry_cathedral.jpg" alt="" class="wp-image-267" srcset="https://kennethlange.com/wp-content/uploads/2019/02/coventry_cathedral.jpg 480w, https://kennethlange.com/wp-content/uploads/2019/02/coventry_cathedral-300x264.jpg 300w" sizes="auto, (max-width: 480px) 100vw, 480px" /><figcaption class="wp-element-caption">“Upon this battle depends the survival of Christian civilization…” (photo credit: <a rel="noreferrer noopener" target="_blank" href="http://commons.wikimedia.org/wiki/File:Winston_Churchill_walks_through_the_ruins_of_Coventry_Cathedral.jpg">Wikimedia Commons</a>)</figcaption></figure>
</div>


<p class="wp-block-paragraph">And Churchill did indeed mobilize his formidable writing skills in the defense of England. In less than two weeks, he wrote three speeches Blood, toil, tears and sweat, <a href="https://www.intelligent-quotes.com/winston-churchill/works/we-shall-fight-on-the-beaches" target="_blank" rel="noreferrer noopener">We shall fight on the beaches</a> and This was their finest hour which are all are among the greatest speeches delivered in the history of mankind.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Winston S Churchill: We Shall Fight on the Beaches" width="640" height="480" src="https://www.youtube.com/embed/MkTw3_PmKtc?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div><figcaption class="wp-element-caption">The voice of a master orator in action…</figcaption></figure>



<p class="wp-block-paragraph">And England did not back down, but stayed in the fight until Russia and America also joined the war effort and together they defeated Hitler and won the war.</p>



<p class="wp-block-paragraph">In 1953, his literary career was crowned with a Nobel Prize in Literature. When reading his books, or listening to his speeches during the war, you tend to agree with the Nobel committee that awarded him the prize for “<em>his mastery of historical and biographical description as well as for brilliant oratory in defending exalted human values.</em>“</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Writing Habits of Ian Fleming</title>
		<link>https://kennethlange.com/writing-habits-of-ian-fleming/</link>
					<comments>https://kennethlange.com/writing-habits-of-ian-fleming/#comments</comments>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Tue, 01 May 2012 13:41:21 +0000</pubDate>
				<category><![CDATA[History]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=252</guid>

					<description><![CDATA[Most people know James Bond, but fewer people know Ian Fleming who wrote the Bond novels, and even fewer know&#8230;<p><a href="https://kennethlange.com/writing-habits-of-ian-fleming/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Most people know James Bond, but fewer people know Ian Fleming who wrote the Bond novels, and even fewer know the leisurely, yet effective, habits he followed when writing the novels about the secret agent.</p>



<p class="wp-block-paragraph">Ian Fleming didn’t start writing until he was in his forties. Before his novelist occupation he had an admirable career in the British Naval Intelligence. During World War II he planned “<em>Operation Goldeneye</em>”, which was the contingency plan for how the British would defend Gibraltar, if the Germans had attacked it through Spain. He was also involved in “<em>Operation Mincemeat</em>”, which was a deception manoeuvre that misled the Germans into thinking that the Allied forces in Africa would invade Southern Europe through Greece, rather than Sicily where it actually happened. And after the D-Day, he helped selecting targets for T-Force, which was a special military unit that captured high-value targets (e.g. individual scientists, nuclear research, rocket technology) before the Russians got them.</p>



<p class="wp-block-paragraph">After the war he stopped in the Naval Intelligence with the rank of Commander and decided that his new objective in life would be the pursuit of pleasure. He secured a job as Foreign Manager at Kemsley Newspapers where his contract included 8 weeks of holiday per year, so that he could spend January and February in the Caribbean, rather than live through the cold winter in London.</p>



<p class="wp-block-paragraph">He bought a piece of land on Jamaica (then, a British Colony) with a private beach and reef, and got a local contractor to build a simple house with a great view of the Caribbean Sea. He christened the house Goldeneye.</p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="640" height="410" src="https://www.kennethlange.com/wp-content/uploads/2019/02/goldeneye.jpg" alt="" class="wp-image-255" srcset="https://kennethlange.com/wp-content/uploads/2019/02/goldeneye.jpg 640w, https://kennethlange.com/wp-content/uploads/2019/02/goldeneye-300x192.jpg 300w, https://kennethlange.com/wp-content/uploads/2019/02/goldeneye-624x400.jpg 624w" sizes="auto, (max-width: 640px) 100vw, 640px" /><figcaption class="wp-element-caption">Goldeneye (Image credit: <a rel="noreferrer noopener" target="_blank" href="https://commons.wikimedia.org/wiki/File:GoldeneyeEstate.jpg">Wikimedia Commons</a>)</figcaption></figure>



<p class="wp-block-paragraph">Goldeneye would always be the destination for Fleming’s long winter holiday, and he used these winter months in Jamaica for sunbathing on the beach, sailing out to the reef to swim with a mask and a spear, catch lobsters for dinner and entertain visitors from near and far.</p>



<p class="wp-block-paragraph">This easy and pleasurable life lasted rather uninterruptedly till 1952. Ian had been the most professional bachelor and had never established any deep emotional connections with any of his many girlfriends. However, at the age of forty-three he had finally ended up marrying his long-term mistress, Lady Anne Rothermere (later, Ann Fleming) as he had made her pregnant and her husband therefore wanted to divorce her.</p>



<p class="wp-block-paragraph">That winter due to the pressure caused by the pending divorce, there weren’t many visitors to Goldeneye. There were many different worries that haunted Fleming. Would he manage to take care of a family at this age? Would it change his life? Would he be able to provide Ann with the same stability as her former and much wealthier husband, Lord Rothermere? All those questions kept circling around in his head, but remained unanswered…</p>



<p class="wp-block-paragraph">Ann kept herself occupied by sitting in the garden wearing her large straw hat and painting flowers. Ian didn’t find any pleasure in painting, so Ann suggested that he should start writing something to distract his thoughts.</p>



<p class="wp-block-paragraph">So to “<em>take my mind of the shock at getting married at the age of forty-three</em>” as he later said, he decided to write the spy novel to end all spy novels, and gave it the title <a href="https://www.intelligent-quotes.com/ian-fleming/works/casino-royale" data-type="link" data-id="https://www.intelligent-quotes.com/ian-fleming/works/casino-royale" target="_blank" rel="noreferrer noopener">Casino Royale</a>.</p>



<p class="wp-block-paragraph">Ian was a man with a boyish enthusiasm, so when he started such a project, he poured all his energy into it. He was also a man of habits, so he integrated writing into his daily routine, which he would follow day in and day out without exceptions.</p>



<h2 class="wp-block-heading">His Daily Routine</h2>



<p class="wp-block-paragraph">He started his day with a morning swim in the Caribbean Sea followed by a breakfast with Ann. The breakfast always consisted of scrambled eggs, bacon and black coffee as he insisted that tea tasted like mud and was the reason behind the decline of the British Empire.</p>



<p class="wp-block-paragraph">At 9am, he would give Ann a kiss, leave the breakfast table and go inside into the main living room in Goldeneye. He would close the jalousied windows to create a cool and shady room with a hint of a tropical breeze. Then he would take out his old Imperial portable typewriter and type for the next three hours.</p>



<p class="wp-block-paragraph">He used his wartime experiences as a starting point for activating his imagination and created the world of James Bond. He would write non-stop and wouldn’t worry about what he would put in as he could always edit it later.</p>



<p class="wp-block-paragraph">At noon, he would stop writing and go outside in the warm Jamaican sun. Together with Ann he would go down to the beach to sunbathe and swim before lunch. After lunch, he would sleep for an hour or two.</p>



<p class="wp-block-paragraph">Around 5pm, he would be ready to continue his work. He would go into the main living room again, and use an hour or so to read through what he had written during the day and make the necessary corrections. After he finished the corrections, he would take the papers and place them in a drawer and thereby end his workday. And by 6:30, he was ready for his first drink of the day and to enjoy the evening without worrying about his work.</p>



<p class="wp-block-paragraph">Six weeks after Ian had started writing for the first time, he completed <a href="https://www.intelligent-quotes.com/ian-fleming/works/casino-royale" data-type="link" data-id="https://www.intelligent-quotes.com/ian-fleming/works/casino-royale" target="_blank" rel="noreferrer noopener">Casino Royale</a>. The novel was a tour through a world of gambling, violence, betrayal, torture and sex. By the end of the tour, Le Chiffre (the bad guy) had been annihilated, and so had Vesper Lynd (the girl), while Bond had completed his first mission.</p>



<p class="wp-block-paragraph">And for the next many years, Ian would continue to follow this elaborate, yet simple, writing schedule and complete a new Bond novel at Goldeneye each winter.</p>



<h2 class="wp-block-heading">Why Did He Follow a Routine?</h2>



<p class="wp-block-paragraph">His writing habits raise some interesting questions. The first is why would a man of creativity and imagination, like Ian Fleming, follow such a strict regime, rather than just write whenever he felt like it? Obviously it served as a reliable safeguard against abandoning a project when feeling moody or unmotivated. He would later advise another writer that you should always follow your routine, because that will keep you going even when you feel that your writing is nonsense and nobody will ever read it.</p>



<p class="wp-block-paragraph">Another interesting question is how he managed to be so productive when only putting in 4 hours of actual work per day? The reason must be that he was much more effective during those hours than an average person. He had the luxury of not being interrupted and did not engage in any activities that were not related to the task at hand. He completely focused on the single task of writing this particular novel what probably helped him enter a flow mode where he was extremely productive.</p>



<p class="wp-block-paragraph">Another reason could be that writing was his true vocation in life, which is why once started, it went so effortlessly that he only needed to spend only a few hours per day and yet remain efficient. He was undoubtedly gifted with an extraordinary imagination and ability to generate ideas (which had also served him good in his previous occupation), but he was also able to create an environment where these talents were expressed most effectively. Fleming certainly had talents, but he was also able to use them to their outmost when writing his novels, which was for the overall benefit — of his own and of his grateful readers.</p>



<p class="wp-block-paragraph">There are some important lessons to be learned from Ian Fleming’s writing habits. The first is that a single-minded focus on a specific task for three hours in a row without any risk of interruptions enables you to enter a flow mode where you can enjoy a much higher productivity and creativity. The second is that forcing yourself to take daily actions, regardless of the mood, will eventually lead to success. But was Fleming successful? I would say so. His Bond novels have sold more than 100,000,000 copies, which seems like a fair amount for a project that just aimed at distracting him from the fact that he was getting married a little late.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://kennethlange.com/writing-habits-of-ian-fleming/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>3 Writing Tips from Hemingway</title>
		<link>https://kennethlange.com/3-writing-tips-from-hemingway/</link>
					<comments>https://kennethlange.com/3-writing-tips-from-hemingway/#comments</comments>
		
		<dc:creator><![CDATA[Kenneth Lange]]></dc:creator>
		<pubDate>Tue, 01 May 2012 06:59:21 +0000</pubDate>
				<category><![CDATA[History]]></category>
		<guid isPermaLink="false">https://www.kennethlange.com/?p=258</guid>

					<description><![CDATA[Ernest Hemingway is one of the best known authors of the 20th century. He wrote classics such as A Farewell&#8230;<p><a href="https://kennethlange.com/3-writing-tips-from-hemingway/" class="btn-more">Read More<span class="arrow-more">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Ernest Hemingway is one of the best known authors of the 20th century. He wrote classics such as <a href="https://www.intelligent-quotes.com/ernest-hemingway/works/a-farewell-to-arms" data-type="link" data-id="https://www.intelligent-quotes.com/ernest-hemingway/works/a-farewell-to-arms" target="_blank" rel="noreferrer noopener">A Farewell to Arms</a>, <a href="https://www.intelligent-quotes.com/ernest-hemingway/works/for-whom-the-bell-tolls" data-type="link" data-id="https://www.intelligent-quotes.com/ernest-hemingway/works/for-whom-the-bell-tolls" target="_blank" rel="noreferrer noopener">For Whom the Bell Tolls</a> and <a href="https://www.intelligent-quotes.com/ernest-hemingway/works/the-old-man-and-the-sea" data-type="link" data-id="https://www.intelligent-quotes.com/ernest-hemingway/works/the-old-man-and-the-sea" target="_blank" rel="noreferrer noopener">The Old Man and the Sea</a> — and his literary achievements were crowned with a Noble Prize in Literature in 1954.</p>



<p class="wp-block-paragraph">His mastery of the word was gained over a lifetime as a journalist and author where he gradually learned the do’s and don’ts of writing. In this post I’d like to share three of the best tips he ever gave to other authors about the secrets of great writing.</p>



<h2 class="wp-block-heading">1. Write in the Morning</h2>



<p class="wp-block-paragraph">Hemingway was a firm believer in writing in the morning — from around 9am till 2pm — because he could start with a fresh mind after a night of sleeping. He knew that a clear mind was essential, so he resisted reading anything before he started writing. He believed that reading other people’s words would fill his mind with their ideas and drown his own true voice.</p>



<p class="wp-block-paragraph">He also learned that the morning was the part of the day where he was most likely to avoid interruptions. Similarly, he knew that the thought of writing in a café was seductive to most authors, but the harsh reality was that authors need tranquillity to write. His own experience proved that sitting alone in his hotel room in the morning he was much more likely to produce great literature than in a busy, noisy café with endless possibilities of being interrupted.</p>



<h2 class="wp-block-heading">2. Don’t Empty the Well</h2>



<p class="wp-block-paragraph">Hemingway knew the importance of breaks in creative work. He was careful never to <em>empty the well</em>, which means keep writing until you are completely drained. Rather, he would stop writing while he knew exactly what to write next.</p>



<p class="wp-block-paragraph">His experience was that if he let a little water stay in the well (<em>i.e.,</em> not drained himself of ideas), it would automatically replenish during the non-writing part of his day and his mind would be full of creativity the next morning when he would start writing again.</p>



<p class="wp-block-paragraph">He also firmly resisted talking or thinking about his writing during the non-writing part of his day, because the unconscious mind should have peace to replenish the well without being interrupted by the conscious mind. So if he started thinking of his story, he would immediately force himself to think of something else.</p>



<h2 class="wp-block-heading">3. Be Concise</h2>



<p class="wp-block-paragraph">Hemingway started his career as a newspaper reporter when telegrams were charged by the number of words in them. In this way he learned early to keep his writing concise and use short declarative sentences.</p>



<p class="wp-block-paragraph">He wrote only about 400-600 words per day — in comparison this post is 520 words — but was careful to select the right words. Some were surprised about how few words he produced per day and questioned his tight style. So to prove his point Hemingway made a bet with a few other writers whether he could write a story in just six words. He won the bet by writing on a napkin: <em>For sale: Baby shoes, never worn</em>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://kennethlange.com/3-writing-tips-from-hemingway/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
	</channel>
</rss>
