Submit on Enter With Aurelia

Written on 25 January 2016

We have a form or at least an input field and we want to submit or execute some behaviour when the user presses Enter. In this tutorial I'm going to show you how to build an Aurelia custom attribute that can be used wherever you want this feature.

Our goal is to use it like this

<input type="text" on-enter.call="submit()">

Let's create the attribute

import {customAttribute, autoinject} from "aurelia-framework";

@autoinject
@customAttribute('on-enter')
export class OnEnter {
    constructor(element:Element) {

        this.element = element;
        this.onEnter=(ev:KeyboardEvent) => {
            //Enter keyCode is 13
            if (ev.keyCode !== 13) return;
            this.action();  
        };
    }
     element:Element;
    attached() {
       this.element.addEventListener("keyup",this.onEnter);
    }
    onEnter;

    action;
    valueChanged(func) {

        this.action = func;


    }

    detached() {

        this.element.removeEventListener("keyup",this.onEnter);
    }
}

Yes, that's all, but now let me explain it. The autoinject decorator tells Aurelia to use metadata generated by TypeScript to determine the dependency type (in this case a DOM Element. This is normal usage in Aurelia, we do that everyhwhere we need to inject dependencies (and we're using TypeScript). The customAttribute is self-explaining.

In the constructor we need the html element where the attribute is used and that's what it gets injected here. Next, we set up the 'onEnter' function. This part is quite important so pay attention.

We need that function as an event handler for a keyup event. You see that we have the attached() and detached() methods which are part of the Aurelia custom element lifecycle i.e they are invoked automatically when the view is attached/detached from the DOM. In this case we don't have a view, but the methods are still invoked by the framework (I suppose when the parent element is attached/detached) allowing us to set up or remove the event handler. That's why we have the onEnter variable instead of using arrow functions (lambdas).

Now, you may wonder why onEnter isn't defined as a function directly. It's because of javascript and the this affair. In a simple function this would be the calling context i.e the window. But we need this to point at our attribute model and using lambdas is the easiest way to do it (TypeScript takes care of the details).

The valueChanged method is automatically invoked by Aurelia when the value of the attribute changes, and in this case we get the function that should be invoked on enter. Note how the binding syntax in html is not .bind but .call. This tells Aurelia to create and pass a delegate (which will wrap the specified function) as a value. So, when we invoke this.action() we're actually invoking the delegate which in turn invokes the specified function.

And pretty much that's it. Once you're aware of the this gotcha and the .call binding you can create all sorts of 'event handler as an attribute'. For example, it's trivial to have an on-escape attribute (hint: replace 13 with 27).

Custom attributes still need to be referenced in a view so you either need a <require from="myAtttribute"></require> or set it up as a global resource or a feature. You can read more about those in Aurelia docs

Rich Domain Doesn't Mean Fat Objects

Written on 17 December 2015

Let's look at a CRUD app. Is it a business app? Yes, because it still provides business value. Sure, the business just wants to store and retrieve some data but that data does have business semantics and usefulness. Do we have business rules? Yes, we do, data validation is implementation of business constraints.

But what about queries? What about calculating how much you owe in unpaid invoices? Sure, it implies just reading some data but the calculation is done according to business rules i.e it is business behaviour. A CRUD app does have business behaviour and quite plenty of it, however what makes it simple it's the fact that the behaviour is quite straightforward and thus, easy to implement.

And yes, a CRUD app can still benefit from DDD, the strategic part aka understanding the business. After all, this is how you know you're dealing with a simple domain. But the tactical patterns are pretty much useless in this case.

So how does a rich behaviour domain looks like then? Well, not only that it has more concepts and use cases, there's a lot of decision making based on business rules. And this is the hard part. We need to untangle the decision-making process.

Thing is, it's not about having big fat objects. The OOP fear of an anaemic domain shouldn't drive us into the other extreme, where we put everything related to a concept into one object. We need to model the complexity of making decisions and maintain a consistent business state. And from an implementation point of view, we have way more services (which are pure behaviour) than aggregates. Yes, an aggregate encapsulates some business rules (constraints) but only those required to ensure consistency when a change is made.

