<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Emil Broman on Medium]]></title>
        <description><![CDATA[Stories by Emil Broman on Medium]]></description>
        <link>https://medium.com/@emilniklas?source=rss-5fd35747355f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*u1Yvy57loAZDlM5u9-lWGw@2x.jpeg</url>
            <title>Stories by Emil Broman on Medium</title>
            <link>https://medium.com/@emilniklas?source=rss-5fd35747355f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 07:35:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@emilniklas/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Pure Objects — a Vision For the Next Generation of Object Oriented Programming Languages]]></title>
            <link>https://medium.com/@emilniklas/pure-objects-a-vision-for-the-next-generation-of-object-oriented-programming-languages-6426c82b48c5?source=rss-5fd35747355f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6426c82b48c5</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[programming-languages]]></category>
            <dc:creator><![CDATA[Emil Broman]]></dc:creator>
            <pubDate>Thu, 06 Sep 2018 07:58:27 GMT</pubDate>
            <atom:updated>2018-09-06T07:58:27.919Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve studied object-oriented programming, you’ve likely come across the “three principles of object-oriented programming”. These are said to be:</p><ul><li>Encapsulation</li><li>Inheritance</li><li>Polymorphism</li></ul><p>You might also have heard that the definition of an object is a unit of computation, which contains data, but only exposes mechanisms for mutating that data through accepting messages from other objects, invoking methods on the object.</p><p>But then you might have been introduced to concepts like <a href="https://en.wikipedia.org/wiki/Composition_over_inheritance">“Composition over Inheritance”</a>. Or told about the <a href="https://www.johndcook.com/blog/2011/07/19/you-wanted-banana/">“Monkey/Banana Problem”</a>, or shown the <a href="https://en.wikipedia.org/wiki/Fragile_base_class">“Fragile Base Class”</a>, or the <a href="https://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem">“Diamond Problem”</a>.</p><p>So when someone — a coworker, a friend, or a “thought leader” — told you that functional programming is “better” than OOP, you were ripe for convincing.</p><p>The functional paradigm promised better reasoning, better reusability, improved error handling, easy(!) concurrency. Indeed, functional programming languages have a long list of utilities that supposedly makes OOP “obsolete”.</p><p>In my mind, most — if not all — of these advantages stem from the functional languages’ implementation of pure immutability. And it seems like this property is diametrically opposed to the concept of an object. Because objects are supposed to contain mutable state, right?</p><p>No, I don’t think so. Objects are supposed to represent the states of things in the natural world, but that definition says nothing about mutability. I reached this conclusion after reading <a href="https://www.quora.com/Why-is-functional-programming-seen-as-the-opposite-of-OOP-rather-than-an-addition-to-it/answer/Alan-Kay-11">this Quora answer from Alan Kay</a> (famously the “father of OOP”). In the post, Alan writes the following:</p><blockquote>[…] this would allow “real objects” to be world-lines of their stable states and they could get to their next stable state in a completely functional manner. In the Strachey sense, they would be “viewing themselves” with no race conditions to get their next version.</blockquote><p>So I took another look at the dominating object-oriented languages, and realized it was completely possible to “translate” every concept into its immutable counterpart. Let’s take a look!</p><pre>public class Account {<br>    private int balance = 0;</pre><pre>    public void deposit(int amount) {<br>        balance += amount;<br>    }</pre><pre>    public void withdraw(int amount) {<br>        balance -= amount;<br>    }</pre><pre>    public int getBalance() {<br>        return balance;<br>    }<br>}</pre><p>This would probably be the canonical example of encapsulation in OOP. Before looking at its immutable sibling, let’s remove some of the sugar that the language (Java in this example) gives us.</p><pre>public class Account {<br>    private int balance;</pre><pre><strong>    public Account() {<br>        this.balance = 0;<br>    }</strong></pre><pre>    public void deposit(int amount) {<br>        <strong>this.balance = this.balance + amount;</strong><br>    }</pre><pre>    public void withdraw(int amount) {<br>        <strong>this.balance = this.balance - amount;</strong><br>    }</pre><pre>    public int getBalance() {<br>        return <strong>this.balance</strong>;<br>    }<br>}</pre><p>What becomes clear here is that the constructor receives an implicit argument called <strong>this</strong>, which looks sort of like a struct from lower level languages. The <strong>dollars</strong> instance variable is initialized to <strong>0</strong>. The <strong>deposit</strong> and <strong>withdraw</strong> methods receive the same implicit argument, which it can both read from and write to.</p><p>A good OOP practitioner will tell you to separate the methods that return information about the object from the methods that change the object. This is referred to as “Command/Query Separation” or CQS. The <strong>void</strong> return type from the methods that <em>change</em> the state communicates that mutation. So even though you can mutate an object and return a value, it’s not good practice.</p><p>Let’s return to Kay’s essay: <em>“[…] this would allow “real objects” to be world-lines of their stable states and they could get to their next stable state […]”</em>. This suggests the implementation of immutable objects, of which <a href="https://medium.com/@emilniklas/functional-objects-in-javascript-7ded06948819">I have written before</a>. That would transform our Java class into this:</p><pre>public class Account {<br>    private <strong>final</strong> int balance;</pre><pre>    private Account(<strong>int balance</strong>) {<br>        this.balance = <strong>balance</strong>;<br>    }</pre><pre>    <strong>public Account() {<br>        this(0);<br>    }</strong></pre><pre>    public <strong>Account</strong> deposit(int amount) {<br>        <strong>return new Account(balance + amount);</strong><br>    }</pre><pre>    public <strong>Account</strong> withdraw(int amount) {<br>        <strong>return new Account(balance - amount);</strong><br>    }</pre><pre>    public int getBalance() {<br>        return balance;<br>    }<br>}</pre><p>The key here is that the methods that previously returned <strong>void</strong> (the “command” methods in CQS terminology) now return new instances of <strong>Account</strong>. Indeed, the objects “get to their next stable state” by “viewing themselves”.</p><p>This is not an entirely uncommon pattern, but it’s much more verbose than the original class. That’s because Java wasn’t <em>designed</em> around classes looking like this.</p><p>So what would it look like if there was a language that <em>was</em> designed around immutable objects? What if we took at as far as it can go? How would an object oriented language look if it was as religious about immutability as Haskell?</p><h3>The WorldLines Programming Language</h3><p>In honor of Kay, let’s create an imaginary language called WorldLines. Let’s walk through the implications of removing mutable state from a Java-like language.</p><h4>1. The Type of This</h4><p>Within a method of a Java class, the implicit <strong>this</strong> variable has the type of the class that we’re currently editing. It is guaranteed to be a <em>covariant </em>of the current class, meaning that if we’re editing the class <strong>Mammal</strong>, we know that <strong>this</strong> is an <strong>Animal</strong>, as well. It <em>can</em>, however, also be a <strong>Dog</strong>, if the method is inherited. We can check for and cast to that case, but we generally avoid doing so, in favor of polymorphism.</p><pre>public class Animal {}</pre><pre>public class Mammal extends Animal {<br>    public void method() {<br>        // `this` is known to be both an<br>        // Animal and a Mammal, but<br>        // might very well be a a Dog.<br>    }<br>}</pre><pre>public class Dog extends Mammal {}</pre><p>When we change the state of the object, the type is stable. It doesn’t change. So a method that is known to change something in the Mammal class is known to change the same thing inside a Dog object, without the Dog changing type.</p><p>This is not the case for our immutable implementation in Java. A change to a Mammal object must return a new Mammal, and so our Dog stops being a Dog.</p><p>To fix this, we need to invent a way to represent the immutable change to an object without changing its identity. In functional languages, struct-like data known as records are changed by applying a “patch” to an existing instance of the record, retaining the non-patched fields’ values.</p><p>So we’ll invent a <strong>patch</strong> keyword! It works like this:</p><pre>Mammal mammal = new Dog();<br>Mammal mammal2 = <strong>patch</strong> (mammal)<br>    ..accessibleField = &quot;new value&quot;<br>    ..otherField = 123;<br>assert(mammal2 instanceof Dog);<br>assert(mammal2.accessibleField == &quot;new value&quot;);</pre><p>Let’s rewrite our <strong>Account</strong> class with this new construct:</p><pre>public class Account {<br><strong>    private int balance = 0;</strong></pre><pre>    public Account deposit(int amount) {<br>        return <strong>patch (this)<br>            ..balance = balance + amount;</strong><br>    }</pre><pre>    public Account withdraw(int amount) {<br>        return <strong>patch (this)<br>            ..balance = balance -amount;</strong><br>    }<br>    ...<br>}</pre><p>Note that we can now remove our constructors and reclaim the initializer, since we have a way to create new instances without using a constructor. But we still have a problem. Consider the following:</p><pre>public class PremiumAccount extends Account {}</pre><pre>PremiumAccount account = new PremiumAccount();<br><strong><em>PremiumAccount</em></strong> account2 = <strong><em>account.deposit(19)</em></strong>;</pre><p>The return type of <strong>deposit</strong> is still just <strong>Account</strong>, and would have to be downcast to <strong>PremiumAccount</strong>. Not optimal!</p><p>The <strong>patch</strong> expression returns an object with the same type as the one being patched. So how do we encode that the <strong>this’s</strong> type is returned? We’ll take inspiration from <a href="https://www.typescriptlang.org/">TypeScript</a> here, and introduce a <a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html#polymorphic-this-types"><strong>this</strong></a> type.</p><pre>public class Account {<br>    ...<br>    public <strong>this</strong> deposit(int amount) {<br>        return patch (this)<br>            ..balance = balance + amount;<br>    }</pre><pre>    public <strong>this</strong> withdraw(int amount) {<br>        return patch (this)<br>            ..balance = balance -amount;<br>    }<br>    ...<br>}</pre><h4>2. Scaling Up</h4><p>In an environment where <em>every</em> class is written like this (since there is no alternative), if a method on one class forwards a message to a member, and so on, the composition of immutable objects seamlessly fit together:</p><pre>public class A {<br>    private int state = 0;<br>    public this updateA() {<br>        return patch (this)<br>            ..state = state + 1;<br>    }<br>}</pre><pre>public class B {<br>    private A a = new A();<br>    public this updateB() {<br>        return patch (this)<br>            ..a = a.updateA();<br>    }<br>}</pre><pre>public class C {<br>    private B b = new B();<br>    public this updateC() {<br>        return patch (this)<br>            ..b = b.updateB();<br>    }<br>}</pre><pre>C c = new C().updateC().updateC(); // c.b.a.state == 2</pre><h4>3. Collateral Improvement</h4><p>These small changes propagate through the design of the language and the APIs that emerge from it. For instance, we’ve inadvertently made it impossible to violate the <a href="https://en.wikipedia.org/wiki/Law_of_Demeter">Law of Demeter</a>, because if you did <strong>new C().getB().getA().updateA()</strong>, you would get a new <strong>A</strong> back, and the original <strong>A</strong> within the <strong>B</strong> within the <strong>C</strong> would be unchanged.</p><p>Another effect of this is that a class with no constructor is a constant object. Think about it; the only way to have meaningful differences between two new instances is if you send in different arguments into their constructors. If the constructor has no parameters, then this would be true:</p><pre>assert(new X() == new X());</pre><p>Therefore, we might consider changing the behaviour of the constructor to be more like <em>the initial patch</em>:</p><pre>public class ClassWithACompleteInitialState {<br>    private int state = 10;</pre><pre>    public this doubleState() {<br>        patch (this)<br>            ..state = state * 2;<br>    }<br>}</pre><pre>public class ClassWithAConstructor {<br>    private int state;</pre><pre>    public ClassWithAConstructor(int state)<br>        ..state = state;</pre><pre>    public this doubleState() {<br>        patch (this)<br>            ..state = state * 2;<br>    }<br>}</pre><pre>ClassWithACompleteInitialState; // A constant object<br>ClassWithAConstructor; // (int) -&gt; ClassWithAConstructor</pre><pre>ClassWithACompleteInitialState.doubleState();<br>ClassWithAConstructor(20).doubleState();</pre><h4>4. Side Effects</h4><p>So how <em>would</em> you perform side effects in this system? There’s this word that keep coming up in functional programming; <em>monad</em>. Most people think it’s very hard to understand what a monad is. All they know is that monads supposedly make side effects pure in functional languages.</p><p>I’m happy to tell you that you’ve probably already used a monadic object. For instance, in JavaScript, the <strong>Promise</strong> is a monadic object. In C#, the <strong>IEnumerable</strong> interface’s extension methods provided by <em>Linq</em> is implemented in a monadic way.</p><p>It all boils down to an object (or a function in FP) representing a changed/changing state even before the change has happened, allowing chaining of other operations to be appended to the same pure object.</p><pre>public class Database {<br>    public Promise&lt;void&gt; execute(String query) { ... }<br>}</pre><pre>public Promise&lt;void&gt; setup(Database db) {<br>    return db.execute(&quot;CREATE TABLE users ...&quot;)<br>        .then(() -&gt;<br>            db.execute(&quot;INSERT INTO users ...&quot;)<br>        );<br>}</pre><pre>public Promise&lt;void&gt; main() {<br>    return connectToDatabase(&quot;postgres://...&quot;).then(setup);<br>}</pre><p>The <strong>then</strong> calls (or <strong>flatMap/map</strong> in more explicitly functional languages like Scala) can be syntactically sugared to reduce some of the noise. JavaScript, C#, Dart, and others have <strong>async/await</strong>. Haskell has <strong><em>do</em></strong><em> notation</em>. Scala has <strong><em>for </em></strong><em>comprehensions</em>. Choose your favorite!</p><h3>Summary</h3><p>Functional languages are very different from object oriented languages today. But I think that without changing the fundamental principles of OOP, we can still have a lot of the benefits that FP has, by fully embracing immutable objects.</p><p>We can keep our <strong>encapsulation</strong>, our subtype <strong>polymorphism</strong> (as opposed to <a href="https://en.wikipedia.org/wiki/Parametric_polymorphism">parametric polymorphism</a> common in FP), and even our <strong>inheritance</strong>, without leaving the world of immutability and <a href="https://en.wikipedia.org/wiki/Referential_transparency">referential transparency</a>. Then we can adopt the laziness of languages like Haskell.</p><p>The conflict between functional languages and the <em>principles</em> of OOP only lies in code organization, and how polymorphism is achieved (subtype vs parametric). The rest is just syntax and preference.</p><p>I sure hope we’ll see competitive languages in this paradigm come out in the next few years.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6426c82b48c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Immutable State Classes and React]]></title>
            <link>https://medium.com/@emilniklas/immutable-state-classes-and-react-f2ac36456502?source=rss-5fd35747355f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2ac36456502</guid>
            <category><![CDATA[immutability]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Emil Broman]]></dc:creator>
            <pubDate>Thu, 28 Jun 2018 19:58:28 GMT</pubDate>
            <atom:updated>2018-06-28T19:58:28.285Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>TL;DR:</strong> Classes can be used as well defined pieces of immutable state, with operations applied to the state expressed as methods. These classes can be used to encapsulate state in your React application, and compose nicely.</p><p>I want to introduce to you a pattern that I’ve been getting into for handling state, and more notably, state changes, in React applications. To demonstrate, I’ll use the canonical example — a Todo list.</p><p>We’re going to start out small, and refactor into the pattern that I’m calling: “Immutable State Class”. Let’s go!</p><pre><strong>class TodoList extends React.Component {<br>  state = {<br>    todos: []<br>  }</strong></pre><pre><strong>  render () {<br>    return (<br>      &lt;ul&gt;<br>        {this.state.todos.map(todo =&gt; (<br>          &lt;li key={todo.id}&gt;<br>            {todo.title}<br>            {todo.isCompleted ? (<br>              &lt;span&gt;Completed!&lt;/span&gt;<br>            ) : null}<br>          &lt;/li&gt;<br>        )}<br>      &lt;/ul&gt;<br>    )<br>  }<br>}</strong></pre><p>We start out with an empty list of todos. We can see in our render method that each todo item must have an <strong>id</strong>, a <strong>title</strong>, and a boolean field <strong>isCompleted</strong>.</p><p>So, let’s add a very basic way to add a todo. This is our first state change.</p><pre><strong>let ID = 0</strong></pre><pre>class TodoList extends React.Component {<br>  state = {<br>    todos: []<br>  }</pre><pre>  <strong>newTodoTitleInput = React.createRef()</strong></pre><pre><strong>  addTodo = () =&gt; {  <br>    const input = this.newTodoTitleInput.current<br>    const todo = {<br>      id: ++ID,<br>      title: input.value,<br>      isCompleted: false<br>    }<br>    this.setState(state =&gt; ({<br>      todos: [...state.todos, todo]<br>    })<br>    input.value = &#39;&#39;<br>  }</strong></pre><pre>  render () {<br>    return (<br>      &lt;&gt;<br>        &lt;ul&gt;<br>          {this.state.todos.map(todo =&gt; (<br>            &lt;li key={todo.id}&gt;<br>              {todo.title}<br>              {todo.isCompleted ? (<br>                &lt;span&gt;Completed!&lt;/span&gt;<br>              ) : null}<br>            &lt;/li&gt;<br>          )}<br>        &lt;/ul&gt;<br>        <strong>&lt;input ref={this.newTodoTitleInput} /&gt;<br>        &lt;button onClick={this.addTodo}&gt;Add Todo&lt;/button&gt;<br>      </strong>&lt;/&gt;<br>    )<br>  }<br>}</pre><p>Of course we can make the input controlled instead of using a ref, but that’s not important right now. What’s important is this: we’re reaching for the most basic way of handling state in React: setting a new state in a method in the component class, triggered by an event listener registered in the render method.</p><p>Next up, we want to be able to mark todo items as completed.</p><pre>let ID = 0</pre><pre>class TodoList extends React.Component {<br>  state = {<br>    todos: []<br>  }</pre><pre>  newTodoTitleInput = React.createRef()</pre><pre>  addTodo = () =&gt; {  <br>    const input = this.newTodoTitleInput.current<br>    const todo = {<br>      id: ++ID,<br>      title: input.value,<br>      isCompleted: false<br>    }<br>    this.setState(state =&gt; ({<br>      todos: [...state.todos, todo]<br>    })<br>    input.value = &#39;&#39;<br>  }</pre><pre>  <strong>toggleTodo = todo =&gt; () =&gt; {<br>    this.setState(state =&gt; ({<br>      todos: state.todos.map(t =&gt;<br>        t.id === todo.id<br>          ? { ...t, isCompleted: !t.isCompleted }<br>          : t<br>      )<br>    })<br>  }</strong></pre><pre>  render () {<br>    return (<br>      &lt;&gt;<br>        &lt;ul&gt;<br>          {this.state.todos.map(todo =&gt; (<br>            &lt;li key={todo.id}&gt;<br>              {todo.title}<br><strong>              &lt;input<br>                type=&#39;checkbox&#39;<br>                checked={todo.isCompleted}<br>                onChange={this.toggleTodo(todo)}<br>              /&gt;</strong><br>            &lt;/li&gt;<br>          )}<br>        &lt;/ul&gt;<br>        &lt;input ref={this.newTodoTitleInput} /&gt;<br>        &lt;button onClick={this.addTodo}&gt;Add Todo&lt;/button&gt;<br>      &lt;/&gt;<br>    )<br>  }<br>}</pre><p>All right, so at this point it’s not <em>too</em> bad, but the component is starting to get muddy, and it’s only going to get worse. So we’ll step back and think about what this component is really doing:</p><ul><li>There’s a list of todo items, rendered into an unordered list.</li><li>There’s also a text input and a button. When the button is pressed, the text input’s value is used to create a new todo item in the list.</li><li>There’s a checkbox next to each item, indicating whether the item is checked or not. Clicking the checkbox toggles the item’s completion state.</li></ul><p>Now for the refactor. We’ll start out by creating a class, moving that initial state into the constructor:</p><pre><strong>class TodoListState {<br>  constructor (todos = []) {<br>    this.todos = todos<br>  }<br>}</strong></pre><p>To add a todo, the title of the new todo is required. Since we want to preserve immutability, we’ll need to return a new instance of the class <em>with the new todo added</em>.</p><pre><strong>let ID = 0</strong></pre><pre>class TodoListState {<br>  constructor (todos = []) {<br>    this.todos = todos<br>  }</pre><pre> <strong> addTodo (title) {<br>    const todo = {<br>      id: ++ID,<br>      title,<br>      isCompleted: false<br>    }<br>    return new TodoListState([...this.todos, todo])<br>  }</strong><br>}</pre><p>Pretty straight forward! Let’s do the same thing with the <strong>toggleTodo</strong> method.</p><pre>let ID = 0</pre><pre>class TodoListState {<br>  constructor (todos = []) {<br>    this.todos = todos<br>  }</pre><pre>  addTodo (title) {<br>    const todo = {<br>      id: ++ID,<br>      title,<br>      isCompleted: false<br>    }<br>    return new TodoListState([...this.todos, todo])<br>  }</pre><pre>  <strong>toggleTodo (todo) {<br>    return new TodoListState(<br>      this.todos.map(t =&gt;<br>        t.id === todo.id<br>          ? { ...t, isCompleted: !t.isCompleted }<br>          : t<br>      )<br>    )<br>  }</strong><br>}</pre><p>Let’s see what happens to our component when we integrate it with this new class.</p><pre>class TodoList extends React.Component {<br>  state = {<br>    <strong>listState: new TodoListState()</strong><br>  }</pre><pre>  newTodoTitleInput = React.createRef()</pre><pre><strong>  addTodo = () =&gt; {  <br>    const input = this.newTodoTitleInput.current<br>    this.setState(state =&gt; ({<br>      listState: state.listState.addTodo(input.value)<br>    })<br>    input.value = &#39;&#39;<br>  }</strong></pre><pre>  <strong>toggleTodo = todo =&gt; () =&gt; {<br>    this.setState(state =&gt; ({<br>      listState: state.listState.toggleTodo(todo)<br>    })<br>  }</strong></pre><pre>  render () {<br>    return (<br>      &lt;&gt;<br>        &lt;ul&gt;<br>          {<strong>this.state.listState.todos</strong>.map(todo =&gt; (<br>            &lt;li key={todo.id}&gt;<br>              {todo.title}<br>              &lt;input<br>                type=&#39;checkbox&#39;<br>                checked={todo.isCompleted}<br>                onChange={this.toggleTodo(todo)}<br>              /&gt;<br>            &lt;/li&gt;<br>          )}<br>        &lt;/ul&gt;<br>        &lt;input ref={this.newTodoTitleInput} /&gt;<br>        &lt;button onClick={this.addTodo}&gt;Add Todo&lt;/button&gt;<br>      &lt;/&gt;<br>    )<br>  }<br>}</pre><p>Pretty cool, right? Now, let’s perform another common refactor: pulling the state up-and-out of the component. We’ll replace the state with conventional <strong>value</strong> and <strong>onChange</strong> props:</p><pre>class TodoList extends React.Component {<br><strong>  static propTypes = {<br>    value: PropTypes.instanceOf(TodoListState).isRequired,<br>    onChange: PropTypes.func.isRequired,<br>  }</strong></pre><pre>  newTodoTitleInput = React.createRef()</pre><pre>  addTodo = () =&gt; {  <br>    const input = this.newTodoTitleInput.current<br> <strong>   this.props.onChange(<br>      this.props.value.addTodo(input.value)<br>    )</strong><br>    input.value = &#39;&#39;<br>  }</pre><pre>  toggleTodo = todo =&gt; () =&gt; {<br>    <strong>this.props.onChange(<br>      this.props.value.toggleTodo(todo)<br>    )</strong><br>  }</pre><pre>  render () {<br>    return (<br>      &lt;&gt;<br>        &lt;ul&gt;<br>          {<strong>this.props.value</strong>.todos.map(todo =&gt; (<br>            &lt;li key={todo.id}&gt;<br>              {todo.title}<br>              &lt;input<br>                type=&#39;checkbox&#39;<br>                checked={todo.isCompleted}<br>                onChange={this.toggleTodo(todo)}<br>              /&gt;<br>            &lt;/li&gt;<br>          )}<br>        &lt;/ul&gt;<br>        &lt;input ref={this.newTodoTitleInput} /&gt;<br>        &lt;button onClick={this.addTodo}&gt;Add Todo&lt;/button&gt;<br>      &lt;/&gt;<br>    )<br>  }<br>}</pre><p><em>That’s right, there’s a way to specify class instances in prop types! Out of the box!</em></p><p>So how does this pattern scale, you might ask? Without changing the API of the <strong>TodoListState</strong> class, we can extract the state of each individual todo item into its own class:</p><pre><strong>class TodoState {<br>  constructor ({ id, title, isCompleted = false }) {<br>    this.id = id<br>    this.title = title<br>    this.isCompleted = isCompleted<br>  }</strong></pre><pre><strong>  toggle () {<br>    return new TodoState({<br>      id: this.id,<br>      title: this.title,<br>      isCompleted: !this.isCompleted<br>    })<br>  }<br>}</strong></pre><p>Our <strong>TodoListState</strong> now looks like this:</p><pre>let ID = 0</pre><pre>class TodoListState {<br>  constructor (todos = []) {<br>    this.todos = todos<br>  }</pre><pre>  addTodo (title) {<br><strong>    const todo = new TodoState({<br>      id: ++ID,<br>      title<br>    })</strong><br>    return new TodoListState([...this.todos, todo])<br>  }</pre><pre>  toggleTodo (todo) {<br>    return new TodoListState(<br>      this.todos.map(t =&gt;<br>        t.id === todo.id<br>          <strong>? t.toggle()</strong><br>          : t<br>      )<br>    )<br>  }<br>}</pre><p>Because all state classes are immutable, they compose together. Changing a todo means getting a new state. Changing it within a todo list means getting a new list.</p><p>Try this pattern, and see what you think. There’s no library to install, and it doesn’t conflict with existing ways of managing state. In fact, the pattern is used in <a href="https://draftjs.org/">DraftJS,</a> where the <strong>Editor</strong> component uses an <strong>EditorState</strong> instance as its <strong>value</strong>, exposing ways of transforming the state of the text editor using methods.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2ac36456502" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The JavaScript object that will completely kill your entire application.]]></title>
            <link>https://medium.com/@emilniklas/the-javascript-object-that-will-completely-kill-your-entire-application-d41dd79a63c0?source=rss-5fd35747355f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d41dd79a63c0</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[promises]]></category>
            <dc:creator><![CDATA[Emil Broman]]></dc:creator>
            <pubDate>Wed, 15 Nov 2017 14:27:51 GMT</pubDate>
            <atom:updated>2017-11-15T14:43:00.559Z</atom:updated>
            <content:encoded><![CDATA[<pre>{<br>  then (f) {<br>    f(this)<br>  }<br>}</pre><h4>Explanation</h4><p>If any part of your program uses the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise API</a>, which it probably does, it’s probably making use of how promises are <em>flattened</em>. For instance, if you call <strong>Promise.resolve(123)</strong>, you will get a promise object which resolves to <strong>123</strong>. However, if you do <strong>Promise.resolve(Promise.resolve(123))</strong>, it will still come back as <strong>123</strong>. If a promise is about to resolve itself, but the resulting object is another promise, it waits for that <em>inner</em> promise to resolve itself before passing the result on.</p><p>So how does it know whether the resulting object is a promise or not? It looks for a property on the object called <strong>then</strong>, which should be a function. If the resolved result satisfies that criteria, it’s considered <em>thenable</em>, and will be part of the flattening process.</p><p>That means that we can create <em>thenable</em> objects ourselves, like so:</p><pre>Promise.resolve({<br>  then (cb) {<br>    cb(123)<br>  }<br>}).then(result =&gt;<br>  // result == 123<br>)</pre><p>The same goes for values returned from Promise <strong>then</strong> mappers:</p><pre>Promise.resolve().then(() =&gt; {<br>  return {<br>    then (cb) {<br>      cb(123)<br>    }<br>  }<br>}).then(result =&gt;<br>  // result == 123<br>)</pre><p>This is all well and good, but sometimes we’re not quite sure what the objects we pass around in our promises look like. In fact, lots of objects that we don’t consider being part of asynchronous code pass through these Promise mechanics.</p><p>What’s worse is that this opens up for a particularly unpleasant bug. One that doesn’t crash the system or overflows the stack, but puts our system in an <em>infinite loop</em>. And it’s as easy as this:</p><pre>const dontTryThisAtHome = {<br>  then (f) {<br>    f(this)<br>  }<br>}</pre><p>This object, once passed into any promise-driven algorithm will kill your system. Once resolved, any promise handling it will see that the resolved object in fact is thenable, so it will call the <strong>then</strong> method, which calls its callback with an object that is also thenable (because it’s the same object).</p><p>And thus, the system will enter an infinite loop of flattening the same object over and over again. Have fun debugging this one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d41dd79a63c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Objects in JavaScript]]></title>
            <link>https://medium.com/@emilniklas/functional-objects-in-javascript-7ded06948819?source=rss-5fd35747355f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ded06948819</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[object-oriented-design]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Emil Broman]]></dc:creator>
            <pubDate>Fri, 31 Mar 2017 17:20:59 GMT</pubDate>
            <atom:updated>2017-03-31T17:20:59.853Z</atom:updated>
            <content:encoded><![CDATA[<p>The Functional and Object Oriented paradigms are often considered to be incompatible. “Sure, you can use higher order functions in JavaScript, but if you’re using classes, you’re not writing functional code”. I beg to differ.</p><p>Functional Programming is all about immutability. That means that data structures can never change. One characteristic of Objects in the OOP sense of the word is that each object holds its own internal mutative state, so instead of using objects you should just use functions, right? Well, not so fast. First, let’s just try to implement a stack without changing any data.</p><pre><strong>class Stack {<br>  constructor () {<br>    this._array = []<br>  }<br>}</strong></pre><p>Wait a second! Is that an assignment? We’re mutating the object and so we’re not being immutable, right?</p><p>The only place where assignment is OK is within a constructor, because you’re <em>initializing</em> the object. Saying constructor assignments are not okay is like saying that <strong>let i = 123</strong> is not okay.</p><p>We now have an object with an internal state, but we haven’t manipulated the data in any way yet. Let’s add a method.</p><pre>class Stack {<br>  constructor () {<br>    this._array = []<br>  }</pre><pre><strong>  get length () {<br>    return this._array.length<br>  }</strong><br>}</pre><p>No problem, right? We have a simple getter function that doesn’t change any data, it simply returns a value. However, how can we implement the mutative <strong>push</strong> method? Let’s look at the mutative example first.</p><pre>class Stack {<br>  constructor () {<br>    this._array = []<br>  }</pre><pre>  get length () {<br>    return this._array.length<br>  }</pre><pre><strong>  push (value) {<br>    this._array.push(value)<br>  }</strong><br>}</pre><p>Here, we’re <em>changing</em> the internal variable, breaking immutability. The tell-tale sign is that we don’t have a <strong>return</strong> statement in the function. If the function doesn’t return anything, it must have a side effect or do nothing at all.</p><p>The first step in solving the issue is a simple one: moving the internal array to a constructor parameter:</p><pre>class Stack {<br><strong>  constructor (array) {<br>    this._array = array<br>  }</strong></pre><pre>  get length () {<br>    return this._array.length<br>  }</pre><pre>  push (value) {<br>    <em>???</em><br>  }<br>}</pre><p>Now, the <strong>push</strong> method can use its internal array, create a new array with the value appended, create a new <strong>Stack</strong> with the array, and return the result:</p><pre>class Stack {<br>  constructor (array) {<br>    this._array = array<br>  }</pre><pre>  get length () {<br>    return this._array.length<br>  }</pre><pre><strong>  push (value) {<br>    return new Stack(<br>      [...this._array, value]<br>    )<br>  }</strong><br>}</pre><p>Look at that! No more mutation. A consumer of the class will use it like this:</p><pre><strong>const stack = new Stack([])</strong></pre><pre><strong>const stackWithItem = stack.push(1)</strong></pre><p>Next, let’s implement pop:</p><pre>class Stack {<br>  constructor (array) {<br>    this._array = array<br>  }</pre><pre>  get length () {<br>    return this._array.length<br>  }</pre><pre>  push (value) {<br>    return new Stack(<br>      [...this._array, value]<br>    )<br>  }</pre><pre><strong>  pop () {<br>    return new Stack(<br>      this._array.slice(0, this._array.length - 1)<br>    )<br>  }</strong><br>}</pre><p>Okay, we now have a method which returns a new <strong>Stack</strong> with one less item. But <strong>pop</strong> is supposed to return the value that is being removed!</p><p>In situations like this, functional programming has the notion of <em>tuples</em>. A <em>tuple</em> is a simple list-like data structure with a fixed length, the values of which can have different types. By returning a <em>tuple</em>, we can return multiple values from the same function. Let’s try it for our <strong>pop</strong>.</p><pre>class Stack {<br>  constructor (array) {<br>    this._array = array<br>  }</pre><pre>  get length () {<br>    return this._array.length<br>  }</pre><pre>  push (value) {<br>    return new Stack(<br>      [...this._array, value]<br>    )<br>  }</pre><pre>  pop () {<br><strong>    const item = this._array[this._array.length - 1]<br>    const stack = new Stack(<br>      this._array.slice(0, this._array.length - 1)<br>    )</strong></pre><pre><strong>    return [stack, item]</strong><br>  }<br>}</pre><p>The consumer can then use the method like so:</p><pre>const stack = new Stack([])</pre><pre>const stackWithOne = stack.push(1)</pre><pre><strong>const [stackWithoutOne, one] = stackWithOne.pop()</strong></pre><p>Another solution is to simply force the consumer to fetch the top item in the stack beforehand:</p><pre>class Stack {<br>  constructor (array) {<br>    this._array = array<br>  }</pre><pre>  get length () {<br>    return this._array.length<br>  }</pre><pre>  push (value) {<br>    return new Stack(<br>      [...this._array, value]<br>    )<br>  }</pre><pre><strong>  get top () {<br>    return this._array[this._array.length - 1]<br>  }</strong></pre><pre>  pop () {<br><strong>    return new Stack(<br>      this._array.slice(0, this._array.length - 1)<br>    )</strong><br>  }<br>}</pre><p>And then it’s up to the consumer:</p><pre>const stack = new Stack([])</pre><pre>const stackWithOne = stack.push(1)</pre><pre><strong>const stackWithoutOne = stackWithOne.pop()<br>const one = stackWithOne.top</strong></pre><blockquote>Notice in the example above, that it doesn’t matter that we access the top object <strong>after</strong> we have popped the stack, because the original stack is never changed, so the value is still there!</blockquote><p>Finally, I like to make a static getter that initializes the empty object just like the original constructor did:</p><pre>class Stack {<br>  constructor (array) {<br>    this._array = array<br>  }</pre><pre><strong>  static get empty () {<br>    return new Stack([])<br>  }</strong></pre><pre>  get length () {<br>    return this._array.length<br>  }</pre><pre>  push (value) {<br>    return new Stack(<br>      [...this._array, value]<br>    )<br>  }</pre><pre>  get top () {<br>    return this._array[this._array.length - 1]<br>  }</pre><pre>  pop () {<br>    return new Stack(<br>      this._array.slice(0, this._array.length - 1)<br>    )<br>  }<br>}</pre><p>Ultimately, I think we’ve achieved a pretty nice API:</p><pre>return Stack.empty<br>  .push(1)<br>  .push(2)<br>  .pop()<br>  .push(3)<br>  .push(4)<br>  .pop()</pre><pre><em>// Stack { _array: [1, 3] }</em></pre><p>This can be done with any object, and if you force yourself to adhere to the principle of immutability, you end up with a system that is well defined, stable, and that’s easy to debug. You rarely need a debugger in a stateless program.</p><p>The implications of objects like this sort of propagate. For example, how would you loop over an array and push each item to the stack?</p><pre><strong>const stack = Stack.empty</strong></pre><pre><strong>for (const item of [1, 2, 3]) {<br>  stack.push(item)<br>}</strong></pre><p>This won’t work, because the original Stack is never changed. So we’ll have to keep track of the object:</p><pre>const stack = Stack.empty</pre><pre>for (const item [1, 2, 3]) {<br><strong>  stack = stack.push(item) // Error!<br></strong>}</pre><p>We can’t do this, because we’ll have to change the variable into a mutable <strong>let </strong>which is against our immutable rules.</p><p>One way to solve it is through recursion:</p><pre><strong>const source = [1, 2, 3]<br>const target = Stack.empty</strong></pre><pre><strong>const result = (function f (stack, index) {<br>  if (index &gt;= target.length) {<br>    return stack<br>  }</strong></pre><pre><strong>  const item = source[index]<br>  const newStack = stack.push(item)</strong></pre><pre><strong>  return f(newStack, index + 1)<br>})(target, 0)</strong></pre><p>However, this gets rather muddy, and probably not very performant in the long run without <a href="http://2ality.com/2015/06/tail-call-optimization.html"><em>tail call optimization</em></a><em> </em>yet implemented in most JavaScript runtimes.</p><p>So the nicest way to solve it in my opinion, is using the <strong>reduceRight</strong> method:</p><pre>const source = [1, 2, 3]<br>const target = Stack.empty</pre><pre><strong>const result = source.reduceRight(<br>  (stack, item) =&gt; stack.push(item),<br>  target<br>)</strong></pre><p>If you’re unfamiliar, this will work pretty much exactly like the recursive version, but in a very optimized fashion, since this is a built-in method.</p><p>The second argument (<strong>target</strong>) will get passed into the function, together with the first item in the array. The return value (i.e. a <strong>Stack</strong> with <strong>[1]</strong>) will be passed back into the function along with the second item, yielding a <strong>Stack</strong> of <strong>[1, 2]</strong> and so forth. No mutation.</p><p>This mindset of functional and object oriented paradigms combined, is very prominent in my UI library <a href="https://tweedjs.github.io/"><strong>TweedJS</strong></a>. Check it out, why don’tcha!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ded06948819" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tweed — An OO JS UI Library]]></title>
            <link>https://medium.com/@emilniklas/tweed-an-oo-js-ui-library-e1a818bb314f?source=rss-5fd35747355f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1a818bb314f</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[virtual-dom]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Emil Broman]]></dc:creator>
            <pubDate>Thu, 05 Jan 2017 15:37:55 GMT</pubDate>
            <atom:updated>2017-01-06T12:30:35.794Z</atom:updated>
            <content:encoded><![CDATA[<p>First of all; look at all those abbreviations. I did it. Yay.</p><p>Before showing Tweed, I need to explain the reasoning behind it, with a little bit of history. If you want, you can skip down to the heading <strong>Enter Tweed</strong>. You’re welcome.</p><p>There has been a bit of a divide as of late, between two paradigms in the web space. Functional Reactive Programming—spearheaded by React—on one hand, and Object Oriented Programming—upheld by Angular and Web Components—on the other.</p><p>The mindsets and traditions of these two have resulted in firm standpoints, from both sides, in questions seemingly unrelated to these paradigms.</p><h4>Virtual DOM</h4><p>One of these controversies are the Document Object Model.</p><p>The standard Web API’s of JavaScript in browsers have since the beginning used an object oriented representation of HTML. An <strong>HTMLButtonElement</strong> is an instance of <strong>HTMLElement</strong> which, in turn, is an instance of a basic DOM <strong>Node</strong>, and so on.</p><p>Since these objects are directly tied to the layout and painting of the UI, operating on these objects can result in bad performance, flickering, lagging et cetera.</p><p>The advent of the Virtual DOM—popularized by Elm and React—introduced the idea of a separate representation of the DOM which <em>wasn’t</em> connected to the UI. This JS-only data structure could be generated, manipulated, and replaced with a very small performance impact. The actual DOM was then intelligently manipulated in the smallest and quickest possible way, making it indistinguishable from carefully managing DOM mutations manually.</p><p>This allowed developers to not worry too much about <em>how</em> the UI was manipulated, and instead focus on <em>what</em> the UI was. This declarative style replacing the old imperative style was a great pairing with Functional Reactive Programming, which led UI developers to slowly adopt a more functional mindset.</p><h4>JSX and the Platform Defense</h4><p>To make the transition from HTML to Virtual DOM, Facebook released React with a new language feature specifically designed to make constructing VDOM feel like writing HTML—JSX. It turned the non-familiar <strong>React.createElement(‘div’)</strong> into the much more comfortable <strong>&lt;div /&gt;</strong>. Furthermore, it allowed developers to create their own components as elements in the XML-like tree, like <strong>&lt;This /&gt;</strong>.</p><p>This was initially considered blasphemous because at the time, the idea of combining the markup and behaviour of a UI had decidedly been deemed a “bad practice”.</p><p>Gradually, as the community realized the appeal of coupling things that change for the same reasons—markup and behaviour—the argument of <em>Working With the Platform</em> instead of “on top” of it emerged in the OO crowd. After all, the web API’s are all object oriented.</p><p>This divide made Virtual DOM exclusive to the FRP folks.</p><h4>The Elm Architecture</h4><p>As you may or may not be aware of, React was actually inspired by another project called Elm, which is not a JS library but an entirely different programming language. It has a syntax similar to the ML-family, like Haskell, and is a strongly typed, purely functional programming language.</p><p>Elm introduced the so called <em>Elm Architecture</em>, which replaced the dominating <em>MVC </em>Architecture. The idea is that you have a <em>Model</em>, a <em>View </em>function, and an <em>Update</em> function. These three work together like this:</p><p>The <em>View</em> receives the <em>Model</em> and renders a UI (VDOM) from it. Actions from the user then trigger the <em>Update</em> function which, given the type of action, runs the <em>View</em> function again with a modified version of the <em>Model</em>, effectively updating the UI.</p><h4>The case against the Elm Architecture</h4><p>However, one issue with this whole approach that I have is the way that it handles source code dependencies.</p><p>The <em>View</em> function only receives the <em>Model</em>, and since Elm is functional, that means that the entire UI must be concretely generated. If we need a “Sidebar”, <em>View</em> must choose an implementation to use for that sidebar. Thus, the <em>View</em> function has a source code dependency on the entire UI codebase.</p><p>There are ways to manage this fact, primarily using function composition and <em>currying</em>, where one function generates the sidebar and receives another function as an argument, which can be called to generate the content of the sidebar. That way the <strong>sidebar</strong> function does not depend on the sidebar’s content in its source code.</p><p>Finally, it should be mentioned that Elm is also a little bit limited in its implementation at the time of writing this. Specifically, it does not have <em>Type Classes</em> like Haskell. Type classes would enable the <em>View</em> function to call functions with unknown implementations, which would then be implemented differently depending on the data types in the <em>Model</em>.</p><h4>Object Orientation and Dependency Injection</h4><p>Suffice it to say that source code dependency management is not very intuitive in functional programming, at least not for a developer like myself who is much more experienced with OOP than with FP.</p><p>The Object Oriented community has been dealing with source code dependencies for a long time, and has established polymorphism as its primary mechanism for code reuse. Traditionally, it has been accomplished using inheritance. There are a lot of issues with that, however, so a better practice may be to use abstract composition using Dependency Injection. I’m referring to the pattern here, not <em>Automatic Dependency Injection </em>by libraries or frameworks.</p><p>By injecting the implementation of an abstract dependency that a class has in its constructor, we not only maximizes the reusability of that class. We also make it easier to test, maintain, and replace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z4UiA4GHfyWsqA4C4wrQHA.png" /><figcaption>The Tweed Logo</figcaption></figure><h3>Enter Tweed</h3><p>Tweed is a reactive, virtual DOM based UI library, which uses the Object Oriented paradigm to solve the problem of maintaining a complex and stateful user interface.</p><p>Here’s a simple <strong>Counter</strong> component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91b4772f783ce9a6294800fb5d8772bf/href">https://medium.com/media/91b4772f783ce9a6294800fb5d8772bf/href</a></iframe><p>At first glance, it looks a lot like a React component, but without the <strong>setState</strong> and instead a <strong>(at)mutating</strong> decorator. I think you can probably imaging what it means (it means the UI will rerender when that property is mutated), so we’ll move on.</p><p>Now let’s look at how this component is used:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bc1de72fc61aa8e4037f3bafb47654a/href">https://medium.com/media/2bc1de72fc61aa8e4037f3bafb47654a/href</a></iframe><p>You’ll notice that we don’t see <strong>&lt;Counter /&gt;</strong> in the <strong>render</strong> method. Instead, we send in the <em>instance</em> that we already have. This is crucial. In React, each component is re-instantiated on re-render, unless otherwise expressed with <strong>shouldComponentUpdate</strong> callbacks and similar mechanisms. With Tweed, render methods simply delegate between persistent instances.</p><h4>JSX as a primitive</h4><p>With Tweed, JSX does not contain and manage instances of classes which should or shouldn’t be replaced. Instead, JSX is simply immutable objects representing HTML. Nothing else.</p><p>With this mindset, you can think of the <strong>render</strong> method as a <strong>toString</strong> for HTML or <strong>toHTML</strong>. In fact, the name <strong>render</strong> is not at all required. It is simply a convention and, as seen in the example above, if the JSX factory receives an object, it will implicitly call a <strong>.render()</strong> method like that, with no arguments.</p><h4>Mounting</h4><p>The final step is to connect that <strong>App</strong> class to the browser, and that’s easy:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67df5b536d4d5b77c4426789c4a9169b/href">https://medium.com/media/67df5b536d4d5b77c4426789c4a9169b/href</a></iframe><p>As you might guess, it’s easy to use other renderers to perform an initial render on the server.</p><h4>Next to Native</h4><p>Since the <strong>render</strong> method on the <strong>Engine</strong> takes an instance and not a class constructor, how you get that instance is entirely up to you. Up until that point, you’re in full control of your objects.</p><p>Furthermore, Tweed doesn’t provide any dependency management facilities, like a <em>DI/IoC Container</em>. If you want to use one of those, you’ll have to choose one. You might even find it’s easier to just new up those classes yourself. If you stick to the <em>Dependency Injection</em> pattern, you will end up with a huge tree of instantiations, like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fe4a97373c439bee7891a9128aee41a/href">https://medium.com/media/9fe4a97373c439bee7891a9128aee41a/href</a></iframe><p>While this may look unwieldy at first, you may actually find that not only does this give quite a comprehensive overview of what your site looks like; all the independent pieces are highly decoupled from the rest of the system, meaning they can easily be replaced or be independently tested and maintained. And everything can be monitored and composed in this top level file.</p><p>Another benefit is that you can structure your app to inject different implementations for some interfaces; one for the client, one for the server. Imagine an interface <strong>EmployeeRepository</strong>, and its respective implementations <strong>APIEmployeeRepository</strong> and <strong>DatabaseEmployeeRepository</strong>. The component injecting the <strong>EmployeeRepository</strong> interface doesn’t need to know <em>how</em> the employees are fetched, only that they are.</p><p>So that’s about it. Give Tweed a try if you’re an experienced OOP developer, or if you’re someone who finds the functional paradigm of React to not match your mental model of how to build apps.</p><p>Check out the <a href="https://tweedjs.github.io/">Tweed homepage</a> for some more examples.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1a818bb314f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop the Web Frontend Cockfight]]></title>
            <link>https://medium.com/@emilniklas/stop-the-web-frontend-cockfight-c0c3cb12f577?source=rss-5fd35747355f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0c3cb12f577</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Emil Broman]]></dc:creator>
            <pubDate>Thu, 06 Oct 2016 17:40:00 GMT</pubDate>
            <atom:updated>2016-10-06T18:19:39.120Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a reaction to recent tweets, one of which is this one:</p><h3>Local Developer on Twitter</h3><p>No! Just because bigger companies have websites that don&#39;t work without js or css, doesn&#39;t mean you should do it too #fronteers #a11y</p><p>TL;DR: It <em>is</em> okay to build a website that doesn’t work without JavaScript, as long as you know that your users won’t suffer for it. It’s also okay to not use the most popular JS framework, if you know that the experience won’t be worse for it. By waging this kind of war, you’re not helping the platform; you’re scaring away newcomers.</p><p>The web is by far the most rapidly changing software platform in history. And people have always had a problem with this. Either it’s not moving quickly enough for people (“Ugh, if I could just use Flexbox”), or it’s moving <em>too</em> quickly (“JavaScript Fatigue”).</p><p>I won’t go into the pros and cons of a platform that works like this — and there are multiple of both — instead, I would like to talk about what’s been happening in the community over the last weeks, or months, or years.</p><p>I would say there are two types of Frontend Engineers; the <em>accessibility activists</em>, and the <em>framework fangirls’n’boys</em>. The accessibility people want the web to work as it did 15 years ago (oh, and then you can sprinkle that fancy JS on top of it as long as it doesn’t prolong the initial load!!!1). The framework crowd wants to treat the entire web platform as some sort of assembly language (I’ll just run <strong>npm run build</strong> and serve that 4MB minified <strong>dist</strong> folder that comes out of it).</p><p>I’m making fun of both groups here, because they can both be ridiculously extremist. This has sparked a bit of a flame war about whether to work <em>with</em> or <em>on top of</em> the web platform.</p><p>The <strong>a11y</strong> soldiers fight for an accessible internet for everyone! This is awesome! And the framework astronauts work tirelessly to find new ways to make web experiences beyond anything that was possible just a few years ago. Amazing!</p><p>What they don’t seem to understand is that they aren’t making the same things. They are comparing sports cars with freight trains. They are solving different issues. It’s all about choosing the best techniques and the best tools for the task at hand.</p><p>If you’re making a web magazine that will spread its articles all around the world, then you should make sure that your website takes into account all the different people and devices that will interact with it. You should make sure that every essential piece of content is available without having JavaScript enabled, and you should take care to support as many accessibility tools as you possibly can.</p><p>On the other hand, if you get hired by a company to develop a tool for all their internal communications and project management, then you should make sure to use the platform to its fullest extent to provide an experience that makes your client productive and happy. If the company consists of 25 healthy, english speaking people with no accessibility problems whatsoever, you shouldn’t waste their money making sure that your website can be used by mandarin speakers that may have physical disabilities.</p><p>Not only does this war waste time and energy while hurting and upsetting people, the worst part of it is that both sides together scare away beginners.</p><p><a href="https://hackernoon.com/how-it-feels-to-learn-javascript-in-2016-d3a717dd577f">How it feels to learn JavaScript in 2016</a></p><p>To be frank, I think this all comes down to <strong>people being scared</strong>. Let me explain:</p><p>Everyone in this industry put down hours and hours to grow, and to learn how to do this right. We read books, listened to talks, read docs and blogs and more books and every one of them told us <strong>what not to do</strong>. “You shouldn’t render HTML in the browser, think about SEO!”, “You shouldn’t mutate state, learn about referential transparency!”, “You shouldn’t duplicate your code!”, “You shouldn’t mix different frameworks!”, “You mustn’t forget to concatenate all your scripts!”, “You mustn’t concatenate all your scripts!”.</p><p>Every time we listen to someone’s argument on how to be a better developer, we learn that another way of doing it is bad. And this turns into fear, because we know that we will make mistakes, and we will write bad code. And we fear that we’re not pursuing the one true way.</p><p>There’s a little thing called <a href="https://youarenotsosmart.com/2010/05/19/fanboyism-and-brand-loyalty/">Retroactive Rationalization</a>, which is a term for the psychological tendency that we humans have, to not admit that we made a bad choice. Instead, we will continue to invest in the same thing, because if we somehow turn out on top, we were right all along.</p><p>So every time someone presents you with an idea that goes against what you’ve learned, you immediately get upset, because <strong>what if they’re right?</strong> Is everything I’ve learned bad? Surely not, so it must be them who are wrong. And they’re teaching other people the wrong thing! So you tell them this in a very sharp tweet.</p><p>In the end, you’re creating an environment where people that are just getting into programming are shamed because they’re using jQuery, or because they’re not using the best supported browser feature, or forgetting to think about SEO and social tagging, or using <strong>setState</strong> instead of Redux, or not using proper Dependency Injection, or not compressing all images correctly, or not providing a fallback PNG to every SVG...</p><p>Here’s what I propose you do:</p><p>Pursue what you think is most interesting about software and allow others to pursue other things that they feel is more interesting. When it comes to actual work, think about the users of your website. Identify who they are <em>before</em> you choose a framework or decide that you will support IE7. Chances are that you’ll sometimes find yourself in a situation where you’re not the most well suited developer for a certain project. <strong>And that’s okay.</strong> Do your best, learn by doing, and if possible, get help from people who are more qualified and can teach you new things.</p><p>Peace and Love.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0c3cb12f577" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to do WordPress without having to deal with WordPress]]></title>
            <link>https://medium.com/@emilniklas/how-to-do-wordpress-without-having-to-deal-with-wordpress-95d7a5a7ddd7?source=rss-5fd35747355f------2</link>
            <guid isPermaLink="false">https://medium.com/p/95d7a5a7ddd7</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[wordpress]]></category>
            <dc:creator><![CDATA[Emil Broman]]></dc:creator>
            <pubDate>Wed, 24 Aug 2016 14:21:50 GMT</pubDate>
            <atom:updated>2016-08-24T14:47:59.872Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s been said before, and I think it’s time to finally officially admit it: WordPress is the worst. It’s <a href="https://en.wikipedia.org/wiki/WordPress#Release_history">old</a>, it’s <a href="https://www.yahoo.com/tech/outdated-versions-wordpress-drupl-led-151103940.html">insecure</a>, it’s <a href="https://www.google.com/search?q=wordpress+is+slow">slow</a>, and its own codebase is <a href="https://github.com/WordPress/WordPress/blob/92343be1f445b83ac2ecce5aa7021c059f2b8f4d/wp-admin/themes.php#L189-L228">nasty</a>. It had its glory days, and it is still incredibly—<strong>incredibly</strong>—<a href="https://managewp.com/14-surprising-statistics-about-wordpress-usage">popular</a>, but it really is way past its best before date.</p><p>Don’t get me wrong. I respect WordPress for what it has accomplished. And I understand where it’s coming from. It really is impressive how well it has handled things like backwards compatibility, and I believe it is still has the biggest plugin market in the history of software (maybe <strong>npm</strong> is getting close but I doubt it). And dare I say it—it has one of the best admin interfaces that’s out there.</p><p>Users seem to love it somehow, and apparently a <a href="https://www.google.com/search?q=wordpress%20agency">lot of developers do too</a>. Or maybe they pretend to like it because of the money, I don’t know.</p><p>It turns out it’s so big that it’s practically impossible to kill. Clients keep coming requesting “an e-commerce site based on WordPress”, or “a simple site for our company. We’re thinking WordPress!”</p><p>The PHP ecosystem has changed a lot since WordPress was launched in 2004. There are now very sophisticated applications running on this platform that was <a href="https://en.wikipedia.org/wiki/PHP#Early_history">intended for much less</a>. A community driven <a href="https://www.google.se/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=1&amp;cad=rja&amp;uact=8&amp;ved=0ahUKEwizs6mThdrOAhXGXCwKHf71AocQFggdMAA&amp;url=http%3A%2F%2Fwww.php-fig.org%2F&amp;usg=AFQjCNFAj-ewFtAr7M7yIaDpClGQzkPcAA&amp;sig2=H-8fmoYBbonJ9I8ZcOLANA">standards committee</a> is in place, as well as countless frameworks and extensions distributed using a (also community driven) <a href="https://getcomposer.org/">package manager</a>.</p><p>But what if there was a way to make WordPress development great again? Or maybe at least bearable?</p><p><strong>Disclaimer: </strong>This post is not for making reusable integrated WordPress themes that you can sell standalone. This is for developers who are used to writing vanilla or framework based PHP and just happen to have to use WordPress. I do not recommend choosing WordPress if you have any other choice at all, but if you <em>really really</em> have to—here’s how you can do it without a nervous breakdown.</p><h4>WordPress as a plugin</h4><p>A good piece of software keeps its high level business logic separated from the low level details like persistence or UI. The WordPress ecosystem on the other hand, forces you to dance to their tune. It leaks into everything; the UI, the persistence, the business logic, you name it. It even forces you to place <em>your code</em> in <em>their directory structure</em>. They have a historical reason for doing this, of course, but we don’t like it.</p><p>There’s a <a href="https://github.com/johnpbloch/wordpress">project on GitHub</a> that has turned WordPress into a Composer package. So let’s pull that in:</p><pre>composer require johnpbloch/wordpress</pre><p>After we’ve run <strong>composer install</strong>, let’s remove the <strong>wordpress</strong> directory that is created for us, from our version control (e.g. using <strong>.gitignore</strong>):</p><pre>wordpress/</pre><p>Now, there is an installation of WordPress in that folder that you’re treating just like any other external dependency.</p><h4>Two public folders</h4><p>WordPress is designed to be the webroot of your server. That can be very dangerous, because if you place some secret file in your theme, anyone can access that file by visiting <strong>example.com/wp-content/themes/example/secret_file.crt</strong>.</p><p>A better way of doing it is having a subfolder called something like <strong>public</strong> and having a single entry point into the back-end there. So that’s exactly what we’re going to do. However, for the WordPress admin pages to still work we have to also make that <strong>wordpress</strong> directory public.</p><p>Depending on your server set up, this can be done in many ways. One nice thing could be to have a subdomain like <strong>admin.example.com</strong> pointing to the <strong>wordpress</strong> folder, and the main <strong>example.com</strong> domain pointing to <strong>public</strong>. Whatever you like.</p><h4>The entry point</h4><p>The usual PHP set up is for the webserver (usually Apache) to check for any files inside <strong>public</strong> that matches the request, and if none is found, send the request to <strong>public/index.php</strong>.</p><p>That script is usually very simple. It should just delegate the request into your application. We’ll do it like this:</p><pre>&lt;?php</pre><pre>require_once(__DIR__.&#39;/../app/bootstrap.php&#39;);</pre><p>As you can see, this script now expects us to have a file ready as <strong>app/bootstrap.php</strong>. This <strong>app</strong> directory is where we will have our entire application.</p><h4>The application</h4><p>You really should be using PSR-4, if you aren’t already. We will set up our <strong>app</strong> directory to be the root namespace for our application, in <strong>composer.json</strong>.</p><pre>{<br>  &quot;require&quot;: {<br>    &quot;johnpbloch/wordpress&quot;: &quot;^4.6&quot;<br>  },<br><strong>  &quot;autoload&quot;: {<br>    &quot;psr-4&quot;: {<br>      &quot;App\\&quot;: &quot;app/&quot;<br>    }<br>  }</strong><br>}</pre><p>We can then run <strong>composer dump</strong> and start working on our <strong>app/bootstrap.php</strong>.</p><pre>&lt;?php</pre><pre>// Autoload<br>require_once(__DIR__.&#39;/../vendor/autoload.php&#39;);</pre><pre>// ...</pre><p>At this point it’s vanilla PHP all the way. You can do anything. Although, you might want to start off pulling in a nice router with Composer.</p><h4>Integrating with WordPress</h4><p>Here’s my best tip: try to get as far as possible with your app without using WordPress. Model your own data, like a <strong>Post</strong> class and a <strong>Category</strong> class and so on. Write automated tests to ensure that the modules you write are working, without having to view them in a browser. Pull in a templating package and start doing the front-end with mocked data.</p><p>And then, when you need to hook up your pretty little app to the monster that is the WordPress installation next door, here’s what you do:</p><h4>Repositories</h4><p>If it’s a blog that you’re making, you’ve probably already made a class called <strong>Post</strong>. Or maybe it’s some kind of e-commerce site with a <strong>Product</strong> model. However you’ve modeled your system, you should have a few basic <em>Data Transfer Object</em> classes in your app. Now, let’s define how we want to interact with this data using the Repository Pattern:</p><pre>interface PostRepository<br>{<br>    public function find($id);<br>    public function save(Post $post);<br>    public function all();<br>}</pre><p>In every place in your application where you want to interact with the posts in your database, you request an instance of this interface.</p><pre>class PostsController<br>{<br>    protected $posts;</pre><pre>    public function __construct(PostRepository $posts)<br>    {<br>        $this-&gt;posts = $posts;<br>    }<br>}</pre><p>Next, we can hook in WordPress:</p><pre>class WordPressPostRepository implements PostRepository<br>{<br>    public function find($id)<br>    {<br>        $post = \get_post($id);<br>        return $this-&gt;postFromWPPost($post);<br>    }<br>    ...<br>}</pre><p>It’s important that you note that we don’t want to return a <strong>WP_Post</strong> class from this <strong>find</strong> method. Instead, we create an instance of our own <strong>Post</strong> class and return that, keeping all WordPress specifics in this class.</p><p>If you’re feeling really clever, you can also implement a <strong>FakePostRepository</strong> that spews out dummy instances of your models, for browser testing. Maybe using a library like <a href="https://github.com/fzaninotto/Faker">Faker</a>.</p><p>However, if you run the app with the <strong>WordPressPostRepository</strong>, it will fail with a message like:</p><pre>Fatal error: Call to undefined function get_post() in ...</pre><p>That’s because we haven’t actually pulled in WordPress yet.</p><h4>Lazy loading WordPress</h4><p>To get access to all the usual WordPress functions, we need to include <strong>wp-load.php</strong>. We could just throw it in beneath the <strong>autoload.php</strong> include, but I wan’t to get a little more clever than that.</p><p>We have a complete application that works without WordPress, except for actually getting the correct Posts into the views. If you have a bunch of routes for different things, chances are that some of them don’t need WordPress to ever load at all.</p><p>So instead of including the <strong>wp-load.php</strong> file on every request, we can put that import somewhere where it only ever gets called if it’s needed.</p><p>There’s a couple of ways of doing this. One way could be to just add a <strong>require_once</strong> statement to the constructor of our classes that need WordPress.</p><pre>class WordPressPostRepository implements PostRepository<br>{<br>    public function __construct()<br>    {<br>        require_once(__DIR__.&#39;/../../wordpress/wp-load.php&#39;);<br>    }<br>    ...<br>}</pre><p>This could get a little muddy, so we might save the path to <strong>wp-load.php</strong> in some constant and clean it up to this:</p><pre>require_once(WP_LOAD_PATH);</pre><p>However, I’m still not satisfied.</p><h4>Laravel Service Container Events</h4><p>I’m a big fan of <a href="https://laravel.com/">Laravel</a>. One cool thing about this framework is that it has a bunch of <a href="https://github.com/illuminate">standalone components available as packages</a>. In one of these, we get access to Laravels powerful <a href="https://laravel.com/docs/5.3/container">IoC Container</a>.</p><p>Using this package, we can clean up the bootstrapping of our code, and at the same time solve our <em>loading WordPress</em> problem.</p><pre>use Illuminate\Container\Container;</pre><pre>$container = new Container;</pre><pre>$container-&gt;bind(<br>  App\PostRepository::class,<br>  App\WordPressPostRepository::class<br>);</pre><p>Here we’re telling the container that we want to use the WordPress implementation of our PostRepository.</p><p>We can now use this container instance in our routes (or by using the standalone Laravel Router), and every time we need access to a PostRepository, the container will provide an instance of the WordPress specific one.</p><p>Next, we can use the container to listen to some events. Specifically, we can listen to when the container is <em>resolving</em> a specific class or interface. So let’s create a <em>Marker Interface</em> that we can use to designate when a class needs WordPress to be loaded.</p><pre>interface UsesWordPress<br>{<br>}</pre><p>And then we can add a listener to the Service Container, where we include <strong>wp-load.php</strong>.</p><pre>$container-&gt;resolving(App\UsesWordPress::class, function () {<br>    require_once(__DIR__.&#39;/../wordpress/wp-load.php&#39;);<br>});</pre><p>Finally, we mark our repository:</p><pre>class WordPressPostRepository implements PostRepository, UsesWordPress<br>{<br>    ...<br>}</pre><p>Now, every time your application requests an instance of the <strong>PostRepository</strong>, WordPress will load and an instance of <strong>WordPressPostRepository</strong> will be returned. Any other class that needs WordPress to be loaded can simply be marked with the <strong>UsesWordPress</strong> interface.</p><p>I’ve made a little boilerplate repo <a href="https://github.com/emilniklas/illuminate-wp-boilerplate">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95d7a5a7ddd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Constructors considered harmful.]]></title>
            <link>https://medium.com/@emilniklas/constructors-considered-harmful-17cccfab8d3?source=rss-5fd35747355f------2</link>
            <guid isPermaLink="false">https://medium.com/p/17cccfab8d3</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Emil Broman]]></dc:creator>
            <pubDate>Mon, 08 Aug 2016 15:57:17 GMT</pubDate>
            <atom:updated>2016-08-08T15:57:17.425Z</atom:updated>
            <content:encoded><![CDATA[<p>TL;DR: If we remove constructors all together, and instead rely on mixins and anonymous classes, multiple inheritance and circular dependencies stop being a problem.</p><p>Let’s talk inheritance. One of the most controversial topics in computer science, apparently. It’s generally considered to be a bad thing (I won’t link to any of the flamey comment sections, but I think you know what I mean).</p><p>Some of the cases against inheritance is that there are problems with overriding methods that affect the internal state of the base class. Case in point, the <a href="https://en.wikipedia.org/wiki/Fragile_base_class">fragile base class problem</a>. This is rarely a problem, though, since stateful classes themselves are considered a bad practice.</p><p>However, the concern with inheritance that I see most often, is the problem of <em>single</em> inheritance. When a language only supports a single base class, it <a href="http://estrattonbailey.tumblr.com/post/137095497581/duplication-by-necessity-not-limited-to-classical">can cause problems</a>. Why not allow for multiple base classes? <a href="https://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem">The diamond problem</a> is a common example. Again, this problem arises from the class’ internal state.</p><p>People talk about composition over inheritance. It’s the notion that your class should <em>use </em>other classes instead of <em>inheriting</em> from them.</p><pre>class <strong>A</strong> {<br>  <strong>B</strong> b;<br>  <strong>A</strong>(<strong>B</strong> b) { this.b = b; }<br>}</pre><p>To reduce complexity, <em>mixins</em> or <em>traits</em> got popular. Here the lines get blurred. Usually, the implementation looks like inheritance, but without the constructor:</p><pre>// PHP<br>class <strong>A</strong> { use <strong>B</strong>; }</pre><pre>// Dart<br>class <strong>A</strong> extends Object with <strong>B</strong> {}</pre><p>If the mixin has a dependency of some sort, it can expect the class that uses it to adhere to some sort of interface.</p><p>Now let’s talk about constructors. What do they usually contain? Dependencies, right?</p><pre>// Java<br>class <strong>A</strong> {<br>  private <strong>B</strong> b;<br>  private <strong>C</strong> c;<br>  public <strong>A</strong>(<strong>B</strong> b, <strong>C</strong> c) {<br>    this.b = b;<br>    this.c = c;<br>  }<br>}</pre><p>Yuck… Luckily, many programming languages have realized this and introduced short hand syntax for this sort of thing:</p><pre>// TypeScript<br>class <strong>A</strong> {<br>  constructor (<br>    private b: <strong>B</strong>,<br>    private c: <strong>C</strong><br>  ) {}<br>}</pre><pre>// Dart<br>class <strong>A</strong> {<br>  <strong>B</strong> b;<br>  <strong>C</strong> c;<br>  <strong>A</strong>(this.b, this.c);<br>}</pre><p>But what are we really saying here? If we forget what we dislike about inheritance for a minute, shouldn’t it work just as well to turn our dependencies into template methods? Compare these two classes:</p><pre>// Java<br>abstract class A {<br>  protected B b();<br>  protected C c();<br>  <br>  public static A make(B b, C c) {<br>    return new A() {<br>      protected B b() { return b; }<br>      protected C c() { return c; }<br>    }<br>  }<br>}</pre><pre>class A {<br>  private B b;<br>  private C c;<br>  private A(B b, C c) { this.b = b; this.c = c; }</pre><pre>  public static A make(B b, C c) {<br>    return new A(b, c);<br>  }<br>}</pre><p>They both use a static factory method (which is <a href="http://stackoverflow.com/a/3852556">considered a good pattern</a>) and apart from how their fields are accessed (a consequence of the limitations of Java), their API looks exactly the same.</p><h4>Removing constructors</h4><p>I’m going to invent my own syntax here. Imagine a programming language that doesn’t have any constructors, and only allow inheritance through mixins. Here is a class:</p><pre>class A {<br>  b: B<br>  c: C<br>}</pre><p>All this tells us is that this <strong>A</strong> class has a dependency on an instance of <strong>B</strong>, and an instance of <strong>C</strong>. Let’s invent a way to instantiate this class:</p><pre>new A {}</pre><p>We need to pass in the dependencies, so let’s make it an anonymous class object:</p><pre>new A {<br>  b = new B {}<br>  c = new C {}<br>}</pre><p>Now let’s move this into a static “constructor” method:</p><pre>class A {<br>  b: B<br>  c: C</pre><pre>  static make (b: B, c: C) {<br>    return new A {<br>      b = b<br>      c = c<br>    }<br>  }<br>}</pre><p>Now how would inheritance work? Let’s make another class and try to use it as a mixin:</p><pre>class M {<br>  d: D<br>  method () {<br>    return this.d.doSomething()<br>  }<br>}</pre><pre>class A: M {<br>  b: B<br>  c: C</pre><pre>  static make (b: B, c: C, d: D) {<br>    return new A {<br>      b = b<br>      c = c<br>      d = d<br>    }<br>  }<br>}</pre><p>Perfectly fine, right? And as long as another mixin has non-conflicting dependencies, we can safely combine them:</p><pre>class M1 { d: D }<br>class M2 { d: D }</pre><pre>class A: M1, M2 {<br>  b: B<br>  c: C</pre><pre>  static make (b: B, c: D, d: D) { ... }<br>}</pre><p>We could even have a circular dependency without introducing any strange behaviours:</p><pre>class A: B {<br>  aDep: AD<br>  // methods can use this.bDep since B is mixed in<br>}<br>class B: A {<br>  bDep: BD<br>  // methods can use this.aDep since A is mixed in<br>}</pre><pre>new A { aDep = ..., bDep = ... }<br>new B { aDep = ..., bDep = ... }</pre><h4>Conclusion</h4><p>Constructors destroy inheritance, and turns it evil. And we don’t even use them very much. However, if we treat all classes as abstract, and create our concrete implementation (with or without overriding properties) at instantiation time, we end up with a pretty sweet composition system that scales and is less complex.</p><p>Moreover, if we need to pack up our final concrete implementations in factory functions, we can do so in static methods, and our API remains friendly.</p><p>I’ve taken an example and pushed a repo to GitHub. <a href="https://github.com/emilniklas/constructors-considered-harmful">Visit it here</a>. I’ve tried to implement this idea in a few programming languages. Feel free to correct me or even push some more languages.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17cccfab8d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Open Letter To Functional Programmers]]></title>
            <link>https://medium.com/@emilniklas/an-open-letter-to-functional-programmers-7eacc9ed6fed?source=rss-5fd35747355f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7eacc9ed6fed</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Emil Broman]]></dc:creator>
            <pubDate>Tue, 10 May 2016 15:31:23 GMT</pubDate>
            <atom:updated>2016-05-10T16:25:29.455Z</atom:updated>
            <content:encoded><![CDATA[<p>Dear Functional Programmers,</p><p>I am what I believe to be somewhat close to the average developer. I’ve spent my training and career learning about Object Oriented Programming® and Design Patterns™. I’ve encountered problems and bugs, and I’ve dealt with them. And I like to believe that each one made me a little better at what I do.</p><p>Then Functional Programming® came into my life. And I plunged into an existential crisis.</p><p>The thing is—I really <em>really</em> like the idea of functional programming. The concept of no mutating state, and all the benefit that comes from it. It’s great! But it’s different.</p><p>And it’s not necessarily a matter of syntax. I can work with that. What really bugs me is that I apparently need to throw everything I’ve learned out of the window.</p><h4>Where I’m coming from</h4><p>Here’s how I usually approach a problem (using OO pseudo-code):</p><pre><strong>class</strong> A {<br>  <strong>function</strong> solveMyProblem(…) { … }<br>}</pre><p>If I feel like the <strong>solveMyProblem</strong> method gets too long, I extract methods. If I feel like the <strong>A</strong> class does too much, I extract a collaborator:</p><pre><strong>class</strong> B {<br>  <strong>function</strong> something() { … }<br>}</pre><pre><strong>class</strong> A {<br>  b: B</pre><pre>  <strong>init</strong>(b: B) {<br>    <strong>this</strong>.b = b <em>// Preferably some shorthand for initializers</em><br>  }</pre><pre><strong>  function</strong> solveMyProblem(…) {<br>    …<br>    <strong>this</strong>.b.something()<br>    …<br>  }<br>}</pre><p>If I feel like the <strong>B</strong> class might be (optionally) implemented another way, I replace the dependency with an interface, and make <strong>B</strong> an implementation of that interface.</p><pre><strong>interface</strong> I {<br>  <strong>function</strong> something()<br>}</pre><pre><strong>class</strong> B: I { … }<br><strong>class</strong> C: I { … }</pre><pre><strong>class</strong> A {<br>  i: I<br>  …<br>}</pre><p>And that is <em>basically</em> it. Everything else is just other ways of expressing the above.</p><p>Now let’s look at what I’ll do in a functional language. I’ll recreate the steps from above the best I can. Please overlook any bad or inaccurate code in my Haskell-ish example. I’m new to this:</p><pre>solveMyProblem … =<br>  …</pre><p>When I feel that the <strong>solveMyProblem</strong> function gets too long, I extract more functions. If my module does too much, I extract another module.</p><pre><strong>module</strong> A</pre><pre><strong>import</strong> B</pre><pre>solveMyProblem … =<br>  …</pre><p>If I feel like the <strong>B</strong> module can be implemented in another way, I make a type class (or whatever method for polymorphism is appropriate):</p><pre><strong>class</strong> I i <strong>where</strong><br>  something :: i -&gt; …</pre><p>Then I make the <strong>A</strong> module depend on the type class instead of the implementation <strong>B</strong>. Then I’ll make my <strong>solveMyProblem</strong> function take an argument of a specific instance of the <strong>I</strong> type class the caller wants to use.</p><pre><strong>module</strong> A</pre><pre><strong>import</strong> I</pre><pre>solveMyProblem :: I i =&gt; i …<br>solveMyProblem i … =<br>  something i</pre><p>Let’s do a comparison.</p><p>If you look at my OO code example above, there is no mutating state. No assignment statements (except for in the constructor, which doesn’t really count because I’m just <em>initializing</em>).</p><p>If it can be at all avoided, I don’t have any mutable state in my classes. And it turns out, this is what most OO people do.</p><p>The functional code—given that it might not be the best way of doing it—is sort of similar.</p><ol><li>Make a function that solves the problem</li><li>Extract collaborator</li><li>Generalize the collaborator</li></ol><p>So to use the API that my code exposes, I simply have to</p><ol><li>Choose an implementation of the collaborator</li><li>Pass the implementation into the function</li></ol><p>I can do it like this:</p><pre>function main() {<br>  a = <strong>new</strong> A(<strong>new</strong> B)<br>  a.solveMyProblem(…)<br>}</pre><p>Or like this:</p><pre><strong>import</strong> B</pre><pre><em>-- where b is imported from B<br></em>b :: I i =&gt; i</pre><pre>main =<br>  solveMyProblem b …</pre><p>If we need to pass around the function <em>with its polymorphic implementation</em>, we can curry the function is Haskell</p><pre>main =<br>  <strong>let</strong> a = solveMyProblem b<br>  <strong>in</strong> a …</pre><h4>What is an object?</h4><p>Haskell doesn’t have objects. It has data and functions. In OOP, most people tend to lean towards the same distinction. Some objects are data structures (DTOs), and some objects contain the functions that operate on those data structures.</p><p>If you remove the <strong>new</strong> keyword from my example, the initialization of an object is really indistinguishable from a function returning a data structure, where we have named functions, which behaviours depend on the arguments passed into the original function (constructor). If we think about it this way, it seems a constructor is really just a higher order function—a function that returns functions. And an object is just a bag of named functions.</p><p>So, now to my question to you, Functional Programmers: <strong>Why should FP be inherently incompatible with OOP?</strong></p><p>Isn’t it conceivable with a programming language that is object oriented, but doesn’t allow any mutation whatsoever?</p><p>And I’m really not trying to start a flame war here. Also, I’m not saying that the OOP model is <em>better</em> than the alternatives. I just don’t want to throw away all I know and start over…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7eacc9ed6fed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Bridge Framework is being discontinued]]></title>
            <link>https://medium.com/@emilniklas/the-bridge-framework-is-being-discontinued-5c3e5c5ad8cc?source=rss-5fd35747355f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c3e5c5ad8cc</guid>
            <category><![CDATA[dartlang]]></category>
            <category><![CDATA[bridge-framework]]></category>
            <dc:creator><![CDATA[Emil Broman]]></dc:creator>
            <pubDate>Fri, 26 Feb 2016 13:29:34 GMT</pubDate>
            <atom:updated>2016-02-27T08:04:08.011Z</atom:updated>
            <content:encoded><![CDATA[<p>Today I’m announcing the discontinuation of the Bridge Framework project <strong>in favor of another project</strong> that is coming up. Here’s my reason:</p><p>When I first fell in love with Dart, I came directly from the PHP community and Laravel. One of the best things about Laravel is the way it makes the developer feel like a first class citizen. With beautiful APIs and <em>Convention over Configuration</em>.</p><p>The main reason I <strong>left</strong> Laravel, though, was because I longed for a language that worked both in a browser and on a server. I wanted to make an attempt to bring front end and back end more closely together, because I figured since they belong to the same app, they should collaborate.</p><p>When I started working on Bridge, all I had in mind was the comfort of Laravel, and how neatly it wrapped everything up for me when starting a new project. So I started copying many of the ideas directly.</p><p>It turns out, though, that Dart — it’s not PHP! And with that I mean mainly two things:</p><ul><li>Laravel very heavily pushes you towards sever side templating, while Dart is driven mostly by the high profile UI frameworks Angular and Polymer.</li><li>PHP is a scripting language that gets executed for each and every request by itself. With Dart, on the other hand, each request that comes in has the ability to access global state, and can therefore create side effects that affects the entire app, not just the current request.</li></ul><p>For instance, Laravel provides a facade with the entire session and authorization information, allowing for helper functions like <strong>Auth::user()</strong>. To have the same functionality in Bridge, I would have to receive a Request object to associate authorization state with. Like <strong>Auth.user(request)</strong>. That’s a bit awkward, since we now have to pass around a request object everywhere.</p><p>Dart, like all other languages, has its own ideas, which turn into patterns. And the solutions that work for PHP devs, are probably not the same that turn out to work best for Dart devs.</p><p>In Dart, it turns out we quite like metaprogramming and declarative configuration (i.e. annotations). Even though it seems a large part of the Dart community dislikes the thought of runtime reflection (i.e. mirrors) — a concept that is used a lot in the world of Laravel.</p><p>During the past <em>almost-a-</em>year, I’ve gotten used to the Dart way of doing things. And this results in the realisation that Bridge isn’t a very good fit. Even though I know there is great potential in a project like this, there are just too many hurdles for the Dart community (where Java and JavaScript devs are most common) to embrace.</p><p>Instead of trying to push the Bridge Framework in a different direction, I’ve decided to discontinue the project before releasing <strong>1.0</strong>.</p><p>I want you to know that it’s not because I just felt sick of the project and moved on. Believe me, if people used and relied on this project, I wouldn’t just leave it like this.</p><p>I’ve been working on a new project, that I think is a better fit for the Dart community. It’s called Embla and is on GitHub (<a href="https://github.com/emilniklas/embla">https://github.com/emilniklas/embla</a>).</p><p>Embla really is the spiritual successor of Bridge:</p><ul><li>It has the concept of Bootstrappers, similar to the ServiceProviders from Laravel and Bridge.</li><li>It has the same reflection based IoC Container as Bridge at its core.</li></ul><p>However, it cleans up a lot of the things that come from Laravel that doesn’t fit well in the Dart ecosystem:</p><ul><li>Configuration is done in the argument lists of Bootstrappers, not in a big YAML-directory.</li><li>Bootstrapper hooks are done with annotations, not with a few magic method names.</li><li>The Embla core package will not contain *every component*, instead you’ll pull in multiple plugins by their own package names.</li><li>There won’t be a boilerplate project for Embla. It is easy to set up from the Stagehand server side template. All you need is a <em>bin/server.dart</em> and a package.</li><li>Immutable data flows are encouraged; all stateful code can be placed in Bootstrappers. As a consequence of that mindset, APIs are more likely to be expressed as immutable lists and pipelines than with mutable collections (like <strong>..add(something)</strong>-APIs).</li><li>There will be less focus on messaging and sharing between server and client, even though a WebSocket plugin will be a natural addition.</li></ul><p>Embla is in early development, and I would very much like to hear your opinions and requests. Feel free to contact me on Twitter or GitHub or anywhere really if you want in.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c3e5c5ad8cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>