Why I moved to Angular Dart - Part 1

You know how it goes, you’ve finally (but probably haven’t) mastered your tech stack, you know the ins and outs of your chosen languages, frameworks. Found work-arounds for all those little niggly bits only for a colleague or friend to turn round and say “Have you heard of ‘x’, it’s amazing!”.

For me, this was “Have you heard of Angular Dart? Google use it internally to get around the problems with AngularTS”…

I love Angular with TypeScript, I’m very much a fan boy at this point and I get to use it at work almost every single day, but I have been thinking a lot about TS recently; how it still inherits JavaScript’s problems and adds more complexity to the already insane eco system that JavaScript is, but discussing JS’s flaws could take up an entire post of its own… Anyway, I decided to take a look at Angular Dart and I’ll now compare my experience with Angular TS.

NOTE: I was originally going to do this in one post, but as I started adding more to it I realised this is a very big subject… I will spread it over 3 parts instead.

TLDR;

I switched over to Angular Dart because I want to see what else is out there. TypeScript is great but is “polishing a turd” in the sense that JavaScript is inherintly flawed, and all TS does is throw a (albeit extremely well created) wrapper around JS.
Dart is amazing. Angular Dart is amazing. It doesn’t feel stiched together like Angular TS, there’s nowhere near as many package installs and creates a natural development experience. GIVE IT A GO!

Dart is actually… Awesome!!

So I started looking into Dart and was hooked almost instantly. A language with optional static typing? Object Oriented paradigms but full support for functional programming? Single Inheritence? Generics? It already has everything that TypeScript has but it’s built into the language. It almost sounded like TypeScript but feels a little more natural. Consider this piece of statically typed code in Dart:

1
2
3
4
5
6
class MyClass {
String field1;
String field2;

MyClass(this.field1, this.field2); // Inline constructors? Go on then :D
}

Simple enough, we’ve declared a Dart class called MyClass, declared to public fields and then used our inline constructor to assign their values. Because static typing is optional, we can also write the class like this:

1
2
3
4
5
6
class MyClass {
final field1;
final field2;

MyClass(this.field1, this.field2);
}

Yayyyyyy, they’re both valid. I like this, it means that I can prototype something really quickly if I need to. Another massive positive for me (and other developers who use Dart) is that it is so easy to be productive, quickly. I already felt like I knew how to write Dart.

This isn’t to say that Dart doesn’t have things that niggle me, every language has its flaws.

Angular

So being completely sold by Dart and all it’s offerings, I decided to go and download the Dart SDK and all the packages I needed to get a project up and running.

package management

This wasn’t actually too bad. Unlike AngularTS that uses a package.json and NPM to manage packages, Angular Dart uses a file called pubspec.yaml which looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
name: music_portal
description: Music Portal
version: 0.0.1
environment:
sdk: '>=2.2.0 <3.0.0'

dependencies:
http: ^0.12.0
angular: ^6.0.0-alpha
angular_router: ^2.0.0-alpha+22
angular_forms: ^2.0.0
angular_components: any
json_serializable: ^3.0.0

dev_dependencies:
build_runner: ^1.5.1
build_test: ^0.10.8
build_web_compilers: ^2.1.0
test: ^1.6.4
sass_builder: ^2.0.0

One thing I liked about package management in Angular Dart is that it only contains packages that you (the developer) needs. Most things like stream libraries are built into the language itself, meaning no more “stiching” Angular together with multiple technologies, pretty much everything comes out of the box.

API calls