However, the decision-making part which contains the bulk of rules should be implemented as services, because this is what they are: business behaviour with no state of their own. Basically, you end up with a number of concepts (and their encapsulated limited behaviours) and lots of services. This might look like an anaemic domain but it's not.

It's easy to think "I'll just put all related User business rules in the User object", but it's the wrong design which complicates things in the long run. While in OOP we want to keep together data (state) and related behaviour, the methods should manipulate or process that state only. In DDD the aggregate is a consistent group of other objects (concepts) treated as one (bigger concept), exposing a facade (the Aggregate Root) which will ensure that all changes maintain the unit's consistency.

But that's it! We don't add other behaviour just because it is related to that concept. We don't want a fat object that acts as container of functions. We represent a business concept in code. Its use cases aren't part of its definition. When trying to decide where you should put a behaviour just look at how the business uses the concept.

As an example, I have the concept of "Chair" . If I have a use case where the chair is moved, most of OO programmers will have something like this chair.Move() . Which is wrong, because it's not the Chair's responsibility (from a business point of view, we always care about the business point of view) to handle position and movement. It would be an external behaviour (another aggregate or a domain service) which will have a .Move(chair,location).

In conclusion, I would say that a rich domain proper implementation depends a lot on understanding how the business thinks and less on programming principles and patterns or technical implementation specifics. The code should serve the business, the business shouldn't adapt to code.

Confirmation Modal With Aurelia And Bootstrap

Written on 16 December 2015

I have lots of (different) items in my view that can be deleted. And I want a confirmation dialog to pop up when I press the delete button. In this post I'll show you how to implement this functionality in Aurelia using Bootstrap for styling.

One thing that I like about Aurelia is how easy it is to write maintainable components. So, I will create a delete custom element that will trigger our confirmation dialog. Because it's a generic element, I want it to be easily "attached" to any item that needs to be deleted. And I want to set the confirmation text and the action to be execute on "yes" .

The Confirmation Dialog

But first things first. We need to create the modal that will be invoked by Delete. Luckily, there is a plugin for Aurelia that does that. Let's install it.

jspm install aurelia-dialog

In order to let aurelia know about it, we need to add this bit in the configuration function

export function configure(aurelia) {
  aurelia.use
    .standardConfiguration()
    .developmentLogging()
    .plugin("aurelia-dialog")
    ;

  aurelia.start().then(() => aurelia.setRoot());
}

