| Props | State | |
| Owner | parent component | component itself |
| Accessibility | public, i.e. inside and outside the component | private, only available inside the component |
| Changeable by parents | yes | no |
| Changeable by component itself | no | yes |
| Change mechanism | parent changes prop | component calls this.setState(newState) |
| Change triggers re-rendering of component | yes | yes |
Wednesday, October 12, 2016
React State and Props compared
Not much blabla today, just a table that compares the differences between React's props and state.
Thursday, April 14, 2016
Why I prefer functional over classical and prototypal inheritance
There are multiple ways in which inheritance can be implemented in JavaScript. In fact so many that the choice easiely gets difficult. I am going to quickly introduce them with a code example and then explain why my recommodation is using functional inheritance in the vast majority of cases.
Classical inheritance
The intention of this pattern (sometimes referred also as pseudo classical inheritance) is to hide away the prototypal nature of JavaScript and look as if JavaScript knew about the concept of classes so that developers coming from languages like Java or C# will find the syntax quite familiar.
Look at this simplified example:
There are quite a bunch of gotchas with this pattern and it's variations (details see for example in the book 'JavaScript Patterns', chapter 'Code reuse patterns'. Another general problem is that classical inheritance hides away the "real", i.e. prototypal nature of JavaScript. Due to these reasons I personally would try to avoid the usage.
Prototypal inheritance
This pattern is based on the
One common gotcha (that also is valid for classical inheritance) comes into play when you have complex objects in the parent:
The reason for the last line's result lies in the way how JavaScript is getting and setting properties.
When getting a property, JavaScript will traverse up the entire prototype chain looking for it and returning the first occurence.
Setting values is different: Javascript will always set a property in the most derived object - but only if it's not a complex object.
What happens here with
Functional inheritance
In his book 'JavaScript: The Good Parts' Douglas Crockford advocates for an approach that he calls 'functional inheritance'. Let's look at an example (btw the usage of ES5 arrow functions and template strings and
What are the advantages of this approach?
There are unfortunately also some bad news:
But still, in my opinion the advantages of functional inheritance outweight the disadavantages, especially because of the fact that in the vast majority of the real life use cases the mentioned drawbacks are not a really problematic.
Finally a word of caution: do not exaggerate the usage of inheritance, instead adhere to one of the most important OO principles and prefer composition over inheritance!
Classical inheritance
The intention of this pattern (sometimes referred also as pseudo classical inheritance) is to hide away the prototypal nature of JavaScript and look as if JavaScript knew about the concept of classes so that developers coming from languages like Java or C# will find the syntax quite familiar.
Look at this simplified example:
There are quite a bunch of gotchas with this pattern and it's variations (details see for example in the book 'JavaScript Patterns', chapter 'Code reuse patterns'. Another general problem is that classical inheritance hides away the "real", i.e. prototypal nature of JavaScript. Due to these reasons I personally would try to avoid the usage.
Prototypal inheritance
This pattern is based on the
Object.create method which was introduced with ES5 and is a more "natural" choice than classical inheritance.
One common gotcha (that also is valid for classical inheritance) comes into play when you have complex objects in the parent:
The reason for the last line's result lies in the way how JavaScript is getting and setting properties.
When getting a property, JavaScript will traverse up the entire prototype chain looking for it and returning the first occurence.
Setting values is different: Javascript will always set a property in the most derived object - but only if it's not a complex object.
What happens here with
schwolf.parts.legs = 1 is that - according to the getting rule - the parts object from the base class is returned. Because parts is a complex object it set's it's legs property to 1. And why does this affect all instances? This is the big differnence between prototypal inheritance and Java/C#: prototypes are 'referenced' whereas Java/C# base classes get part of the object and don't share anything with other instances (except for stuff that is explicitely marked as 'static').Functional inheritance
In his book 'JavaScript: The Good Parts' Douglas Crockford advocates for an approach that he calls 'functional inheritance'. Let's look at an example (btw the usage of ES5 arrow functions and template strings and
Object.assign is just for keeping the example concise):What are the advantages of this approach?
- easy to grasp - note that we only use functions and no (relatively complicated) prototypes or constructors
- no gotchas
- encapsulation (private members), see nameLength variable in person function
- high performance after object creation
There are unfortunately also some bad news:
- low performance when creating many objects
- less dynamic than prototypal inheritance (prototype augmention not possible at any time like with prototypal inheritance)
- instanceof not possible
But still, in my opinion the advantages of functional inheritance outweight the disadavantages, especially because of the fact that in the vast majority of the real life use cases the mentioned drawbacks are not a really problematic.
Finally a word of caution: do not exaggerate the usage of inheritance, instead adhere to one of the most important OO principles and prefer composition over inheritance!
Friday, April 1, 2016
Is a JavaScript function which takes a callback as a parameter automatically async?
As JavaScript programmers we know that with ES6 promises, the notion of asyncronous programming has been built into JavaScript natively. Using promises guarantees that code is performed asynchronously.
But have you been aware that before ES6, the language itself did not have support for sync/async programming?
"That's not true!" you will probably say, "I have been using setTimeout and Ajax long before ES6! And you tell me that they are not async ??".
Well, the mentioned examples are clearly examples for async functionality, but: it is not functionality which is coming from the JavaScript language! Instead, it is functionality that comes from the environment in which JavaScript is executed (browser, nodejs...).
Indeed language-built-in constructs were not available.
So, how does setTimeout etc. this work?
On a low level this works because hardware interrupts signal events to the operating system which in turn then passes them to the JavaScript engine.
Takeaway: asyncronity is only achieved by using the environment's async functionality - or by leveraging promises functionality, either natively via ES6 promises or using promise libraries like Q.
Now let's go back to the original question from the title of this blog post: is every higher level function (a function that takes another function as an argument) async?
Having the background above in mind it should be obvious that the answer is no - because not all of such functions use async functionality from the environment.
Need examples? Check out Array.sort(compareFx) or String.replace(stringToReplace, replaceFx)...
And how can you find out if a function that you consume is async or not? There are only two possibilites: from the documentation or by digging into the code.
PS: Promises are not the end of the evolution of async programming in JavaScript. There is currently a proposal at stage 3 which deals with the introduction of async / await keywords in the language (btw: this is very similar to how the C# syntax looks).
But have you been aware that before ES6, the language itself did not have support for sync/async programming?
"That's not true!" you will probably say, "I have been using setTimeout and Ajax long before ES6! And you tell me that they are not async ??".
Well, the mentioned examples are clearly examples for async functionality, but: it is not functionality which is coming from the JavaScript language! Instead, it is functionality that comes from the environment in which JavaScript is executed (browser, nodejs...).
Indeed language-built-in constructs were not available.
So, how does setTimeout etc. this work?
On a low level this works because hardware interrupts signal events to the operating system which in turn then passes them to the JavaScript engine.
Takeaway: asyncronity is only achieved by using the environment's async functionality - or by leveraging promises functionality, either natively via ES6 promises or using promise libraries like Q.
Now let's go back to the original question from the title of this blog post: is every higher level function (a function that takes another function as an argument) async?
Having the background above in mind it should be obvious that the answer is no - because not all of such functions use async functionality from the environment.
Need examples? Check out Array.sort(compareFx) or String.replace(stringToReplace, replaceFx)...
And how can you find out if a function that you consume is async or not? There are only two possibilites: from the documentation or by digging into the code.
PS: Promises are not the end of the evolution of async programming in JavaScript. There is currently a proposal at stage 3 which deals with the introduction of async / await keywords in the language (btw: this is very similar to how the C# syntax looks).
Monday, September 21, 2015
Configuring Synology NAS for my home network
After having plugged my DS215j into my home network some fine tuning had to be done. This following list is my personal protocol in case I have to do this once again - perhaps it is be helpful for other Synology users as well.
1. DSM 5.2 more or less forces the user to put multimedia files into auto-generated folders (video/photo/music). However on my clients I prefer one share "multimedia" over mapping three network drives. I solved this by setting up a shared folder "multimedia" containing 3 symbolic links video, photo and music that point to the corresponding auto-generated folders (here is how to create permanent symbolic links on the Synology - note that you have to have some knowledge how vi works)
2. User accounts for my wife, the children and me are to be set up. Note that interaction between Synology and Windows / Mac without a directory server works best if credentials are kept synchronous both on clients and the NAS.
3. The three folders mentioned above had to be given appropriate permissions: read-write for admin group and my own user, my wife and the children are only allowed to read ;-)
4. On each of the clients, I mapped 2 network drives: the multimedia share and a personal home.
5. Configured standby behavior of the HDDs:
6. Set up Cloud Station for my working directories both on Synology and my clients. I tried out cloud sync with dropbox but moved away from that again because of privacy concerns ;-) and the fact that this is interfering with the standby times of the HDDs.
7. Configuration of automatic shutdown at night:
8. Due to security reasons I changed SSH to use a different port than default port 22.
9. I assigned the machine a static IP in my router configuration.
10. Because I want to have a public accessible node server I configured DDNS (at first I tried to do this within my router, but changes of the public IP were not notified the the DDNS provider):
11. To start the node server on automatically I added "node [path to js starting http server]" to rc.local
12. Port forwarding configured in router:
12. Note that Synology's multimedia apps Audio, Video and PhotoStation are only necessary when you want to access your multimedia through the browser - which is not the case for me, so I did not activate them.
1. DSM 5.2 more or less forces the user to put multimedia files into auto-generated folders (video/photo/music). However on my clients I prefer one share "multimedia" over mapping three network drives. I solved this by setting up a shared folder "multimedia" containing 3 symbolic links video, photo and music that point to the corresponding auto-generated folders (here is how to create permanent symbolic links on the Synology - note that you have to have some knowledge how vi works)
2. User accounts for my wife, the children and me are to be set up. Note that interaction between Synology and Windows / Mac without a directory server works best if credentials are kept synchronous both on clients and the NAS.
3. The three folders mentioned above had to be given appropriate permissions: read-write for admin group and my own user, my wife and the children are only allowed to read ;-)
4. On each of the clients, I mapped 2 network drives: the multimedia share and a personal home.
5. Configured standby behavior of the HDDs:
6. Set up Cloud Station for my working directories both on Synology and my clients. I tried out cloud sync with dropbox but moved away from that again because of privacy concerns ;-) and the fact that this is interfering with the standby times of the HDDs.
7. Configuration of automatic shutdown at night:
8. Due to security reasons I changed SSH to use a different port than default port 22.
9. I assigned the machine a static IP in my router configuration.
10. Because I want to have a public accessible node server I configured DDNS (at first I tried to do this within my router, but changes of the public IP were not notified the the DDNS provider):
11. To start the node server on automatically I added "node [path to js starting http server]" to rc.local
12. Port forwarding configured in router:
12. Note that Synology's multimedia apps Audio, Video and PhotoStation are only necessary when you want to access your multimedia through the browser - which is not the case for me, so I did not activate them.
Tuesday, August 25, 2015
Node / V8 versions and ES6 features on my Synology
I've set up a Synology NAS in my home network last week. One of the reasons was that I want to run a node server, and Synology offers it out of the box with DSM 5.2.
Because I want to check out / make use of ES6 features I had to find out which versions of Node and V8 are coming with the package. This is how I did it on the SSH shell:
Fortunately there is a discussion on StackOverflow which answers which features node has enabled by default and which can optionally be enabled using the --harmony flag.
Because I want to check out / make use of ES6 features I had to find out which versions of Node and V8 are coming with the package. This is how I did it on the SSH shell:
Fortunately there is a discussion on StackOverflow which answers which features node has enabled by default and which can optionally be enabled using the --harmony flag.
Sunday, May 3, 2015
Key takeaways from working with async/await in C#
There is a lot of information available around the web about asynchronous programming with async/await in C#. In this post I am going to explain my personal key takeaways.
In general, the pattern is all about avoiding to have threads in idle state, doing nothing but waiting for some time consuming operation to finish (you also have better things to do than waiting for the pizza in front of your door after you ordered it, right?).
Why is this needed? There are two scenarios: In user interfaces, the "free" UI thread can be used to react on user actions while the asynchronous operation takes place. User actions can be things like moving the window around, resizing, clicking buttons and so on. On the server side (e.g. in an ASP.NET web application), the "free" threads can be used to process other requests, i.e. the application's scalability will be improved.
For further discussion let's have a look at the following example code from MSDN:
In general, the pattern is all about avoiding to have threads in idle state, doing nothing but waiting for some time consuming operation to finish (you also have better things to do than waiting for the pizza in front of your door after you ordered it, right?).
Why is this needed? There are two scenarios: In user interfaces, the "free" UI thread can be used to react on user actions while the asynchronous operation takes place. User actions can be things like moving the window around, resizing, clicking buttons and so on. On the server side (e.g. in an ASP.NET web application), the "free" threads can be used to process other requests, i.e. the application's scalability will be improved.
For further discussion let's have a look at the following example code from MSDN:
1: async Task<int> AccessTheWebAsync()
2: {
3: HttpClient client = new HttpClient();
4: Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");
5: DoIndependentWork();
6: string urlContents = await getStringTask;
7: return urlContents.Length;
8: }
- Async and await are appearing together: async is part of the method signature, await is used at least once within the method (Lines 1 and 6)
- An async method returns Task<T>, Task or void (in rare cases) (Line 1)
- Tasks can be considered as "containers" of work that has to be done.
- There is a convention that says async method names should be postfixed with "...Async" (Line 1)
- When an async method is called, the work within this method is kicked off but usually not finished, hence the return value is not the final result (string in this case) but the task which encapsulates the work (Line 4).
- You can do other stuff while the async task is being performed (Line 5)
- When our code hit's await it either continues processing when the result is already available, or - when the result is not yet available - it will for now pass control back to the caller. But await implies a promise that once the result is available the program will jump back continuing processing the result (Line 6).
- The naming of "await" is a bit misleading. Think of it as "continue after task has been finished", i.e. in the above example: "continue after getStringTask has been finished" (Line 6)
- For an async method, internally a state machine is created by the compiler that does all the heavy lifting.
- Note that the datatype represents is a string and not a task any more, i.e. await automatically unwraps the generic type parameter from the Task (Line 6).
- async/await are often going up the complete call stack, i.e. all the methods in the stack are async
An interesting source of information you might want to check out when working with asynchrony in C# is the article "Best Practices in Asynchronous Programming" from MSDN magazin.
Monday, March 16, 2015
Automating client side testing with Karma
Google says "The main goal for Karma is to bring a productive testing
environment to developers."
I recently found a nice answer on stackoverflow explaining how Karma is doing this.
This inspired me to create a visualization on this topic, here it is:
This is how it works:
1. The Karma HTTP server is launched. It serves a test framework specific html file (test.html) which references both application specific javascripts (app.js) and the tests (specs.js)
2. A browser is being launched which requests test.html
3. Karma HTTP server serves test.html and the referenced javascript files.
4. The tests are run within the client.
5. The results are submitted to the Karma HTTP server.
6. Based on the configured loggers, the results are being rendered to the console, a textfile or other output formats. The output can be checked manually or processed automatically.
Karma is highly configurable, the most important configurations are:
I recently found a nice answer on stackoverflow explaining how Karma is doing this.
This inspired me to create a visualization on this topic, here it is:
This is how it works:
1. The Karma HTTP server is launched. It serves a test framework specific html file (test.html) which references both application specific javascripts (app.js) and the tests (specs.js)
2. A browser is being launched which requests test.html
3. Karma HTTP server serves test.html and the referenced javascript files.
4. The tests are run within the client.
5. The results are submitted to the Karma HTTP server.
6. Based on the configured loggers, the results are being rendered to the console, a textfile or other output formats. The output can be checked manually or processed automatically.
Karma is highly configurable, the most important configurations are:
- The list of files to load in the browser (app.js)
- The testing framework which is used (e.g. jasmine) has to be configured and appropiate plugins have to be loaded - note that this also determines the html page (test.html) because it is framework specific
- The list of browsers (can be a headless one like phantom.js, too) to launch and run tests in
- The list of log appenders (console, textfile...) to be used
Note that 2., 3. and 4. support a plugin mechanism, i.e. Karma will load appropriate plugins. Such plugins are available for the most common scenarios, for more exotic scenarios you could write them on your own.
Monday, February 16, 2015
How TFS and git can play together
Playing around with Git for some days now, I see the following benefits over centralized systems (ordered by importance):
The solution is a hybrid way: installing git-tfs (a two way bridge between git and tfs, the platform neutral alternative is Microsofts git-tf) makes it possible to work with git locally while the remote repository stays TFVC, i.e. every developer on the project is free to decide to choose between working with the bridge or using TFS "traditionally".
To be complete, let me mention a 3rd option: there may be situations where the only need for TFS functionality is the usage of TFS build processes (i.e. no work item management and other TFS functionality). For these scenarios, it is possible to use Visual Studio and git without TFVC, hosting the "central" repository e.g. at github.
The following table contains the support of the features work item management, build process usage and gated checkin in relation to the mentioned possibilities how TFS and git can play together:
- quick context switches between branches and quick setup of new branches
- faster, due to fewer network traffic
- using state-of-the-art technology, e.g. consistent style of working with open source community
- no need to be online
- inherent decentralized backup of repositories
- 2-way commit (i.e. staging area) gives more fine-grained control about what to check in
The solution is a hybrid way: installing git-tfs (a two way bridge between git and tfs, the platform neutral alternative is Microsofts git-tf) makes it possible to work with git locally while the remote repository stays TFVC, i.e. every developer on the project is free to decide to choose between working with the bridge or using TFS "traditionally".
To be complete, let me mention a 3rd option: there may be situations where the only need for TFS functionality is the usage of TFS build processes (i.e. no work item management and other TFS functionality). For these scenarios, it is possible to use Visual Studio and git without TFVC, hosting the "central" repository e.g. at github.
The following table contains the support of the features work item management, build process usage and gated checkin in relation to the mentioned possibilities how TFS and git can play together:
| work item mgmt. | build process usage | gated checkin | |
| TFS-git | yes | yes | no |
| git-tfs (locally git, remote TFVC) | yes | yes | no |
| git with any non-TFVC (e.g. github) | no | yes | no |
Monday, December 15, 2014
Rhino Mocks AAA syntax recommondations
The multiple models that are supported by Rhino Mocks (Standard, Record/Replay, Fluent, Act/Arrange/Assert) together with some weaknesses in the documentation make the software a bit unintuitive to use for the beginner - that was my own experience as well as the experience of several people I spoke to.
I personally prefer AAA syntax over the others, mainly due to the fact that this is the style which is used in many other testing frameworks both for server and client side testing.
2 things helped me a lot:
First, check out the Rhino Mocks AAA Syntax Quick Reference assembled by Sven - thanks a lot!
Second, following Ayende's recommendations on how to use AAA make life easier:
- In general, prefer stubs over mocks. Mocks are only necessary for complex interactions
- Use the static MockRepository.Generate... methods instead of newing up MockRepository (see box "Create Mocks/Stubs" in the quick reference)
- Do not use CreateMock and StriktMock
- Use inline constraints instead of .IgnoreArguments()
Tuesday, November 25, 2014
DDD Dos and Don'ts in a real life project
We recently reviewed our two year old DDD / Hexagonal architecture based online shop ASP.NET MVC application and tried to identify the DDD related issues which should be refactored (or at least avoid in new applications). Here is a short abstract about the list of the main findings:
Domain Anaemia
Some of the domain objects are quite anaemic. That is mainly the case in places where we are the application is integrating web services which are already covering most (or all) of the domain stuff.
An example for this is a pricing web service which takes care about customer price calculations, rebates, currency conversions and so on (in other words: a lot of business rules). Our conclusion is that it in fact makes sense to apply DDD to this pricing service – but it does not make sense to apply DDD in the parts of the consuming applications that are dealing with this topic because all you do is get the data from the pricing service, pass it through the separate layers and display it. No business rules and stuff, so no need for a domain layer.
We probably would nowadays even go a step further: we would actually prefer a pure non-DDD presentation application which is only taking care about presentation concerns and is integrating web services that are containing all the business rules and are DDD based. Like this it can be avoided to have kind of a hybrid architecture in one application (parts of the application are worth applying DDD, other parts are just passing results from the infrastructure layer to the UI). Moreover in the past it turned out that most of the “DDD worthy” stuff will sooner or later be used by other clients than our application (e.g. the prices are needed by the companies CRM system) and then it anyway makes sense to separate this parts from the application.
Other examples than the pricing service which I already mentioned would be a product service, a cart management service, an order tracking service or an availability service.
Separation of application services
We initially thought that it would make sense to separate our different application services (the “use case controllers”) from each other, e.g. we have an independent “CartApplicationService”, “CatalogApplicationService”, “PricingApplicationService” and so on.
Now we had the following situation more than once: one of these services actually had to use data that was already processed by one of the other services. Because we had defined that as being not possible (we used Visual Studio’s Architecture Diagram functionality to forbid it) the developers usually found workarounds containing duplicated code (sometimes only few lines, sometimes more) which is clearly violating the DRY principle.
This strict separation does not make sense. The reason for this is that there are basically 3 classifications of services (chapter 6 of the book "SOA in Practise" covers the details):
- basic services wrap or hide implementation details of a specific single backend and can be either data-driven or logic-driven
- composed services are using ("orchestrate") multiple basic services or other composed services
- process services handle long running workflows or business processes and are - in contrast to the other classifications - usually stateful.
Only the first of these - the basic service - does have the constraint that it must not communicate with other services. Though the author mainly talks about the classification of web services the same can be applied to application services. The important thing is to be aware of which type an application service is and deal with its dependencies accordingly. This approach is much better than finding workarounds including acceptance of DRY-violations.
Application service return types
Application services are sometimes called “use case controllers”. Might be due to this we made the mistake that we created specialized return data types (DTOs) for more or less every application service method. That certainly resulted in an explosion of the number of DTO classes and classes that are mapping domain objects to these DTOs. On the other hand, view models in our presentation layer were more or less useless. They were nearly always a 1:1 representation of the DTOs.
The preferred way is to let the application services return much fewer different data types (usually the DTO representations of the domain objects) and use view models as they are thought to be used, i.e. mapping to formats that are needed by the UI.
DAOs versus repositories
At the point of time we started modelling the application we were not aware of the differences between repositories and DAOs at all. We for instance created two assemblies within the infrastructure layer – one for database access and one for service proxies. When we started using real repositories (instead of DAOs that were named repositories) we soon needed repository implementations that contained both database access components and service proxies. Now we had the choice between creating a new third assembly containing these repositories and referencing the two others or to arbitrarily choose one of the existing assemblies for putting the repository implementations there and referencing the other assembly.
All of these solutions seem to be suboptimal – the solution is to just create one infrastructure assembly containing everything (which does not mean that every type of component should have access to all other types – which in turn can be avoided introducing Visual Studio Architecture Diagrams or using a tool like NDepend).
Domain Anaemia
Some of the domain objects are quite anaemic. That is mainly the case in places where we are the application is integrating web services which are already covering most (or all) of the domain stuff.
An example for this is a pricing web service which takes care about customer price calculations, rebates, currency conversions and so on (in other words: a lot of business rules). Our conclusion is that it in fact makes sense to apply DDD to this pricing service – but it does not make sense to apply DDD in the parts of the consuming applications that are dealing with this topic because all you do is get the data from the pricing service, pass it through the separate layers and display it. No business rules and stuff, so no need for a domain layer.
We probably would nowadays even go a step further: we would actually prefer a pure non-DDD presentation application which is only taking care about presentation concerns and is integrating web services that are containing all the business rules and are DDD based. Like this it can be avoided to have kind of a hybrid architecture in one application (parts of the application are worth applying DDD, other parts are just passing results from the infrastructure layer to the UI). Moreover in the past it turned out that most of the “DDD worthy” stuff will sooner or later be used by other clients than our application (e.g. the prices are needed by the companies CRM system) and then it anyway makes sense to separate this parts from the application.
Other examples than the pricing service which I already mentioned would be a product service, a cart management service, an order tracking service or an availability service.
Separation of application services
We initially thought that it would make sense to separate our different application services (the “use case controllers”) from each other, e.g. we have an independent “CartApplicationService”, “CatalogApplicationService”, “PricingApplicationService” and so on.
Now we had the following situation more than once: one of these services actually had to use data that was already processed by one of the other services. Because we had defined that as being not possible (we used Visual Studio’s Architecture Diagram functionality to forbid it) the developers usually found workarounds containing duplicated code (sometimes only few lines, sometimes more) which is clearly violating the DRY principle.
This strict separation does not make sense. The reason for this is that there are basically 3 classifications of services (chapter 6 of the book "SOA in Practise" covers the details):
- basic services wrap or hide implementation details of a specific single backend and can be either data-driven or logic-driven
- composed services are using ("orchestrate") multiple basic services or other composed services
- process services handle long running workflows or business processes and are - in contrast to the other classifications - usually stateful.
Only the first of these - the basic service - does have the constraint that it must not communicate with other services. Though the author mainly talks about the classification of web services the same can be applied to application services. The important thing is to be aware of which type an application service is and deal with its dependencies accordingly. This approach is much better than finding workarounds including acceptance of DRY-violations.
Application service return types
Application services are sometimes called “use case controllers”. Might be due to this we made the mistake that we created specialized return data types (DTOs) for more or less every application service method. That certainly resulted in an explosion of the number of DTO classes and classes that are mapping domain objects to these DTOs. On the other hand, view models in our presentation layer were more or less useless. They were nearly always a 1:1 representation of the DTOs.
The preferred way is to let the application services return much fewer different data types (usually the DTO representations of the domain objects) and use view models as they are thought to be used, i.e. mapping to formats that are needed by the UI.
DAOs versus repositories
At the point of time we started modelling the application we were not aware of the differences between repositories and DAOs at all. We for instance created two assemblies within the infrastructure layer – one for database access and one for service proxies. When we started using real repositories (instead of DAOs that were named repositories) we soon needed repository implementations that contained both database access components and service proxies. Now we had the choice between creating a new third assembly containing these repositories and referencing the two others or to arbitrarily choose one of the existing assemblies for putting the repository implementations there and referencing the other assembly.
All of these solutions seem to be suboptimal – the solution is to just create one infrastructure assembly containing everything (which does not mean that every type of component should have access to all other types – which in turn can be avoided introducing Visual Studio Architecture Diagrams or using a tool like NDepend).
Monday, April 14, 2014
The famous "broken closures in loop" bug
I bet I am not the first who introduced this closure related type of bug in my javascript code:
Say you wanted to add "onclick"-functionaly to a number of similar UI Elements where the behavior for each item should only differ in one parameter - in the following simplified example the element should alert it's index within the list of elements that have the css class "someCssClass" applied:
Expected behavior is that clicking the first UI element alerts "0", the second "1" and so on.
If you tried this out you would see that this does not work as expected. Instead, every element alerts the index of the last element.
Can you spot the bug?
The reason why the index of the last element is being displayed is that the anonymous function is being called after the loop has executed. At this point in time the value of i is already elems.length - 1 for all elements.
To fix this we need to introduce a different "lexical environment". There are multiple ways to do this, here is one which adheres to JSLint's recommodation not to make functions within a loop:
But why is this working?
The reasons are:
1. With the introduction of function "alertIndex" we introduced a new lexical environment. The interpreter works in a way that it is traversing up the lexical environments until it finds the appropriate variable (and "encloses" it as it would be it's own variable - therefore the denomiation "closure"). In that case it does not find it in the anonymous function which is triggering the alert but one level up inside "alertIndex".
2. Variables in outer lexical environments might change, but inner lexical environments do always see the last value.
More about lexical environments and closures can be found at http://javascript.info/tutorial/closures
Say you wanted to add "onclick"-functionaly to a number of similar UI Elements where the behavior for each item should only differ in one parameter - in the following simplified example the element should alert it's index within the list of elements that have the css class "someCssClass" applied:
var elems = document.getElementsByClassName("someCssClass");
for (var i = 0; i < elems.length; i++) {
elems[i].addEventListener("click", function() {
alert(i);
});
}
Expected behavior is that clicking the first UI element alerts "0", the second "1" and so on.
If you tried this out you would see that this does not work as expected. Instead, every element alerts the index of the last element.
Can you spot the bug?
The reason why the index of the last element is being displayed is that the anonymous function is being called after the loop has executed. At this point in time the value of i is already elems.length - 1 for all elements.
To fix this we need to introduce a different "lexical environment". There are multiple ways to do this, here is one which adheres to JSLint's recommodation not to make functions within a loop:
var elems = document.getElementsByClassName("myClass");
for (var i = 0; i < elems.length; i++) {
elems[i].addEventListener("click", alertIndex(i));
}
function alertIndex(i) {
return function() {
alert(i);
};
}
But why is this working?
The reasons are:
1. With the introduction of function "alertIndex" we introduced a new lexical environment. The interpreter works in a way that it is traversing up the lexical environments until it finds the appropriate variable (and "encloses" it as it would be it's own variable - therefore the denomiation "closure"). In that case it does not find it in the anonymous function which is triggering the alert but one level up inside "alertIndex".
2. Variables in outer lexical environments might change, but inner lexical environments do always see the last value.
More about lexical environments and closures can be found at http://javascript.info/tutorial/closures
Monday, November 18, 2013
Repositories vs. DAOs
Dealing with DDD for some time now, I asked myself the following question:
What is the difference between a Repository and a DAO (Data Access Object) ?
The reason for the question was that in many repositories (real world projects and tutorials on the web) I could not see much difference to good old DAOs.
Let's say you we have a functionality which is grabbing customers out of your database - seems to be modern to call stuff like this "CustomerRepository" - I personally doubt that this is what DDD is aiming at.
I started searching on the web but it was not so easy to find a precise answers but finally I stumbled over a very good blog post with illustrative examples. You definitely should check this out. I just would like to abstract it by opposing different aspects of repositories and DAOs:
What is the difference between a Repository and a DAO (Data Access Object) ?
The reason for the question was that in many repositories (real world projects and tutorials on the web) I could not see much difference to good old DAOs.
Let's say you we have a functionality which is grabbing customers out of your database - seems to be modern to call stuff like this "CustomerRepository" - I personally doubt that this is what DDD is aiming at.
I started searching on the web but it was not so easy to find a precise answers but finally I stumbled over a very good blog post with illustrative examples. You definitely should check this out. I just would like to abstract it by opposing different aspects of repositories and DAOs:
| Repository | DAO |
| "business interface" speaking ubiquitous domain language | "technical interface" contracting between data source and OO application |
| Close to domain | Close to data source |
| typically one per aggregate root | typically one per database table (or web service operation) |
| containing one or multiple DAOs | used by a repository |
| interfaces in domain layer | interfaces in infrastructure layer |
| parameters of interface methods are domain types | parameters of interface methods are reflecting the data source |
| implementations in infrastructure layer (lots of technical plumbing) | implementations in infrastructure layer (purely technical) |
Friday, October 11, 2013
The seven falsy values in JavaScript
JavaScript is different from other languages regarding the evaluation if a value is true or false.
The easiest way is to remember the 7 values that are evaluated to "false".
Here they are (some of them are obvious, some are a bit surprising):
This behavior can be used in different ways, e.g. shortening the check if a jQuery selector returns elements or not:
if ($('#foo').length > 0) {
...
}
can also be checked as follows (because jQuery returns an array of length 0 which is evaluated to "false"):
if ($('#foo').length) {
...
}
Note that you can produce subtle bugs if you are not aware of the evaluation rules.
Example:
function printLineItem(article, price) {
if (article && price) {
console.log("Article: " + article + "Price: " + price);
}
}
printLineItem("Amiga 500", 999);
printLineItem("5 bitcoins voucher for next purchase", 0);
Bad luck for the customer, he won't get the voucher :-(
The easiest way is to remember the 7 values that are evaluated to "false".
Here they are (some of them are obvious, some are a bit surprising):
- undefined
- null
- false
- +0
- -0
- NaN
- "" (empty string)
This behavior can be used in different ways, e.g. shortening the check if a jQuery selector returns elements or not:
if ($('#foo').length > 0) {
...
}
can also be checked as follows (because jQuery returns an array of length 0 which is evaluated to "false"):
if ($('#foo').length) {
...
}
Note that you can produce subtle bugs if you are not aware of the evaluation rules.
Example:
function printLineItem(article, price) {
if (article && price) {
console.log("Article: " + article + "Price: " + price);
}
}
printLineItem("Amiga 500", 999);
printLineItem("5 bitcoins voucher for next purchase", 0);
Bad luck for the customer, he won't get the voucher :-(
Friday, July 19, 2013
JavaScript type checks
JavaScript type checks have slight complexity. This and the reason that your code should be consistent through your project(s) make it necessary that type checks are part of your javascript programming guidelines.
I am using the recommodations from the jQuery project.
They say:
String
Global Variables
I am using the recommodations from the jQuery project.
They say:
String
typeof object === "string"
Number
typeof object === "number"
Boolean
typeof object === "boolean"
Object
typeof object === "object"
Plain Object
jQuery.isPlainObject(object)
Function
jQuery.isFunction(object)
Array jQuery.isArray(object)
Element object.nodeType
null
object === null
null or undefined
object == null
undefinedGlobal Variables
typeof variable === "undefined"
Local Variables
variable === undefined
Properties
object.prop === undefined
Thursday, March 7, 2013
The evolution of delegates and anonymous methods
A delegate is a type that safely encapsulates a method, see MSDN for a deep-dive.
I want to concentrate on showing how delegates evolved during the versions of the .NET Framework.
Let's look at .NET Framework 1.0 first:
A delegate declaration looks like this:
Next, you need a method with a signature that is corresponding to the delegate declaration:
Delegates are classes (derived from System.MulticastDelegate), so they can be instantiated:
With .NET Framework 2.0 the C# compiler shipped with a feature called "delegate inference". That gives you the possibility to omit the instantiation with "new". Because you mention the delegate once ("NetWageCalculation calc = ..."), the compiler automatically recognizes that you want to new up a delegate:
Moreover, this version of the Framework supported anonymous methods. With anonymous methods the amount of code that had to be written for instantiation of delegates was reduced because no separate methods had to be coded any more:
The next step in evolution of delegates were lambda expressions introduced in .NET Framework 3.5. Lambdas are simplifying anonymous methods:
Examining closely, we will realize that there is still a lot of "ceremony" in the the code snipped above. Two features allow further simplification:
"Delegate type inference" gives you the possibility to omit the types of parameters ("Employee" in that case) - the compiler automatically detects the types of the passed parameters.
"Return type inference" gives you the possibility to omit the return statement.
Again without disturbing strike-throughs:
I want to concentrate on showing how delegates evolved during the versions of the .NET Framework.
Let's look at .NET Framework 1.0 first:
A delegate declaration looks like this:
public delegate double NetWageCalculation(Employee emp);
Next, you need a method with a signature that is corresponding to the delegate declaration:
public double GetTaxReducedWage(Employee emp)
{
return emp.GrossWage * 0.8;
}
Delegates are classes (derived from System.MulticastDelegate), so they can be instantiated:
NetWageCalculation calc = new NetWageCalculation(GetTaxReducedWage);
With .NET Framework 2.0 the C# compiler shipped with a feature called "delegate inference". That gives you the possibility to omit the instantiation with "new". Because you mention the delegate once ("NetWageCalculation calc = ..."), the compiler automatically recognizes that you want to new up a delegate:
NetWageCalculation calc = new NetWageCalculation(GetTaxReducedWage);
Moreover, this version of the Framework supported anonymous methods. With anonymous methods the amount of code that had to be written for instantiation of delegates was reduced because no separate methods had to be coded any more:
NetWageCalculation calc3 = delegate(Employee emp) { return emp.GrossWage * 0.8; };
The next step in evolution of delegates were lambda expressions introduced in .NET Framework 3.5. Lambdas are simplifying anonymous methods:
NetWageCalculation calc3 = delegate(Employee emp) => { return emp.GrossWage * 0.8; };
Examining closely, we will realize that there is still a lot of "ceremony" in the the code snipped above. Two features allow further simplification:
"Delegate type inference" gives you the possibility to omit the types of parameters ("Employee" in that case) - the compiler automatically detects the types of the passed parameters.
"Return type inference" gives you the possibility to omit the return statement.
NetWageCalculation calc3 = (Employee emp) => { return emp.GrossWage * 0.8; };
Again without disturbing strike-throughs:
NetWageCalculation calc3 = emp => emp.GrossWage * 0.8;
Thursday, February 7, 2013
Implicite transactions in SQL Server
Assume you are "quickly" fireing a single statement like this within SQL Server Management Studio:
Dependend on the number of rows in the Person table and the overall performance of your database server this statement will run for some amount of time. During it runs you have the possibility to stop it hitting the "Cancel Executing Query" button.
Why can you cancel the query without having any of the Birthdates updated?
This works because internally, SqlServer is performing single statements in a transaction, even if you did not specify this explicitely. So the above statement is actually the same as
UPDATE Person SET Birthdate = '1976-09-20'
Dependend on the number of rows in the Person table and the overall performance of your database server this statement will run for some amount of time. During it runs you have the possibility to stop it hitting the "Cancel Executing Query" button.
Why can you cancel the query without having any of the Birthdates updated?
This works because internally, SqlServer is performing single statements in a transaction, even if you did not specify this explicitely. So the above statement is actually the same as
BEGIN TRANSACTION
UPDATE Person SET Birthdate = '1976-09-20'
COMMIT
Friday, January 18, 2013
Good practises for unit testing
When performing unit test (no matter which language, the same applies to e.g. javascript unit tests) make sure your tests are fullfilling the some quality criteria.
Unit tests should...
... be deterministic: Assert.Equals(Random.Next(), myResultingNumber) is probably a bad idea ;-)
... be repeatable: you should be able to run them 1, 100 or 1000 times in a row, the results shall always be the same.
... be order independent: running TestB before TestA shouldn't have any influence.
... be isolated: strive for not using external systems like databases or services, use a mocking framework instead. Reason: doing not so will make it hard to fulfill some of the other principles listed here, e.g. "fast", "easy to setup", "deterministic" (think about a temporary network problem when connecting a test database).
... run fast: slow tests will decrease your productivity and they will be run fewer times because no one likes waiting
... be included in continuous integration process: don't rely on developers manually triggering of the tests, they should be run automatically (as often as possible).
... be easy to setup: the danger in hard to setup tests is that they are simply not written.
... be either atomic or integration tests: atomic tests (i.e. tests that cover a very specific, small amount of functionality) are a must, integration tests (covering the collaboration of multiple modules) are not always necessary but sometimes useful. The disadvantage in integration test is that in case of failing tests, problems are harder to find whereas a failing atomic unit test often even does not have to get debugged to find the problem. Do not mix both types but make a clear separation (e.g. by introducing naming conventions).
... have one logical assert per test: does not mean you should never have multiple asserts in your test case, but if this is the case make sure the asserts are tightly logically connected to each other.
... concentrate on the public "API" of your SUT (which normally covers private methods. Note that the need of testing private methods is often an indicator for violation of SRP within the class).
... read like documentation for your system: benefit from your test suite also in a way that it is an additional documentation for your software. Actually, a system without unit tests cannot be conidered as being "valid": it might be free from obvious bugs (such as users get error messages), but that does not always mean that it works as it should (and often other documentation - if available at all - is far away from being as precise as unit tests in describing desired behavior).
... have the same code quality as productive code: there is NO reason for neglecting unit test code. It will grow like productive code grows, you will get the same problems as with your productive code if you are not applying the same patterns and practises.
... also cover the "sad" path, not only the "happy" path: also test unexpected values and behavior including tests for exceptions.
... be written each time a bug in development, testing or on your live system is occuring. Like this you make sure that this bug is abandoned forever.
Unit tests should...
... be deterministic: Assert.Equals(Random.Next(), myResultingNumber) is probably a bad idea ;-)
... be repeatable: you should be able to run them 1, 100 or 1000 times in a row, the results shall always be the same.
... be order independent: running TestB before TestA shouldn't have any influence.
... be isolated: strive for not using external systems like databases or services, use a mocking framework instead. Reason: doing not so will make it hard to fulfill some of the other principles listed here, e.g. "fast", "easy to setup", "deterministic" (think about a temporary network problem when connecting a test database).
... run fast: slow tests will decrease your productivity and they will be run fewer times because no one likes waiting
... be included in continuous integration process: don't rely on developers manually triggering of the tests, they should be run automatically (as often as possible).
... be easy to setup: the danger in hard to setup tests is that they are simply not written.
... be either atomic or integration tests: atomic tests (i.e. tests that cover a very specific, small amount of functionality) are a must, integration tests (covering the collaboration of multiple modules) are not always necessary but sometimes useful. The disadvantage in integration test is that in case of failing tests, problems are harder to find whereas a failing atomic unit test often even does not have to get debugged to find the problem. Do not mix both types but make a clear separation (e.g. by introducing naming conventions).
... have one logical assert per test: does not mean you should never have multiple asserts in your test case, but if this is the case make sure the asserts are tightly logically connected to each other.
... concentrate on the public "API" of your SUT (which normally covers private methods. Note that the need of testing private methods is often an indicator for violation of SRP within the class).
... read like documentation for your system: benefit from your test suite also in a way that it is an additional documentation for your software. Actually, a system without unit tests cannot be conidered as being "valid": it might be free from obvious bugs (such as users get error messages), but that does not always mean that it works as it should (and often other documentation - if available at all - is far away from being as precise as unit tests in describing desired behavior).
... have the same code quality as productive code: there is NO reason for neglecting unit test code. It will grow like productive code grows, you will get the same problems as with your productive code if you are not applying the same patterns and practises.
... also cover the "sad" path, not only the "happy" path: also test unexpected values and behavior including tests for exceptions.
... be written each time a bug in development, testing or on your live system is occuring. Like this you make sure that this bug is abandoned forever.
Sunday, January 6, 2013
TFS build process templates vs MSBuild
The introduction of build process templates (implemented with WWF / XAML) with Team Foundation Server 2010 did not mean the end of MSBuild scripts. After all every .csproj or .vbproj project file Visual Studio generates during creation of new projects is a MSBuild script.
WWF build process templates provide a higher level orchestration layer on top of the core build engine MSBuild and has some more sophisticated possibilities that are coming with WWF, e.g. distribute a process across multiple machines and to tie the process into other workflow-based processes.
But still, a lot of steps you want to have within your project specific build (e.g. Stylecop analysis, NDepend static code analysis, script and style bundling and minification) can be realized in both ways. So the question arises which way to go: WWF or MSBuild.
I found an guideline from Jim Lamb (who is a TFS programm manager at Microsoft) how to handle this:
MSBuild is the tool of choice in the following scenarios:
1) the task requires knowledge of specific build inputs or outputs
2) the task is something you need to happen when you build in Visual Studio (so for example you have to decide if you want to have a StyleCop check for every local build or only after check-in)
Jim's recommondation is to use WWF in all other cases.
In my opinion the WWF approach has also it's downsides:
1. While it is quite simple to let an MSBuild script run on a developers machine (e.g. for debugging a build problem) this isn't so simple with the WWF solution (you had to install TFS build service locally).
2. The WWF approach can not be reused when your organization switches from TFS to another ALM platform (e.g. Subversion and TeamCity).
3. You have to know not only how MSBuild works but also have to have a clue at least of the basics of the WWF stuff.
When leveraging MSBuild, keep in mind that from a maintenance and reuse perspective it is better to create additional MSBuild files (can be referenced by "import" statements) rather than writing the additional task directly into the project files (they are already containing enough stuff).
WWF build process templates provide a higher level orchestration layer on top of the core build engine MSBuild and has some more sophisticated possibilities that are coming with WWF, e.g. distribute a process across multiple machines and to tie the process into other workflow-based processes.
But still, a lot of steps you want to have within your project specific build (e.g. Stylecop analysis, NDepend static code analysis, script and style bundling and minification) can be realized in both ways. So the question arises which way to go: WWF or MSBuild.
I found an guideline from Jim Lamb (who is a TFS programm manager at Microsoft) how to handle this:
MSBuild is the tool of choice in the following scenarios:
1) the task requires knowledge of specific build inputs or outputs
2) the task is something you need to happen when you build in Visual Studio (so for example you have to decide if you want to have a StyleCop check for every local build or only after check-in)
Jim's recommondation is to use WWF in all other cases.
In my opinion the WWF approach has also it's downsides:
1. While it is quite simple to let an MSBuild script run on a developers machine (e.g. for debugging a build problem) this isn't so simple with the WWF solution (you had to install TFS build service locally).
2. The WWF approach can not be reused when your organization switches from TFS to another ALM platform (e.g. Subversion and TeamCity).
3. You have to know not only how MSBuild works but also have to have a clue at least of the basics of the WWF stuff.
When leveraging MSBuild, keep in mind that from a maintenance and reuse perspective it is better to create additional MSBuild files (can be referenced by "import" statements) rather than writing the additional task directly into the project files (they are already containing enough stuff).
What happens when you click "Build Solution" in Visual Studio?
You probably know that msbuild.exe is somehow involved when you click "Build Solution" from the "Build" menu within Visual Studio.
But msbuild.exe is not called directly, instead Visual Studio does the same as you would call "devenv.exe /build" from the command prompt. The executable has to be passed the name of the solution together with the desired solution configuration.
devenv.exe is more or less a wrapper that calls msbuild.exe with a set of properties that are visual studio specific.
Note that devenv.exe only comes with an installed Visual Studio, msbuild.exe is (easier) available with the .NET Framework installation.
But msbuild.exe is not called directly, instead Visual Studio does the same as you would call "devenv.exe /build" from the command prompt. The executable has to be passed the name of the solution together with the desired solution configuration.
devenv.exe is more or less a wrapper that calls msbuild.exe with a set of properties that are visual studio specific.
Note that devenv.exe only comes with an installed Visual Studio, msbuild.exe is (easier) available with the .NET Framework installation.
Thursday, November 29, 2012
Control Entity Framework, do not let it control you
In the company I am working they are currently facing really
heavy problems with an application that (miss)uses Entity Framework (EF).
I have not yet worked with EF in my own projects (so take
this post not too serious) but did some hours of investigation how it probably
should be used in a "real world" application (I mean a mid-sized or
even big data centric business application in contrast to the "hello
world" style tutorials you usually see in the internet where DbContexts are
within controller actions).
First of all, what are the main features / benefits that
ship with EF:
- Build-in mapping functionality and relationship management (foreign keys)
- Automatic generation of CRUD SQL statements
- No need to define SQL parameters manually (increased security due to reduced risk of SQL injections)
- Automatic data migrations (managed by Nuget Package Manager) can replace non-integrated data migrations
- Data access layer validation (data annotations)
- Concurrency handling (with timestamps)
- Support of all major RDBMS
- Quick (re-)generation of databases (possible use case: "quickly" creating testing databases within nightly builds)
- Precompilation of queries (execution plans), but only from Version 5 on
In enterprise scenarios, you are usually dealing with
existing databases. Here the question comes up how you would apply EF to an
existing database.
There are two possibilites: if you prefer working with Code
instead of designer tools (my guess is that most developers do) you would use
reverse engineer tools (e.g. EF powertools) to define code classes and mappings
for your existing database. Alternative to this code centric way is the
designer centric way ("database first") where you would reverse
engineer an .edmx model (classes and mappings are auto-generated from .edmx).
Now, what should be taken into consideration when working
with EF (most of the hints are from a TechEd 2012 session by Adam Tuliper) ?
- DBContext is not thread safe, instantiate a new one per request (best via DI)
- Do not cache it or use a static instance.
- Dispose DBContext when done (DI does that automatically for you)
- Utilize repository pattern, make EF your repository implementation
- No EF code anywhere else than in your repository implementation (e.g. not as view models) - no references to EF from other layers than data access
- Return data grabbed data with .ToArray() / .ToList(). Reason: EF uses deferred execution and you usually want to have control over when a database query is being performed (note that deferred execution outside the DBContext scope will lead to "DBContext already disposed" errors). By calling .ToArray() or .ToList() you are forcing an immediate execution.
- Always check EF generated Sql statements (e.g. MiniProfiler is a convenient possibility) - replace them by telling EF to use custom stored procedures in non trivial scenarios
- Performance was improved in Version 5 (see above), but be aware that EF is still slower compared to „raw“ ADO.NET access (SqlDataReader etc). Consider using a more lightweight ORM (e.g. dapper) if winning some milliseconds per query is crucial for your application.
- Keep controlling the loading process, avoid lazy loading when it is not necessary
- EF does have out-of –the-box support for “nolock”, you have to use Transactions with READ UNCOMMITTED (or call stored procedures)
Let me know if you think that other things are also
important when using EF beyond “hello, world”. Btw: most of the mentioned
points are not only applying to EF but to every ORM.
Subscribe to:
Posts (Atom)