Hahaha here we go, this is where things started to get really interesting. One thing us JS and TS devs take for granted all the while is that JSON is a natural part of the language, we can call a server with JSON, and get a response back in JSON and we don’t need to do anything else… Dart on the other hand, you don’t have so much luck. If we want to instantiate a class from a server response, we need to make the class serializable. This really threw me off but again, Dart has your back with a built in (and fairly well documented) JSON library, so with a tiny bit of code and reading, this is my solution for making Dart classes JSON friendly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// a class that hits an authentication endpoint.
class UserAuthApi implements IUserAuthApi {
final BrowserClient _http;

Future<ApiResponse<AuthenticationResponse>> authenticateUser(LoginRequest loginRequest) {
final response = await this._http.post('${ApiHelper.apiUrl}/auth/authenticate',
headers: ApiHelper.headers,
body: jsonEncode(loginRequest));

final loginResponse = MusicPortalApiResponse<MusicPortalAuthenticationResponse>.fromJson(jsonDecode(response.body)); // <-- the fromJson method is where the magic happens

return loginResponse
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import 'package:json_annotation/json_annotation.dart'; // <-- Dart's JSON library
import 'package:music_portal/src/api/helpers/json_convert.dart'; // <-- custom JSON converter for use with generic types

part 'api_response.g.dart' // <-- this is actually generated by Dart's JSON library.

@JsonSerializable()
class ApiResponse<T> {

@JsonKey(name: "data")
@JsonConvert()
T data;
String message;
String authToken;
bool hasError;

MusicPortalApiResponse(this.data, this.message, this.authToken, this.hasError);
factory MusicPortalApiResponse.fromJson(Map<String, dynamic> json) => _$MusicPortalApiResponseFromJson(json);
}

Notice the factory? Dart encourages the Factory pattern right in the core of it’s language. This factory is responsible for taking a JSON blob and mapping it to the ApiResponse. Although I soon hit another issue, because data is a generic field, the compiler couldn’t create from JSON because it’s type isn’t known at compile time. This is where the @JsonConvert annotation comes in:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import 'package:json_annotation/json_annotation.dart';
import 'package:music_portal/src/types/api_response/auth_response.dart';

class JsonConvert<T> implements JsonConverter<T, Object> {

const JsonConvert();

@override
T fromJson(Object json) {
if(json is Map<String, dynamic> && json.containsKey("userId")) {
return MusicPortalAuthenticationResponse.fromJson(json) as T;
}
}

@override
Object toJson(T object) {
// TODO: implement toJson
return null;
}

}

Now this feels a bit hacky, but it works. I’ll have to work on cleaning this up as more types are used with the ApiResponse class.

That’s it for part 1, I feel like this post is going on for far too long. I’ll update with post 2 soon…

How Primitive Obsession can be an Anti-Pattern

This post was inspired by my own self reflection on code I have recently writtne. I should be doing University coursework, but whatever, there’s always time to write a programming blog. Especially if it’s the uni work that has inspired me to write this article.

What is primitive type obsession?

Primitive type obessesion according to Refactoring Guru “Like most other smells, primitive obsessions are born in moments of weakness. “Just a field for storing some data!” the programmer said. Creating a primitive field is so much easier than making a whole new class, right?”

It’s way easier to use your languages built in primitive types than to create one, but sometimes it’s best for your product, your code base and your team to just make your own custom types.

Consider this piece of Java code:

1
2
3
4
5
6
7
8
9
10
11
12
public class RentalOrder extends ObservableOrder {

private String orderReference;
private String dateStarted;
private String dateFinished;
private String orderStatus;

public RentalOrder() {
super();
this.orderReference = "OSG-" + UUID.randomUUID().toString().substring(0, 7);
}
}

pretty simple right? The whole idea of this is that we have a rental order (Doesn’t matter what for), but I want to target something that seems fairly innocent:

1
private String orderReference;

But what’s wrong with this? It seems perfectly fine, right? That’s because it is to a degree. We’ve told out RentalOrder class to have a value called orderReference and that is going to be a string, and in the constructor we tell it to create a new reference every time the class is constructed by prefixing ‘OSG’ with the first 8 characters of a UUID.

But what if we wanted to validate this order ref before saving it?

We could wrap the order ref inside some logic that would validate it before we save it, yeah that seems okay.

1
2
3
4
5
6
7
/** let's suppose this code sits inside a method called 'saveNewRentalOrder()'
* we can validate our order reference to make sure that it starts with 'OSG' and contains another 7 alpha-numerical characters
*/

if(order.getOrderReference().substring(0 ,3).equals("OSG-") && order.getOrderReference().substring(4, 11)...) { // further logic
this._db.write(order); // yes, I know, it's not this easy but let's assume it is.
}

This (if implemented properly) would make sure that an order reference looks something like this ‘OSG-1234567’, this works as well it does exactly what it’s supposed to,
we could even move the logic into a method called orderReferenceIsValid(String orderReference); and call it like so

1
2
3
if(orderReferenceIsValid(order.getOrderReference())) {
// ...
}

and that cleans the code up a little, it’s always a good idea to use the single responsibility principle where possible in app development.

BUT what if we wanted our order reference to validate itself? This is where things get interesting, what if orderReference wasn’t a string but its own type?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class OrderRefernce {

private String _orderReference;

OrderReference(String orderReference) {
if(this._isValidOrderReference(orderReference)) {
this._orderReference = orderReference
} else {
throw new Error("order reference is not valid." +
" It must start with OSG- and have 7 following alpha-numeric characters e.g: OSG-1234567")
}
}

private boolean _isValidOrderReference(String orderRefernce) {
// validation logic
}

private String getOrderReference() {
return this._orderReference;
}
}

That’s much better, the OrderReference is now aware of whether it’s valid at time of construction and will force the code to throw an error. So now when we look back at our Rental Order class, we are now seeing the following code:

1
2
3
4
5
6
7
8
9
10
11
12
public class RentalOrder extends ObservableOrder {

private OrderReference orderReference;
private String dateStarted;
private String dateFinished;
private String orderStatus;

public RentalOrder() {
super();
this.orderReference = new OrderReference("OSG-" + UUID.randomUUID().toString().substring(0, 7));
}
}

Awesome, we now no longer need to validate the orderReference on save or any other action, because we can have confidence in the fact that each orderReference is self-validated.

Why tho?

Primitive types are great when they don’t require any custom logic as they all contain the methods required to most basic operations. Creating our own types ensures that all this logic is encapuslated inside it’s own class. We’ve also also made our lives easier because any problems with the orderReference will also be encapsulated so we know exactly where to go if we ever need to debug.

That said, use Primitive types wisely. Not everything needs to be encapsulated into a new class, developer discression is advised when creating these.

My First 2 Years as a Software Developer

As a moody, angsty 19 year old starting a Music Technology course back in 2011. I never would have once thought that I would end up developing software for a living. But here we are in 2019, still moody, still angsty just older… Developing software for a rapidly growing dev-house in Staffordshire.

The music technology course opened the door for my passion for software. As I was using digital software and plugins, I found myself asking “How do these plugins work? How are they made” more and more often. After doing some research, I found that you could write these plugins in something called C++. So I started to learn C++, I cried, alot… Failed my degree, Moved to learning JavaScript whilst working in a Zoo resturaunt for a few years and the rest is history.

I’ve learned a lot over 2 years, I’ve learned that being a good software developer is more than just being able to architect and write code all day. It’s having the ability to collaborate with a team of people that aren’t just developers, problem solving to meet customer requirements, compromise, and most importantly, having the mindset that you don’t know everything, and you probably never will.

What I’ve learned

It can be tough being a new software developer, you’re surrounded by brilliant and talented people who know what they’re talking about, there’s all these buzzwords, Acronyms, frameworks and technologies being thrown around in discussion and it can be overwhelming… Don’t worry about it. Looking back from when I first started to now, I’d probably give myself these words of advice:

  • Learn how to read other people’s code - This one is so important! Let’s be real, you’re going to be spending most of your time looking at code that isn’t yours, and the programmer who originally wrote it has probably moved on. It can be scary to look at other people’s code, you weren’t in their minds or with them when they wrote it but as long as the code is well written, you’ll get used to reading code that you don’t own.
  • Your colleagues are there to help - I don’t think I would have got very far at a dev house if I didn’t constantly ask people about EVERYTHING. Everytime I was paired with someone, I would constantly be asking ‘Why are we doing this?’ or ‘Is there another way of doing this?’ to the point where I honestly thought I was going to be kidnapped and dumped in a forest somewhere in Scotland. Truth is as long as you’re listening, most people are more than happy to teach you.
  • Use work’s tech stack in your own projects - There’s a lot to learn in programming, a lot of concepts, technologies, frameworks and languages. One thing that really boosted my confidence on our massive code base was learning the tech stack that I use day in, day out (in my case: .NET/C# and Angular/TypeScript). It really does help.
  • You don’t have to be a genius - I wonder if a lot of people suffered from the illusion that you have to be some sort of God with a 10,000 IQ to be a programmer like I did? You really don’t. All you need is a keen attitude to learn.
  • But it doesn’t mean programming is easy - It’s still important to understand that software development also isn’t easy. There are times where you will struggle but it’s all part of the job.
  • Domain knowledge is key - Having an understanding of how systems gives you more confidence when it comes to adding and removing from the code base. It also helps with things like making sure that what you are doing doesn’t have potential side effects to the rest of the system or having confidence that you’re not going to introduce a new bug to the system.

And that’s about it

I think it’s just important to remember that Software development is one of those ‘you get out what you put in’ kind of industries and that it’s a very rewarding industry if you are willing to put time into professional and personal development. Enjoy what you do and you’ll never work a day in your life, or something like that…