Now we need to create the modal element itself. The plugin comes with a 'Prompt' example, but we won't be using it. So let's create the confirmation modal. First the view model (I'm using Typescript)

import {autoinject} from "aurelia-framework";
import {DialogController} from 'aurelia-dialog';

@autoinject
export class Confirm {

    constructor(public controller: DialogController) {

    }
    message ="";
    activate(data) {
        this.message = data;
    }
}

Now, the view. We can use most of the Bootstrap styling without the js functionality.

<template>
    <div tabindex="-1" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" click.trigger="controller.cancel()" class="close" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">Confirmation</h4>
                </div>
                <div class="modal-body">
                   ${message}?
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" click.trigger="controller.cancel()">No!</button>
                    <button type="button" class="btn btn-danger" click.trigger="controller.ok()">Yes</button>
                </div>
            </div><!-- /.modal-content  -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->

</template>

Note how the dialog div is missing the usual "modal fade" classes. It's because aurelia will take care of creating, displaying and hiding the modal. The rest of the code is pretty much self explaining. We control the outcome of the dialog invoking the controller (DialogController) ok() or cancel() methods. Both will trigger the closing of the dialog and will set up the result that we can use further.

One thing worth mentioning is you can pass a model to the ok method. For example, if the dialog was for a form, whose fields were bound to a model, I could pass that model to be returned like controller.ok(myModel) . You can read more about this on the plugin page .

Now, we won't be using this element directly, we'll be opening the dialog through DialogService. Or more precisely the Delete element will do that.

The Delete element

This is what will be actually using in our templates. Let's see its definition:

import {autoinject, bindable} from "aurelia-framework";
import {DialogService} from "aurelia-dialog";
import {Confirm} from "./confirm";

@autoinject
export class Delete {

    @bindable
    action=()=>{};

    @bindable
    msg = "Are you sure";

    constructor(public dlg:DialogService) {

    }

    do() {
        this.dlg.open({
            viewModel: Confirm
            , model: this.msg
        }).then(result => {
            if (result.wasCancelled) return;
            this.action();
        });
    }
}
<template>
    <button class="btn btn-danger" click.trigger="do()">Delete</button>
</template>

Nothing complex here. The element will accept the values of the message and of the action to be taken on "Yes". Then when the button is clicked, the do() method invokes the DialogService's open() method, passing the type of the confirmation's view model and the model (in this case a simple string) used by it. The method returns a Promise where we can set up what happens after the dialog is closed.

The 'result' argument has 2 fields: wasCancelled which is obvious what it does and output which is the modified model that is returned by the dialog (if any). In this scenario we don't need it.

Actual usage

Now we can use our Delete element where we need it. As an example, let's say I have a list of names

    data=['John','Mary','David'];

    delete(name:string){

       this.data.splice(this.data.indexOf(name), 1);            

    }

    deleteOther(){
        console.log("something deleted");
    }
<require from="./delete"></require>

<delete msg="Are you sure" action.call="deleteOther()"></delete>

<ul>
 <li repeat.for="item of data">
     ${item}
       <delete msg="Are you sure you want to delete ${item}" action.call="$parent.delete(item)"></delete>   
 </li>
</ul>

Note the binding to a function syntax action.call . This tells Aurelia to execute the specified expression every time action() is invoked.

And this is it! As you've seen, it's quite simple to create your own custom dialog with Aurelia while using Bootstrap CSS. Before I knew about the dialog plugin, I had my own custom element which used Bootstrap js and jQuery and while it's not complicated, it's not as clean and smooth as it is with 'aurelia-dialog'. This means that even if there is no plugin to offer the functionality you need, it's still trivial to use existing Boostrap or JQuery plugins.

Domain Driven Design (DDD) Is Not Programming

Written on 23 November 2015

I keep saying that design and programming are sides of the same coin. This means that both are required to develop a proper product but it also means that they are different . As the name implies, Domain Driven Design is design, therefore it's not programming. And this is quite important because programming, as a mindset, can be and it is an obstacle in doing DDD properly.

First and foremost, DDD means strategic design aka high level design where we don't care about implementation details like code, database, monolith/micro services etc. Sure, DDD has tactical patterns which help us in writing the code, especially doing low-level (object, function) design but the DDD tactics are still higher level than code.

The power of DDD (the strategic part) comes from understanding the domain i.e understanding the business mindset, language and solutions. It's not about coming up with solutions (the programmer mindset), but understanding how the business implements its own solutions. When we do Domain modelling, we open our eyes, ears and brain and we learn about the business concepts and behaviour. It has nothing to do with code. At this level, concepts are just a name(not a class) and behaviour is how the business uses those concepts (not a method/function).

It's also important to understand the domain relationships between the concepts. Those aren't RDBMS relationships (one to many), nor OOP relationships (is a or has a ). It's not about applying programming principles, it's not about identifying programming relationships (inheritance, composition) to be written in code.

For example:"A table has 4 legs". In domain speak this might mean that the "Table" concept requires 4 legs in order to be a valid concept for a specific use case. It's not about a Table class which has a "Legs" property, although it might be a valid way to implement it in code (but at this stage we aren't concerned with writing code, we care about understanding how the business sees (defines) that concept in a certain scenario) . Another example: "A person has a hat". Applying the programmer mindset is wrong, you'll end up with a class Person that has a property "Hat". But from the domain point of view it might mean that "a person owns a hat" and/or "a person is wearing a hat". Domain relationships != object/table relationships. Domain language != programmer language.

The whole point of the DDD strategic design is to identify the business concepts, their constraints and the business behaviour (use cases and business rules), it's not about writing code i.e designing class diagrams or worse, databases. Sure, we need to implement all those in code (our final objective), but first we need to have a very thorough understanding of the things, only afterwards we begin writing code. Basically we need to become domain "experts". And the programmer's mindset is an obstacle in our way.

Even the DDD tactics are higher level than code. You can think of them like this: strategic design is the highest level and it involves learning the domain mindset. Next we're using the tactics (aggregates, entities etc) as an intermediate step, where we're trying to focus and group together the relevant concepts and business behaviour aka business rules, for a specific use case. Only after that we can go implementing things into code, after you know the aggregates.

The DDD tactics are themselves design abstractions, not implementations. The aggregate is a group of concepts (not objects!) and business rules, required by the business process to maintain its consistency when you want to change things. In practice, you have a bunch of names and rules. Those can be implemented by code using your favourite approach (OOP, FP or both). Always, the actual code is an implementation detail (this is the programming part), but we need the proper high level design (concept abstraction) first.

The whole point of DDD is to help us coming up with a model that mimics how the business looks at the things, how the business works in the real world. This will allow us to implement business changes faster, because the code itself is designed (modeled) according to the business mindset (efficient or not). When the business change in a certain way, the code just follows. If we design things programming driven, it will always be a mismatch between the real business model and the coded model, resulting in slower, more complicated changes. Yes, your code could be of the highest technical quality and your algorithms the most efficient, these don't matter if any change required by the business means you have to resort to patching, cutting corners, technical debt or delivering value very slow.

We don't build software for the glory of technology (most of us anyway), we build a product that delivers value to its stakeholders. That's why in DDD, business (domain knowledge) comes first, code comes second. Rushing to write code usually means ending up with an improper domain model which on the long run becomes more and more complicated and harder to maintain. I cringe when I see people asking how to code things in DDD, it's not about the code, it's not about learning a new magic recipe, it's not about being a (better) programmer. That's why, when we're doing DDD (and high level design in general), we should forget we are programmers. The programmer mindset of finding solutions is an impediment when trying to learn how an existing system (a domain) works. The best quality of a DDD practitioner is listening, not problem solving.

P.S: Obviously, all the good modelling and design is useless with a crappy implementation, but the point here is: understand business first, understand business second, write code third.

I Saw Your Profile On Stack Overflow

Written on 20 November 2015

So, I get this glorious email

[bla bla] viewed your Stack Overflow Careers profile and sent you a message.

Hi Mihai,

I saw your profile on Stack Overflow Candidate Search and wanted to get in touch with you about some development job opportunities we have here at [bla bla].

You can see our current job ad at http://jobview.monster.ca/Junior-or-Intermediate-Software-Developer!-[bla bla].aspx and your profile suggests that you may be interested in hearing more about the type of development work we do at [bla]. If this is not the case then please let me know and I will be sure not to contact you again.

I'd love to have a chance to chat with you to tell you more about bla (you can also find out more at our SO company page) and to find out a bit more about you.

Cheers,

[whatever] VP & Director of Engineering, [bla bla]

Obviously, I was delighted. After all these years on SO and around 300(ish) answers about Domain Driven Design, application architecture and design patterns, finally someone considered that I'm a good material for a junior/intermediate dev. After all, as mr VP said, my profile ("SOLID web apps architect") suggests that.

Anyway, I was curious about the ad itself and it was so great that I had to blog about it.

We're looking for both junior and intermediate resources;

Yeah, I don't know if an overhead or a C-level asset is the author. Hey, at least they don't look for Chuck Norris or Neo, like other companies do.

Things we’re looking for in terms of more specific skill-sets and experience:

BS, MS, or PhD in Computer Science or related technical discipline (or equivalent).

I only have a BSc degree in Business Administration (Masters degrees were boring so I've quit - 3 times actually) so I guess I'm part of the "or equivalent".

Extensive programming experience in a language that demands strong OO skills (C# / Java / C++ / etc.)

Ok, I've heard about some of those, but I've never heard of this "etc" language. Nevermind extensive experience. I'm still puzzled though about which language/stack they're actually using. I mean, writing web apps (job is for a cloud solution) in C++ is pretty old-skool, right? Maybe they're using all the languages? I wonder how we do memory management and pointers in that "etc" language.

Experience working with scripting languages like PHP, Ruby, Python or Perl in a web application.

Lol, at least I've heard of those, hey I even did php for some years. But Perl? Really?! I'd get that "etc" language before Perl. A curious thing though, how Ruby and Python aren't part of the OOP list above. I guess they're just some silly scripting languages where strong OOP skills don't matter. But now I'm really confused about their stack. Maybe C# with a dash of Ruby and a pinch on Perl? Or that "etc"?

Coding skills in Javascript / AJAX, database design and SQL.

Phew... at least they don't require experience with these. I do have to wonder why db design and sql are next to javascript/ajax. I think they're related somehow.

Several years of software design and development experience, with knowledge of Unix / Linux.

How many is "several"? Enough to qualify for a junior/intermediate? I don't know. Hm... Linux. Oh well, at least they know that asp.net 5 will run very well on it.

Ideally you’ve been coding since you were old enough to read.

Whoa... let me see... I've learnt how to read when I was 7, this means that ideally I'd have close to 30 years coding experience? Not as much as uncle Bob, but well, it's for a junior/intermediate position after all. Oh wait, maybe it's for the younger people, those who've just graduated college. 23 - 7, eh, only 16 years experience for the ideal junior/intermediate candidate.

A solid foundation in computer science, with strong competencies in data structures, algorithms, and software design.

You know, someone really needs to be more specific. What does count as solid foundation? Strong competencies? If I implement bubble sort, does this mean I'm competent in writing maintainable code? It reminds me of another very used and useless requirement like "analytical thinking" or "problem solver". Btw, is any company looking for someone who doesn't solve problems and (s)he's clueless about their field? I know they hire those people, but are they actively looking for them?

(Intermediate level) Previous experience with agile development methodologies and unit testing.

Wait a minute.... all those things, like extensive experience and more experience and ideally at least 16 years of programming is just for the junior position? Wow, these people are hardcore! But really, a junior of that level who doesn't know about agile or unit testing (cough)TDD(cough) is not such a great resource, is it?

I'm very curious about a senior/lead or architect position. I guess it's someone with at least 50 years experience in building scalable apps and former senior architect at Facebook/Twitter/Amazon and the founder of that "etc" language.

For the obviously clueless author of the job ad: you need at least a MS (masters - not to be confused with Microsoft) in basic logic and a PhD in common sense. Better yet, go to a real developer to write the job ad. Demanding extensive experience and strong skills for a junior/intermediate position is an oxymoron. Not specifying the actual tech stack (you know the languages, frameworks and platforms used by the company) shows you don't care enough to attract the right people. Because a Ruby developer won't be in a hurry to become an asp.net dev. Good developers are language/tool agnostic but we all have our preferences and things we don't like. For example, you won't see me writing Vb.Net or Ruby.

And yet, you don't have any problem writing this bullshit:

But, for the lucky few—the ones that have talent, the ones who can see beyond fossil fuels—these have the chance to work in an evolved and developer-focused culture.

First, dafuq means "who can see beyond fossil fuels"?! And a culture so "evolved and developer focused" would let a damn developer write the job ad. Who would specify the language/framework used.

I'm pretty certain it was not the VP & Director of Engineering who sent me that email (at least I hope so). Just matching some keywords, the way 95% of 'recruiters' work, shows you simply don't give a fuck. And when you get no answer or an angry email, you complain that there is shortage of good developers and it's oh, so hard to attract talent. It is... when you're oozing laziness. Developers, especially good ones, are pretty smart people with strong analytical skills. They can detect an incompetent recruiter/email/job ad. Unfortunately, most of the job ads are dumb, choke-full of bullshit. Even the decent ones still have some WTFs ("Expert knowledge of RDBMS concepts, Database coding techniques [I suppose it means Sql, I sure hope they don't want someone to code a database] and store [sic] procedures"). And I've read job ads with incomplete sentences and misspelled tech names. The people writing those ads display a total lack of respect and competence, showing how little they care.

Yes, it was a rant and I'm sure that you (a developer reading this post) read and mocked similar job ads. But, if you are one of the overheads (HR) or C-assets (VP/CTO) reading this, show some respect and common sense and try to understand the mindset of a good developer. Hint: ego stroking, big empty words aka bullshit, vague specifications and stupid technical requirements will attract only juniors or mediocre developers who are very passionate about having a job but that's about it. Want to attract great talent? Then think and act like one.