{"title":"Programmatically Speaking","link":[{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/","rel":"alternate"}},{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/feeds\/all.atom.xml","rel":"self"}}],"id":"https:\/\/programmaticallyspeaking.com\/","updated":"2025-07-16T23:30:00+02:00","entry":[{"title":"A TDD Mindset","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/a-tdd-mindset.html","rel":"alternate"}},"published":"2025-07-16T23:30:00+02:00","updated":"2025-07-16T23:30:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2025-07-16:\/a-tdd-mindset.html","summary":"<p>In the beginning of my career, I discovered that having automated tests is invaluable when making changes to any non-trivial software system. Or, put differently, I realized that changing a non-trivial software system without having the support of a suite of automated tests is both risky and time consuming.<\/p>","content":"<p>In the beginning of my career, I discovered that having automated tests is invaluable when making changes to any non-trivial software system.\nOr, put differently, I realized that changing a non-trivial software system without having the support of a suite of automated tests is both risky and time consuming.<\/p>\n<p>I also discovered that TDD (Test-Driven Development) is a really, really good way of writing automated tests.<\/p>\n<p>However, TDD is not primarily about writing tests. It&rsquo;s about encoding some knowledge or requirement as a piece of code that can verify that a system behaves as expected.<sup id=\"fnref:xp\"><a class=\"footnote-ref\" href=\"#fn:xp\">1<\/a><\/sup> <a href=\"https:\/\/dannorth.net\/\">Dan North<\/a> realized a long time ago that the word &ldquo;test&rdquo; is a distraction\n(testing is an activity that you do after coding something, right?), and so he coined <a href=\"https:\/\/en.wikipedia.org\/wiki\/Behavior-driven_development\">Behavior-Driven Development<\/a>.\nSome unit test frameworks avoid the word &ldquo;test&rdquo;&mdash;for example, <a href=\"https:\/\/xunit.net\/\">XUnit<\/a> uses <em>fact<\/em> and <em>theory<\/em>.<\/p>\n<p>Despite this, I tend to use the word &ldquo;test&rdquo; out of habit. Similarly, I refer to what&rsquo;s being tested as &ldquo;unit of test&rdquo; (UT) or &ldquo;system under test&rdquo; (SUT), whether it is a function, class, actor, HTTP API or something else.<\/p>\n<p>When you write a test using TDD, it is the first chance you have to create a client for your UT, and in doing so, to shape it so that it is easy to use in the code base. In other words, TDD acts as a design support tool.\nI have encountered many functions and classes that were incredibly difficult to use in isolation due to convoluted call mechanisms and high coupling, which typically means that they were not test-driven.\nWhen you start with a test, it&rsquo;s unlikely that you deliberately create a <a href=\"https:\/\/en.wikipedia.org\/wiki\/Rube_Goldberg_machine\">Rube Goldberg machine<\/a>.\nI mean, you could, but if you\u2019re in the business of making things hard for yourself, I think there are better ways.<\/p>\n<blockquote>\n<p>An API (and I mean it broadly, not only web API) isn&rsquo;t fully usable until you have written three clients for it.\nI don&rsquo;t know if it was <a href=\"https:\/\/poutsma-principles.com\/blog\/\">Arjen Poutsma<\/a> who first said it, but I first heard it from him (also, I&rsquo;m paraphrasing; I don&rsquo;t recall the exact wording). I consider TDD tests to be the first client.<\/p>\n<\/blockquote>\n<h2>Why TDD?<\/h2>\n<p>To me, TDD is just a tool, albeit an incredibly important one. It is a tool that helps me write high-quality code.\nI use other tools that play important roles in this endeavor as well, such as various input devices, IDEs, type checkers, static analysis tools, and so on&mdash;but TDD is special.\nUnlike some of the other tools, TDD allows me to create a situation where any team member and future maintainer (including future me) can be productive and make changes without being afraid of breaking things.<\/p>\n<p>I think that anyone working with a code base should be able to say the following:<sup id=\"fnref:tdd-team\"><a class=\"footnote-ref\" href=\"#fn:tdd-team\">2<\/a><\/sup><\/p>\n<p><center>\n&ldquo;<i>If I, with good intentions, change some code,<br>\nand all tests on existing functionality are green,<br>\nthen I didn\u2019t break anything.<\/i>&rdquo;\n<\/center><\/p>\n<p>This is an important driving factor for me, and it means that TDD is not only a tool for making me more productive, but also for enabling others to be more productive.<\/p>\n<p>I think that to fully benefit from TDD, it&rsquo;s important to not just view it as a mechanical activity, and definitely not as an activity for writing tests, but instead to adopt a <em>TDD mindset<\/em>.<\/p>\n<h2>What&rsquo;s in a mindset?<\/h2>\n<p>When I say TDD mindset, this is what I mean:<\/p>\n<p><strong>View a test as representing a <em>requirement<\/em> or a <em>desired outcome<\/em>, rather than something that cements a particular implementation.<\/strong><\/p>\n<p>A common problem with writing tests <em>after<\/em> the production code is that the tests become tightly coupled to the implementation, resulting in a brittle test suite.\nWith a TDD mindset, you end up with behavior-oriented, flexible tests that allow implementation details to change.<\/p>\n<p>Many years ago, I worked on a project where a team member was tasked with implementing some requested changes to domain logic.\nAs they did that, a number of existing test started to fail. Instead of viewing those tests as requirements that were now violated,\nthey updated the failing tests to match the new changes. A while later, we received a bug report on broken behavior.\nWith a TDD mindset, you recognize that tests are requirements, and investigate why they fail. In this situation, the requested changes were actually incompatible with the original requirements.<\/p>\n<p><strong>Accept the initial investment and focus on the long-term perspective.<\/strong><\/p>\n<p>The first test is always the hardest to write. Even if you&rsquo;re test-driving new code in an empty code base,\nyou probably need to set up test infrastructure and test data. However, the investment <a href=\"\/return-on-investment-for-test-driven-development.html\">quickly pays off<\/a>.<\/p>\n<p>If you use TDD to write code in an existing code base with limited testability, it&rsquo;s likely that you will have to spend a lot\nof time paving the way for the first test. However, the return on investment will be equally great, as you take the first steps\ntowards making it possible to change the code with confidence.<\/p>\n<p>Having a TDD mindset means ensuring that a code base stays healthy and can be maintained over a long period of time.\nThis goal outweighs any short-term wins that may result from skipping TDD <em>right now<\/em>\n(though personally, I&rsquo;m faster <em>with<\/em> TDD than without, so it&rsquo;s always a win for me).<\/p>\n<p><strong>Decouple code to increase testability.<\/strong><\/p>\n<p>As noted, TDD is a design support tool. Using TDD inevitably leads to a decoupled, testable design.\nBut sometimes, you&rsquo;re in a situation where it&rsquo;s next to impossible to write a test, let alone use TDD.\nTypically, this happens if you use a platform or third-party software that is not built with testability in mind.\nThe technology becomes an obstacle.<\/p>\n<p>I once tried to write tests for an old PowerBuilder application, but realized quickly that I was in over my head.\nThe PowerBuilder version in question did not provide any mechanism whatsoever for writing tests.\nThus, encouraging the developers to use TDD was simply not an option.<\/p>\n<p>Having a TDD mindset means not giving up. Instead, create and maintain a clear separation between code that is tied to the platform\/technology and code that is free from unwanted dependencies.\nThe latter can be domain model code, view model code, or pure functions, for example. This way, the amount of untestable (or at least hard-to-test) code can be kept to a minimum. If your existing code base is tightly coupled to a specific\nplatform, drain it one piece at a time to move to a situation where you can test-drive future changes.<\/p>\n<p><strong>Make sure the tool is as useful as possible.<\/strong><\/p>\n<p>TDD is a tool, and any tool should be used in a way that maximizes its usefulness.\nWith TDD, this includes a number of practices such as naming tests in a good way, ensuring that tests fail for the correct reason, and making sure that running tests is really fast.<\/p>\n<p>When embracing a TDD mindset, a whole bunch of common questions become irrelevant: Should I write tests for this function? How high test coverage should we have? Is it safe to make this change or will something break?<\/p>\n<p>Thus, using TDD should make things easier. It should be something helpful, not an obstacle.<\/p>\n<p>If it doesn&rsquo;t make things easier, consider what needs to change. Do you need better test helpers? A faster test runner? Should you test-drive on a different abstraction level? I have worked with TDD for about 20 years, and I still try to find ways to improve how I work and how TDD can help me write higher-quality code.<\/p>\n<h2>Prototyping<\/h2>\n<p>Should prototypes be test-driven? No, I think that would defeat their purpose. A prototype is a mechanism for experimentation, discovery and learning.\nMaybe you need to write integration code, but you&rsquo;re not sure how the other party behaves, so you need to write some code to find out.\nMaybe you should build a UI component, but you need to compare a few alternatives before deciding what is best for the end user.<\/p>\n<p>That said, sometimes it is possible and helpful to write a very high-level tests to use as a guide for the prototyping activity. With my TDD mindset, I do that if I have an opportunity.<\/p>\n<p>When you&rsquo;re done, you can throw away the prototype and start test-driving real production code. Or you can comment out the prototype and <a href=\"\/tdd-and-prototyping-a-love-story.html\">test-drive its inclusion<\/a>, though that has its risk and is more a test-first activity than real TDD. But let&rsquo;s not split hairs&hellip;<\/p>\n<h2>Just use AI instead!?<\/h2>\n<p>Does TDD play a role in a future where we use generative AI to assist software development? Yes, I think so very much!<\/p>\n<p>Consider the following factors:<\/p>\n<ul>\n<li>TDD is primarily about formulating requirements and desired behavior.<\/li>\n<li>LLMs often produce plausible-looking but incorrect code, too verbose code and code that isn&rsquo;t strictly necessary.<\/li>\n<li>LLMs sometimes get derailed and lose track of the task at hand.<sup id=\"fnref:multi-turn\"><a class=\"footnote-ref\" href=\"#fn:multi-turn\">3<\/a><\/sup><\/li>\n<\/ul>\n<p>Even though careful prompting, chain-of-thought, and multi-agent systems can improve the performance of an AI coding assistant,\nhaving expressed requirements using TDD is an excellent way of ensuring that the end result becomes what you intended, and that the code remains maintainable over time. Additionally, requirements-as-tests provide useful context to\nan LLM.<\/p>\n<p>Should you let the AI coding assistant write tests? It is certainly able to (though any quality qualms you may have over production code applies to generated tests as well), but is it a good idea? It depends on how you approach the task.\nIf you really try, you can make an <a href=\"https:\/\/nizar.se\/agentic-tdd\/\">AI assistant use TDD<\/a>, but you need to make sure that the tests actually correspond to your requirements rather than what the LLM thinks is most probable.\nUsing TDD is a good way of discovering what the next logical step is, and though there is research on how to use generative AI for requirements engineering,<sup id=\"fnref:ai-re\"><a class=\"footnote-ref\" href=\"#fn:ai-re\">4<\/a><\/sup> an LLM won&rsquo;t always be able to predict what you don&rsquo;t know yet.<\/p>\n<h2>Summary<\/h2>\n<p>Having a TDD mindset means to use tests as requirements for writing correct and maintainable code (rather than seeing it as a test-writing activity),\nto accept that the initial cost may be high but consider the long-term effects (rather than having just the short-term perspective),\nto decouple code to be able to test-drive as much as possible (rather than blaming a platform\/framework\/technology for preventing the use of TDD),\nand to see TDD as a tool that should be useful and helpful and strive to make it even more so (rather than accepting friction).<\/p>\n<div class=\"footnote\">\n<hr \/>\n<ol>\n<li id=\"fn:xp\">\n<p>See chapter 18 in: Beck, Kent. Extreme Programming Explained: Embrace Change. 1st edition, Addison-Wesley, 1999.&#160;<a class=\"footnote-backref\" href=\"#fnref:xp\" title=\"Jump back to footnote 1 in the text\">&#8617;<\/a><\/p>\n<\/li>\n<li id=\"fn:tdd-team\">\n<p>From my <a href=\"https:\/\/www.youtube.com\/watch?v=LTJmwmRpe2M\">Swetugg presentation<\/a>, &ldquo;The T in TDD stands for&hellip; Team?&rdquo;&#160;<a class=\"footnote-backref\" href=\"#fnref:tdd-team\" title=\"Jump back to footnote 2 in the text\">&#8617;<\/a><\/p>\n<\/li>\n<li id=\"fn:multi-turn\">\n<p>Laban, P., Hayashi, H., Zhou, Y., Neville, J. LLMs Get Lost In Multi-Turn Conversation. Preprint. <a href=\"https:\/\/arxiv.org\/pdf\/2505.06120\">arXiv<\/a>, fetched 2025-07-16.&#160;<a class=\"footnote-backref\" href=\"#fnref:multi-turn\" title=\"Jump back to footnote 3 in the text\">&#8617;<\/a><\/p>\n<\/li>\n<li id=\"fn:ai-re\">\n<p>AI for Requirements Engineering (AI4RE). <a href=\"https:\/\/www.oru.se\/english\/research\/research-projects\/rp\/?rdb=p2791\">\u00d6rebro University<\/a>, fetched 2025-07-16.&#160;<a class=\"footnote-backref\" href=\"#fnref:ai-re\" title=\"Jump back to footnote 4 in the text\">&#8617;<\/a><\/p>\n<\/li>\n<\/ol>\n<\/div>","category":[{"@attributes":{"term":"Methodology"}},{"@attributes":{"term":"test"}},{"@attributes":{"term":"tdd"}},{"@attributes":{"term":"requirements"}}]},{"title":"Don't write code, generate it!","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/dont-write-code-generate-it.html","rel":"alternate"}},"published":"2024-09-06T16:30:00+02:00","updated":"2024-09-06T16:30:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2024-09-06:\/dont-write-code-generate-it.html","summary":"<p>A while back, I got fed up with writing code. Not writing code in general, mind you, but I did face a situation\nwhere I needed to write a lot of <a href=\"https:\/\/en.wikipedia.org\/wiki\/Boilerplate_code\">boilerplate code<\/a>,\nand having to write such code is a certain way of losing interest in software development. Not \u2026<\/p>","content":"<p>A while back, I got fed up with writing code. Not writing code in general, mind you, but I did face a situation\nwhere I needed to write a lot of <a href=\"https:\/\/en.wikipedia.org\/wiki\/Boilerplate_code\">boilerplate code<\/a>,\nand having to write such code is a certain way of losing interest in software development. Not only\nis it tedious - repetitive code tends to be error-prone, requires a lot of equally repetitive tests,\nand thus usually ends up being quite a large maintenance burden.<\/p>\n<p>This was a C# project, and after contemplating the task for a while, I realized that this was a good opportunity\nfor creating a\n<a href=\"https:\/\/learn.microsoft.com\/en-us\/dotnet\/csharp\/roslyn-sdk\/source-generators-overview\">source generator<\/a>.\nA source generator runs during compilation and emits code that becomes part of the compilation.\nExactly what I needed!<\/p>\n<p>This post documents the steps I went through to build a source generator, with extra focus on different ways of\nwriting automated tests for the generator. Since I&rsquo;m a strong proponent of using Test-Driven Development (TDD),\nthe ability to write automated tests is crucial to me, and luckily there are many options on the table for\nthat.<\/p>\n<blockquote>\n<p>Side note: One situation where writing automated tests is difficult, is when you have to interface with\na framework or library that was not written with testability in mind. I&rsquo;m happy that Microsoft thought about this aspect!<\/p>\n<\/blockquote>\n<p>It should be noted that this post is not a comprehensive guide to writing source generators. There are plenty of good guides\nand documentation available online. Also, the post is not a TDD post, but as a TDD aficionado, I really\ncan&rsquo;t help but approach it from that angle, as you&rsquo;ll see.<\/p>\n<p>The code examples use modern C# (12.0) and .NET 8, so if you&rsquo;re stuck on older versions, you have to adjust\naccordingly.<\/p>\n<p>A more complete version of the code in the post is available in <a href=\"https:\/\/github.com\/provegard\/source-generator-lab\">this GitHub repository<\/a>.<\/p>\n<h1>Use case<\/h1>\n<p>To have a use case to work with, consider a class that defines color models:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">ColorModels<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span><span class=\"p\">[]<\/span><span class=\"w\"> <\/span><span class=\"n\">RGB<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"s\">&quot;red&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;green&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;blue&quot;<\/span><span class=\"p\">];<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span><span class=\"p\">[]<\/span><span class=\"w\"> <\/span><span class=\"n\">CMYK<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"s\">&quot;cyan&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;magenta&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;yellow&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;black&quot;<\/span><span class=\"p\">];<\/span><span class=\"w\"> <\/span><span class=\"c1\">\/\/ k is for &quot;key&quot;, which is black<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Based on a color model, we want to generate a wrapper class that allows us to extract values from a dictionary\nthat may or may not contain values for the components of the model:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"nf\">RGBAccessor<\/span><span class=\"p\">(<\/span><span class=\"n\">IDictionary<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">string<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"kt\">double<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">values<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"kt\">double?<\/span><span class=\"w\"> <\/span><span class=\"n\">Red<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">values<\/span><span class=\"p\">.<\/span><span class=\"n\">TryGetValue<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;red&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"k\">out<\/span><span class=\"w\"> <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"k\">value<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">?<\/span><span class=\"w\"> <\/span><span class=\"k\">value<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"k\">null<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"kt\">double?<\/span><span class=\"w\"> <\/span><span class=\"n\">Green<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">values<\/span><span class=\"p\">.<\/span><span class=\"n\">TryGetValue<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;green&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"k\">out<\/span><span class=\"w\"> <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"k\">value<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">?<\/span><span class=\"w\"> <\/span><span class=\"k\">value<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"k\">null<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"kt\">double?<\/span><span class=\"w\"> <\/span><span class=\"n\">Blue<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">values<\/span><span class=\"p\">.<\/span><span class=\"n\">TryGetValue<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;blue&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"k\">out<\/span><span class=\"w\"> <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"k\">value<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">?<\/span><span class=\"w\"> <\/span><span class=\"k\">value<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"k\">null<\/span><span class=\"p\">;<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>This particular piece of code isn&rsquo;t too bad to write (though tests are omitted here),\nbut as the number of color models and color components grow,\nmore similar code has to be written, and if a color model changes, the corresponding accessor must be\nkept in sync.<\/p>\n<h1>Project setup<\/h1>\n<p>We start by creating a solution and the relevant projects - one class library project to house the source generator,\nand one unit test project. It&rsquo;s important that the project for the source generator targets <code>netstandard2.0<\/code>.\nThe resulting structure looks like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>\\ source-generator-lab\/\n  |- source-generator-lab.sln\n  |- generator\/\n  |  \\ generator.csproj\n  \\- generator.tests\/\n     \\ generator.tests.csproj\n<\/code><\/pre><\/div>\n\n<p>The examples use NUnit as test library, but that&rsquo;s not important. Any modern test\/assertion framework\nshould do.<\/p>\n<p>Once the solution structure is in place, we modify the project file of the <code>generator<\/code> project so that the\nprimary property group contains the following:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nt\">&lt;PropertyGroup&gt;<\/span>\n<span class=\"w\">    <\/span><span class=\"nt\">&lt;TargetFramework&gt;<\/span>netstandard2.0<span class=\"nt\">&lt;\/TargetFramework&gt;<\/span>\n<span class=\"w\">    <\/span><span class=\"cm\">&lt;!-- Change the language version as needed. --&gt;<\/span>\n<span class=\"w\">    <\/span><span class=\"nt\">&lt;LangVersion&gt;<\/span>12.0<span class=\"nt\">&lt;\/LangVersion&gt;<\/span>\n<span class=\"w\">    <\/span><span class=\"nt\">&lt;ImplicitUsings&gt;<\/span>enable<span class=\"nt\">&lt;\/ImplicitUsings&gt;<\/span>\n<span class=\"w\">    <\/span><span class=\"nt\">&lt;Nullable&gt;<\/span>enable<span class=\"nt\">&lt;\/Nullable&gt;<\/span>\n<span class=\"w\">    <\/span><span class=\"nt\">&lt;EnforceExtendedAnalyzerRules&gt;<\/span>true<span class=\"nt\">&lt;\/EnforceExtendedAnalyzerRules&gt;<\/span>\n<span class=\"w\">    <\/span><span class=\"nt\">&lt;IsRoslynComponent&gt;<\/span>true<span class=\"nt\">&lt;\/IsRoslynComponent&gt;<\/span>\n<span class=\"nt\">&lt;\/PropertyGroup&gt;<\/span>\n<\/code><\/pre><\/div>\n\n<p>The <code>IsRoslynComponent<\/code> setting is necessary for debugging to work in Visual Studio (<a href=\"https:\/\/www.jetbrains.com\/rider\/\">Rider<\/a> doesn&rsquo;t care).<\/p>\n<p>The <code>EnforceExtendedAnalyzerRules<\/code> setting prevents us from using certain \n<a href=\"https:\/\/github.com\/dotnet\/roslyn-analyzers\/blob\/main\/src\/Microsoft.CodeAnalysis.Analyzers\/Core\/AnalyzerBannedSymbols.txt\">banned APIs<\/a>\nin the source generator.<\/p>\n<p>We also need to add references to some NuGet packages:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nt\">&lt;ItemGroup&gt;<\/span>\n<span class=\"w\">    <\/span><span class=\"nt\">&lt;PackageReference<\/span><span class=\"w\"> <\/span><span class=\"na\">Include=<\/span><span class=\"s\">&quot;Microsoft.CodeAnalysis.Analyzers&quot;<\/span><span class=\"w\"> <\/span><span class=\"na\">Version=<\/span><span class=\"s\">&quot;3.3.4&quot;<\/span><span class=\"w\"> <\/span><span class=\"na\">PrivateAssets=<\/span><span class=\"s\">&quot;all&quot;<\/span><span class=\"w\"> <\/span><span class=\"nt\">\/&gt;<\/span>\n<span class=\"w\">    <\/span><span class=\"nt\">&lt;PackageReference<\/span><span class=\"w\"> <\/span><span class=\"na\">Include=<\/span><span class=\"s\">&quot;Microsoft.CodeAnalysis.CSharp&quot;<\/span><span class=\"w\"> <\/span><span class=\"na\">Version=<\/span><span class=\"s\">&quot;4.9.2&quot;<\/span><span class=\"w\"> <\/span><span class=\"nt\">\/&gt;<\/span>\n<span class=\"nt\">&lt;\/ItemGroup&gt;<\/span>\n<\/code><\/pre><\/div>\n\n<p>There may be newer versions of course; these are the latest versions at the time of writing this post.<\/p>\n<p>Next, we edit the project file of the <code>generator.tests<\/code> project to add an item group\nwith a reference to <code>generator<\/code> that looks like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nt\">&lt;ItemGroup&gt;<\/span>\n<span class=\"w\">    <\/span><span class=\"nt\">&lt;ProjectReference<\/span><span class=\"w\"> <\/span><span class=\"na\">Include=<\/span><span class=\"s\">&quot;..\\generator\\generator.csproj&quot;<\/span>\n<span class=\"w\">        <\/span><span class=\"na\">OutputItemType=<\/span><span class=\"s\">&quot;Analyzer&quot;<\/span>\n<span class=\"w\">        <\/span><span class=\"na\">ReferenceOutputAssembly=<\/span><span class=\"s\">&quot;true&quot;<\/span>\n<span class=\"w\">    <\/span><span class=\"nt\">\/&gt;<\/span>\n<span class=\"nt\">&lt;\/ItemGroup&gt;<\/span>\n<\/code><\/pre><\/div>\n\n<p>The value of <code>ReferenceOutputAssembly<\/code> determines if the project should be a runtime reference or not.\nThere are two cases when having the generator assembly as a runtime reference is useful:<\/p>\n<ol>\n<li>When you&rsquo;re writing tests for the generator.<\/li>\n<li>When the generated code contains references to types defined in the generator assembly.<\/li>\n<\/ol>\n<p>If both cases apply, I recommend making the generator class <code>internal<\/code> and using <code>InternalsVisibleTo<\/code> to make it\navailable to the test project.<\/p>\n<p>Furthermore, we modify the primary <code>PropertyGroup<\/code> of <code>generator.tests<\/code> so that it contains:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nt\">&lt;EmitCompilerGeneratedFiles&gt;<\/span>true<span class=\"nt\">&lt;\/EmitCompilerGeneratedFiles&gt;<\/span>\n<\/code><\/pre><\/div>\n\n<p>This causes generated sources to be written into a subfolder of <code>generated.tests\/obj<\/code>, which is helpful for\ntroubleshooting. The <code>obj<\/code> folder is normally excluded from source control. If you for some reason want to add\nthe generated source to source control, take a look at the <code>CompilerGeneratedFilesOutputPath<\/code> setting.<\/p>\n<p>In the <code>generator.tests<\/code> project, we add a file named <code>GlobalUsings.cs<\/code> that contains (modify accordingly\nif you don&rsquo;t use NUnit):<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">global<\/span><span class=\"w\"> <\/span><span class=\"k\">using<\/span><span class=\"w\"> <\/span><span class=\"nn\">System.Reflection<\/span><span class=\"p\">;<\/span>\n<span class=\"n\">global<\/span><span class=\"w\"> <\/span><span class=\"k\">using<\/span><span class=\"w\"> <\/span><span class=\"nn\">System.Text<\/span><span class=\"p\">;<\/span>\n<span class=\"n\">global<\/span><span class=\"w\"> <\/span><span class=\"k\">using<\/span><span class=\"w\"> <\/span><span class=\"nn\">Microsoft.CodeAnalysis<\/span><span class=\"p\">;<\/span>\n<span class=\"n\">global<\/span><span class=\"w\"> <\/span><span class=\"k\">using<\/span><span class=\"w\"> <\/span><span class=\"nn\">Microsoft.CodeAnalysis.CSharp<\/span><span class=\"p\">;<\/span>\n<span class=\"n\">global<\/span><span class=\"w\"> <\/span><span class=\"k\">using<\/span><span class=\"w\"> <\/span><span class=\"nn\">Microsoft.CodeAnalysis.Text<\/span><span class=\"p\">;<\/span>\n<span class=\"n\">global<\/span><span class=\"w\"> <\/span><span class=\"k\">using<\/span><span class=\"w\"> <\/span><span class=\"nn\">NUnit.Framework<\/span><span class=\"p\">;<\/span>\n<span class=\"n\">global<\/span><span class=\"w\"> <\/span><span class=\"k\">using<\/span><span class=\"w\"> <\/span><span class=\"nn\">generator<\/span><span class=\"p\">;<\/span>\n<\/code><\/pre><\/div>\n\n<p>This way, we don&rsquo;t have to repeat those usings in individual test files.<\/p>\n<h1>Generator class (scaffolding)<\/h1>\n<p>In the <code>generator<\/code> project, we add an attribute class that will be a <em>marker<\/em> attribute that triggers\nsource generation:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">namespace<\/span><span class=\"w\"> <\/span><span class=\"nn\">generator<\/span><span class=\"p\">;<\/span>\n\n<span class=\"na\">[AttributeUsage(AttributeTargets.Class)]<\/span>\n<span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">ColorModelsAttribute<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">Attribute<\/span><span class=\"p\">;<\/span>\n<\/code><\/pre><\/div>\n\n<p>There is another option for providing the marker attribute - it can be generated using\n<code>context.RegisterPostInitializationOutput<\/code>. If you prefer that approach, the generator assembly\ndoes not have to be a runtime dependency.<\/p>\n<p>Next, we add the actual source generator class, <code>ColorModelGenerator<\/code>.\nWe add the <code>[Generator]<\/code> attribute and let it implement the <code>IIncrementalGenerator<\/code> interface:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">using<\/span><span class=\"w\"> <\/span><span class=\"nn\">System.Text<\/span><span class=\"p\">;<\/span>\n<span class=\"k\">using<\/span><span class=\"w\"> <\/span><span class=\"nn\">Microsoft.CodeAnalysis<\/span><span class=\"p\">;<\/span>\n<span class=\"k\">using<\/span><span class=\"w\"> <\/span><span class=\"nn\">Microsoft.CodeAnalysis.CSharp.Syntax<\/span><span class=\"p\">;<\/span>\n<span class=\"k\">using<\/span><span class=\"w\"> <\/span><span class=\"nn\">Microsoft.CodeAnalysis.Text<\/span><span class=\"p\">;<\/span>\n\n<span class=\"k\">namespace<\/span><span class=\"w\"> <\/span><span class=\"nn\">generator<\/span><span class=\"p\">;<\/span>\n\n<span class=\"na\">[Generator]<\/span>\n<span class=\"k\">internal<\/span><span class=\"w\"> <\/span><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">ColorModelGenerator<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">IIncrementalGenerator<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">Initialize<\/span><span class=\"p\">(<\/span><span class=\"n\">IncrementalGeneratorInitializationContext<\/span><span class=\"w\"> <\/span><span class=\"n\">context<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>The <code>IIncrementalGenerator<\/code> interface is a modern API for defining a source generator.\nIt&rsquo;s also possible to use the <code>ISourceGenerator<\/code> interface, which requires a slightly different\ngenerator implementation.<\/p>\n<p>Since the generator assembly contains the marker attribute, it needs to be a runtime reference as well.\nAs noted before, it&rsquo;s a good idea to make the generator class internal in this case, so we do that.<\/p>\n<p>Finally, we add a file named <code>InternalsVisibleTo.cs<\/code> with the following contents, so that unit\ntests can reference the generator class directly despite its <code>internal<\/code> visibility.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">using<\/span><span class=\"w\"> <\/span><span class=\"nn\">System.Runtime.CompilerServices<\/span><span class=\"p\">;<\/span>\n<span class=\"na\">[assembly: InternalsVisibleTo(&quot;generator.tests&quot;)]<\/span>\n<\/code><\/pre><\/div>\n\n<p>In Visual Studio, if you expand <em>Dependencies\/Analyzers<\/em> for <code>generator.tests<\/code>, you should see a reference\nto <code>generator<\/code>. In Rider, look in <em>Dependencies\/.NET 8.0\/Analyzers<\/em>.<\/p>\n<h1>Writing tests<\/h1>\n<p>There are at least two different ways of writing tests for a source generator:<\/p>\n<ol>\n<li>Write high-level tests that verify the presence and\/or behavior of the final generated code elements.<\/li>\n<li>Write unit tests that verify the raw output of the source generator.<\/li>\n<\/ol>\n<p>Pros of the first way are:<\/p>\n<ul>\n<li>It&rsquo;s possible to test the behavior of the generated code elements.<\/li>\n<li>The tests become less sensitive to changes in the generator output.<\/li>\n<\/ul>\n<p>Pros of the second way are:<\/p>\n<ul>\n<li>It&rsquo;s possible to test diagnostics (e.g., errors) emitted by the source generator.<\/li>\n<li>It&rsquo;s easier to verify exactly what code is generated.<\/li>\n<li>It&rsquo;s easier to debug the source generator from the tests.<\/li>\n<\/ul>\n<h2>1. Test the generated code elements<\/h2>\n<p>To try the first way, we add a new class named <code>ColorModelGeneratorWay1Test<\/code> to the test project.\n(Normally, I don&rsquo;t use numbers in test fixture names or test names, but this is way 1, after all.)<\/p>\n<p>We modify <code>ColorModelGeneratorWay1Test<\/code> as follows (if you use a different test framework, adjust as necessary):<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"na\">[TestFixture]<\/span>\n<span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">ColorModelGeneratorWay1Test<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"na\">[Test]<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">Should_generate_an_accessor_for_a_color_model<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">type<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Type<\/span><span class=\"p\">.<\/span><span class=\"n\">GetType<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;colormodels.EmptyColorModelAccessor&quot;<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">Assert<\/span><span class=\"p\">.<\/span><span class=\"n\">That<\/span><span class=\"p\">(<\/span><span class=\"n\">type<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Is<\/span><span class=\"p\">.<\/span><span class=\"n\">Not<\/span><span class=\"p\">.<\/span><span class=\"n\">Null<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">    <\/span><span class=\"na\">[ColorModels]<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">TestColorModels<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span><span class=\"p\">[]<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"p\">[];<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>This test will fail since there is no <code>EmptyColorModelAccessor<\/code> class generated for the\n<code>Empty<\/code> color model yet. However, it will compile and run, since we use <code>Type.GetType<\/code> rather than\naccessing the class statically. As we test-drive further, we can at some point start using the \nclass directly.<\/p>\n<blockquote>\n<p>There&rsquo;s a philosophical aspect to this. It can be argued that not being able to compile is also\na variant of the Red step in Red-Green-Refactor. Whatever works for you is good, I think!<\/p>\n<\/blockquote>\n<p>Note that the test assumes that the generated accessor class\nends up in a <code>colormodels<\/code> namespace. Furthermore, the test assumes that the generator will\nrecognize the <code>TestColorModels<\/code> class based on the <code>[ColorModels]<\/code> marker attribute and use its field.\nThe recommended approach is to trigger source\ngeneration based on an attribute, and there is an optimized mechanism for that that we&rsquo;ll use (see\n<a href=\"https:\/\/github.com\/dotnet\/roslyn\/blob\/main\/docs\/features\/incremental-generators.md#forattributewithmetadataname-fawmn\">this section<\/a>\nin the incremental generators documentation).<\/p>\n<blockquote>\n<p>It seems that msbuild caches generated code quite aggressively. This is problematic when working\nwith tests of this kind, since they may run against old generated code. In Rider, it&rsquo;s sufficient\nto rebuild the test project to refresh the generated code.<\/p>\n<\/blockquote>\n<h2>2. Test the output of the source generator<\/h2>\n<p>To be able to try the second way, it&rsquo;s beneficial to create a <em>verifier<\/em> helper.\nI found <code>Microsoft.CodeAnalysis.CSharp.SourceGenerators.Testing.NUnit<\/code>\nvia the <a href=\"https:\/\/github.com\/dotnet\/roslyn\/blob\/main\/docs\/features\/source-generators.cookbook.md#unit-testing-of-generators\">source generators cookbook<\/a>,\nbut sadly it depends indirectly on a version of <code>Microsoft.CodeAnalysis.Common<\/code> that is too old.\nLuckily, it&rsquo;s easy for us to roll our own verifier.<\/p>\n<p>We start by defining a base class for the verifier:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">using<\/span><span class=\"w\"> <\/span><span class=\"nn\">System.Collections.Immutable<\/span><span class=\"p\">;<\/span>\n\n<span class=\"k\">namespace<\/span><span class=\"w\"> <\/span><span class=\"nn\">generator.tests<\/span><span class=\"p\">;<\/span>\n\n<span class=\"c1\">\/\/ A verifier helper base class that is generic on a generator type (that has a default constructor).<\/span>\n<span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">abstract<\/span><span class=\"w\"> <\/span><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">VerifierBase<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">TGenerator<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"k\">where<\/span><span class=\"w\"> <\/span><span class=\"n\">TGenerator<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">IIncrementalGenerator<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ References to assemblies needed for the compilation.<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ Adjust the System.Runtime version as needed.<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">private<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"k\">readonly<\/span><span class=\"w\"> <\/span><span class=\"n\">MetadataReference<\/span><span class=\"w\"> <\/span><span class=\"n\">SystemRuntimeReference<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">MetadataReference<\/span><span class=\"p\">.<\/span><span class=\"n\">CreateFromFile<\/span><span class=\"p\">(<\/span><span class=\"n\">Assembly<\/span><span class=\"p\">.<\/span><span class=\"n\">Load<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;System.Runtime, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a&quot;<\/span><span class=\"p\">).<\/span><span class=\"n\">Location<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">private<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"k\">readonly<\/span><span class=\"w\"> <\/span><span class=\"n\">MetadataReference<\/span><span class=\"w\"> <\/span><span class=\"n\">NetStandard<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">MetadataReference<\/span><span class=\"p\">.<\/span><span class=\"n\">CreateFromFile<\/span><span class=\"p\">(<\/span><span class=\"n\">Assembly<\/span><span class=\"p\">.<\/span><span class=\"n\">Load<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51&quot;<\/span><span class=\"p\">).<\/span><span class=\"n\">Location<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">private<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"k\">readonly<\/span><span class=\"w\"> <\/span><span class=\"n\">MetadataReference<\/span><span class=\"w\"> <\/span><span class=\"n\">SystemPrivateCoreLib<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">MetadataReference<\/span><span class=\"p\">.<\/span><span class=\"n\">CreateFromFile<\/span><span class=\"p\">(<\/span><span class=\"k\">typeof<\/span><span class=\"p\">(<\/span><span class=\"n\">Binder<\/span><span class=\"p\">).<\/span><span class=\"n\">GetTypeInfo<\/span><span class=\"p\">().<\/span><span class=\"n\">Assembly<\/span><span class=\"p\">.<\/span><span class=\"n\">Location<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">private<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"k\">readonly<\/span><span class=\"w\"> <\/span><span class=\"n\">MetadataReference<\/span><span class=\"w\"> <\/span><span class=\"n\">Generator<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">MetadataReference<\/span><span class=\"p\">.<\/span><span class=\"n\">CreateFromFile<\/span><span class=\"p\">(<\/span><span class=\"k\">typeof<\/span><span class=\"p\">(<\/span><span class=\"n\">TGenerator<\/span><span class=\"p\">).<\/span><span class=\"n\">GetTypeInfo<\/span><span class=\"p\">().<\/span><span class=\"n\">Assembly<\/span><span class=\"p\">.<\/span><span class=\"n\">Location<\/span><span class=\"p\">);<\/span>\n\n<span class=\"w\">    <\/span><span class=\"k\">private<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"n\">Compilation<\/span><span class=\"w\"> <\/span><span class=\"nf\">CreateCompilation<\/span><span class=\"p\">(<\/span><span class=\"kt\">string<\/span><span class=\"w\"> <\/span><span class=\"n\">source<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">CSharpCompilation<\/span><span class=\"p\">.<\/span><span class=\"n\">Create<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;compilation&quot;<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">            <\/span><span class=\"na\">[CSharpSyntaxTree.ParseText(source)]<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">            <\/span><span class=\"na\">[<\/span>\n<span class=\"na\">                SystemPrivateCoreLib,   \/\/ needed for predefined types like System.Object<\/span>\n<span class=\"na\">                SystemRuntimeReference, \/\/ needed for Attribute<\/span>\n<span class=\"na\">                NetStandard,            \/\/ needed for Attribute<\/span>\n<span class=\"na\">                Generator,              \/\/ needed for ColorModelsAttribute<\/span>\n<span class=\"na\">            ]<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">            <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"nf\">CSharpCompilationOptions<\/span><span class=\"p\">(<\/span><span class=\"n\">OutputKind<\/span><span class=\"p\">.<\/span><span class=\"n\">ConsoleApplication<\/span><span class=\"p\">));<\/span>\n\n<span class=\"w\">    <\/span><span class=\"k\">protected<\/span><span class=\"w\"> <\/span><span class=\"n\">GeneratorDriverRunResult<\/span><span class=\"w\"> <\/span><span class=\"nf\">RunGenerator<\/span><span class=\"p\">(<\/span><span class=\"kt\">string<\/span><span class=\"w\"> <\/span><span class=\"n\">inputCode<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"k\">out<\/span><span class=\"w\"> <\/span><span class=\"n\">Compilation<\/span><span class=\"w\"> <\/span><span class=\"n\">outputCompilation<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"k\">out<\/span><span class=\"w\"> <\/span><span class=\"n\">ImmutableArray<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Diagnostic<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">diagnostics<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Create the input compilation that the generator will act on.<\/span>\n<span class=\"w\">        <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">inputCompilation<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">CreateCompilation<\/span><span class=\"p\">(<\/span><span class=\"n\">inputCode<\/span><span class=\"p\">);<\/span>\n\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Create an instance of the generator.<\/span>\n<span class=\"w\">        <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">generator<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">TGenerator<\/span><span class=\"p\">();<\/span>\n\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Create the driver that will control the generation.<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">GeneratorDriver<\/span><span class=\"w\"> <\/span><span class=\"n\">driver<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">CSharpGeneratorDriver<\/span><span class=\"p\">.<\/span><span class=\"n\">Create<\/span><span class=\"p\">(<\/span><span class=\"n\">generator<\/span><span class=\"p\">);<\/span>\n\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Run the generation pass. The driver is immutable, and all calls return a new driver instance.<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">driver<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">driver<\/span><span class=\"p\">.<\/span><span class=\"n\">RunGeneratorsAndUpdateCompilation<\/span><span class=\"p\">(<\/span><span class=\"n\">inputCompilation<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"k\">out<\/span><span class=\"w\"> <\/span><span class=\"n\">outputCompilation<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">            <\/span><span class=\"k\">out<\/span><span class=\"w\"> <\/span><span class=\"n\">diagnostics<\/span><span class=\"p\">);<\/span>\n\n<span class=\"w\">        <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">driver<\/span><span class=\"p\">.<\/span><span class=\"n\">GetRunResult<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>The base verifier creates metadata references needed for compiling the input code. Most of them are needed\nbecause <code>ColorModels<\/code> attribute is defined in the same assembly as the generator.<\/p>\n<p>We can test the generator output by looking at the generated source code, or by looking at the\ngenerated syntax tree. Let&rsquo;s start with source code.<\/p>\n<h3>2A. Test the generated source code text<\/h3>\n<p>Here&rsquo;s a verifier that can be constructed with input code, expected generated sources,\nand some other settings. It compares the output of the generator line by line.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">namespace<\/span><span class=\"w\"> <\/span><span class=\"nn\">generator.tests<\/span><span class=\"p\">;<\/span>\n\n<span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">TextVerifier<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">TGenerator<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">VerifierBase<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">TGenerator<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"k\">where<\/span><span class=\"w\"> <\/span><span class=\"n\">TGenerator<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">IIncrementalGenerator<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ The input code to run through the generator.<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"n\">required<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span><span class=\"w\"> <\/span><span class=\"n\">InputCode<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"k\">get<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"n\">init<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ The sources we expect to be generated, as a list of tuples. The hint name is<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ typically the filename of a generated source file.<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"nf\">required<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"kt\">string<\/span><span class=\"w\"> <\/span><span class=\"n\">hintName<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span><span class=\"w\"> <\/span><span class=\"n\">expectedCode<\/span><span class=\"p\">)[]<\/span><span class=\"w\"> <\/span><span class=\"n\">ExpectedCode<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"k\">get<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"n\">init<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ Whether to ignore line comments when comparing actual and expected source code.<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"kt\">bool<\/span><span class=\"w\"> <\/span><span class=\"n\">IgnoreLineComments<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"k\">get<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"n\">init<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">true<\/span><span class=\"p\">;<\/span>\n\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ List of error IDs to ignore. CS5001 is &quot;Program does not contain a static &#39;Main&#39; method suitable for an entry point&quot;.<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"n\">IList<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">string<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">IgnoredErrors<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"k\">get<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"n\">init<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"s\">&quot;CS5001&quot;<\/span><span class=\"p\">];<\/span>\n\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ Runs the verifier.    <\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">Run<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Input validation omitted for brevity.<\/span>\n\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Compile the input code.        <\/span>\n<span class=\"w\">        <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">runResult<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">RunGenerator<\/span><span class=\"p\">(<\/span><span class=\"n\">InputCode<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"k\">out<\/span><span class=\"w\"> <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">outputCompilation<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"k\">out<\/span><span class=\"w\"> <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">diagnostics<\/span><span class=\"p\">);<\/span>\n\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ We get diagnostics at this point if there are problems with the input source code. Fail on any<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ non-ignored error.<\/span>\n<span class=\"w\">        <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">errors<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">outputCompilation<\/span><span class=\"p\">.<\/span><span class=\"n\">GetDiagnostics<\/span><span class=\"p\">().<\/span><span class=\"n\">Where<\/span><span class=\"p\">(<\/span><span class=\"n\">d<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">d<\/span><span class=\"p\">.<\/span><span class=\"n\">Severity<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"n\">DiagnosticSeverity<\/span><span class=\"p\">.<\/span><span class=\"n\">Error<\/span><span class=\"w\"> <\/span><span class=\"o\">&amp;&amp;<\/span><span class=\"w\"> <\/span><span class=\"o\">!<\/span><span class=\"n\">IgnoredErrors<\/span><span class=\"p\">.<\/span><span class=\"n\">Contains<\/span><span class=\"p\">(<\/span><span class=\"n\">d<\/span><span class=\"p\">.<\/span><span class=\"n\">Id<\/span><span class=\"p\">)).<\/span><span class=\"n\">ToList<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">Assert<\/span><span class=\"p\">.<\/span><span class=\"n\">That<\/span><span class=\"p\">(<\/span><span class=\"n\">errors<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Is<\/span><span class=\"p\">.<\/span><span class=\"n\">Empty<\/span><span class=\"p\">);<\/span>\n\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ We&#39;ll see a diagnostic at this point if the generator throws an exception,<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ or if the generator emits a diagnostic.<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">Assert<\/span><span class=\"p\">.<\/span><span class=\"n\">That<\/span><span class=\"p\">(<\/span><span class=\"n\">diagnostics<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Is<\/span><span class=\"p\">.<\/span><span class=\"n\">Empty<\/span><span class=\"p\">);<\/span>\n\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Get the result from the generator.<\/span>\n<span class=\"w\">        <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">generatorResult<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">runResult<\/span><span class=\"p\">.<\/span><span class=\"n\">Results<\/span><span class=\"p\">.<\/span><span class=\"n\">FirstOrDefault<\/span><span class=\"p\">();<\/span>\n\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Iterate over the expected source code files.<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">foreach<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">hintName<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">code<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"n\">ExpectedCode<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">            <\/span><span class=\"c1\">\/\/ GeneratedSourceResult is a struct, so check that we get a valid result.<\/span>\n<span class=\"w\">            <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">generated<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">generatorResult<\/span><span class=\"p\">.<\/span><span class=\"n\">GeneratedSources<\/span><span class=\"p\">.<\/span><span class=\"n\">FirstOrDefault<\/span><span class=\"p\">(<\/span><span class=\"n\">r<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">r<\/span><span class=\"p\">.<\/span><span class=\"n\">HintName<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"n\">hintName<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">            <\/span><span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">generated<\/span><span class=\"p\">.<\/span><span class=\"n\">HintName<\/span><span class=\"w\"> <\/span><span class=\"o\">!=<\/span><span class=\"w\"> <\/span><span class=\"n\">hintName<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">                <\/span><span class=\"k\">throw<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"nf\">InvalidOperationException<\/span><span class=\"p\">(<\/span><span class=\"s\">$&quot;No generated source found for: {hintName}&quot;<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">            <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">            <\/span><span class=\"c1\">\/\/ Convert the expected code into source text.<\/span>\n<span class=\"w\">            <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">expectedSourceText<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">SourceText<\/span><span class=\"p\">.<\/span><span class=\"n\">From<\/span><span class=\"p\">(<\/span><span class=\"n\">code<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Encoding<\/span><span class=\"p\">.<\/span><span class=\"n\">UTF8<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">SourceHashAlgorithm<\/span><span class=\"p\">.<\/span><span class=\"n\">Sha256<\/span><span class=\"p\">);<\/span>\n\n<span class=\"w\">            <\/span><span class=\"c1\">\/\/ Extract lines from the generated and expected source texts, for comparison.<\/span>\n<span class=\"w\">            <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">generatedLines<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">getLines<\/span><span class=\"p\">(<\/span><span class=\"n\">generated<\/span><span class=\"p\">.<\/span><span class=\"n\">SourceText<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">            <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">expectedLines<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">getLines<\/span><span class=\"p\">(<\/span><span class=\"n\">expectedSourceText<\/span><span class=\"p\">);<\/span>\n\n<span class=\"w\">            <\/span><span class=\"c1\">\/\/ Compare the lines using a collection assertion, to get as good failure<\/span>\n<span class=\"w\">            <\/span><span class=\"c1\">\/\/ output as possible.<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">Assert<\/span><span class=\"p\">.<\/span><span class=\"n\">That<\/span><span class=\"p\">(<\/span><span class=\"n\">generatedLines<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Is<\/span><span class=\"p\">.<\/span><span class=\"n\">EqualTo<\/span><span class=\"p\">(<\/span><span class=\"n\">expectedLines<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"s\">$&quot;Line mismatch for {hintName}&quot;<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">        <\/span><span class=\"k\">return<\/span><span class=\"p\">;<\/span>\n\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ This local function extracts lines from a source text, ignoring empty lines and<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ possibly ignoring line comments. Lines are trimmed so that comparison is not sensitive<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ to trailing whitespace.<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">IList<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">string<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">getLines<\/span><span class=\"p\">(<\/span><span class=\"n\">SourceText<\/span><span class=\"w\"> <\/span><span class=\"n\">text<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">            <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">text<\/span><span class=\"p\">.<\/span><span class=\"n\">Lines<\/span>\n<span class=\"w\">                <\/span><span class=\"p\">.<\/span><span class=\"n\">Select<\/span><span class=\"p\">(<\/span><span class=\"n\">l<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">l<\/span><span class=\"p\">.<\/span><span class=\"n\">ToString<\/span><span class=\"p\">().<\/span><span class=\"n\">Trim<\/span><span class=\"p\">())<\/span>\n<span class=\"w\">                <\/span><span class=\"p\">.<\/span><span class=\"n\">Where<\/span><span class=\"p\">(<\/span><span class=\"n\">l<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">l<\/span><span class=\"w\"> <\/span><span class=\"o\">!=<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">                <\/span><span class=\"p\">.<\/span><span class=\"n\">Where<\/span><span class=\"p\">(<\/span><span class=\"n\">l<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"o\">!<\/span><span class=\"n\">IgnoreLineComments<\/span><span class=\"w\"> <\/span><span class=\"o\">||<\/span><span class=\"w\"> <\/span><span class=\"o\">!<\/span><span class=\"n\">l<\/span><span class=\"p\">.<\/span><span class=\"n\">TrimStart<\/span><span class=\"p\">().<\/span><span class=\"n\">StartsWith<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;\/\/&quot;<\/span><span class=\"p\">))<\/span>\n<span class=\"w\">                <\/span><span class=\"p\">.<\/span><span class=\"n\">ToList<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Using this verifier, we can write a unit test for the generator. We create a class named\n<code>ColorModelGeneratorWay2ATest<\/code>, and write the first test as follows:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"na\">[TestFixture]<\/span>\n<span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">ColorModelGeneratorWay2ATest<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"na\">[Test]<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">Should_generate_an_accessor_class_for_a_color_model<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">verifier<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">TextVerifier<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">ColorModelGenerator<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">InputCode<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;&quot;&quot;<\/span>\n<span class=\"w\">                        <\/span><span class=\"na\">[generator.ColorModels]<\/span>\n<span class=\"w\">                        <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">ColorModels<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">                            <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span><span class=\"p\">[]<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"p\">[];<\/span>\n<span class=\"w\">                        <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">                        <\/span><span class=\"s\">&quot;&quot;&quot;,<\/span>\n\n<span class=\"w\">            <\/span><span class=\"n\">ExpectedCode<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span>\n<span class=\"w\">            <\/span><span class=\"na\">[<\/span>\n<span class=\"na\">                (<\/span>\n<span class=\"na\">                    &quot;colormodels.g.cs&quot;,<\/span>\n<span class=\"na\">                    &quot;&quot;&quot;<\/span>\n<span class=\"na\">                    #nullable enable<\/span>\n<span class=\"na\">                    using System;<\/span>\n<span class=\"na\">                    using System.Collections.Generic;<\/span>\n\n<span class=\"na\">                    namespace colormodels;<\/span>\n\n<span class=\"na\">                    public class EmptyColorModelAccessor(IDictionary&lt;string, double&gt; values) {<\/span>\n<span class=\"na\">                    }                                          <\/span>\n<span class=\"na\">                    &quot;&quot;&quot;)<\/span>\n<span class=\"na\">            ]<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">};<\/span>\n\n<span class=\"w\">        <\/span><span class=\"n\">verifier<\/span><span class=\"p\">.<\/span><span class=\"n\">Run<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>As you can see, the test is much more detailed than the previous one. Since we compare source text, we need to include\nusings, namespace etc. in the expected output. Of course, it would be possible to modify the verifier helper\nto ignore such lines in addition to empty lines and comment lines, but even so, this approach is\nsensitive to things like placement of curly braces. Old tests break easily if you make even small\nmodifications to the generated code.<\/p>\n<p>A benefit of writing tests like this is that it&rsquo;s very easy to visually (e.g., in a code review)\ndetermine that the expected code is correct. Another benefit is that we (with some modifications to the verifier)\ncan verify that no unexpected code is being generated.<\/p>\n<h3>2B. Test the generated syntax tree<\/h3>\n<p>We can create a slightly different verifier that allows us to write tests against the\ngenerated syntax tree. It can look like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">namespace<\/span><span class=\"w\"> <\/span><span class=\"nn\">generator.tests<\/span><span class=\"p\">;<\/span>\n\n<span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">SyntaxVerifier<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">TGenerator<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">VerifierBase<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">TGenerator<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"k\">where<\/span><span class=\"w\"> <\/span><span class=\"n\">TGenerator<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">IIncrementalGenerator<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ The input code to run through the generator.<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"n\">required<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span><span class=\"w\"> <\/span><span class=\"n\">InputCode<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"k\">get<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"n\">init<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ The sources we expect to be generated, as a list of tuples. The hint name is<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ typically the filename of a generated source file.<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"nf\">required<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"kt\">string<\/span><span class=\"w\"> <\/span><span class=\"n\">hintName<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Action<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">SyntaxTree<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">)[]<\/span><span class=\"w\"> <\/span><span class=\"n\">CodeTesters<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"k\">get<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"n\">init<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ List of error IDs to ignore. CS5001 is &quot;Program does not contain a static &#39;Main&#39; method suitable for an entry point&quot;.<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"n\">IList<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">string<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">IgnoredErrors<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"k\">get<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"n\">init<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"s\">&quot;CS5001&quot;<\/span><span class=\"p\">];<\/span>\n\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ Runs the verifier.<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">Run<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Input validation omitted for brevity.<\/span>\n\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Compile the input code.        <\/span>\n<span class=\"w\">        <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">runResult<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">RunGenerator<\/span><span class=\"p\">(<\/span><span class=\"n\">InputCode<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"k\">out<\/span><span class=\"w\"> <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">outputCompilation<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"k\">out<\/span><span class=\"w\"> <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">diagnostics<\/span><span class=\"p\">);<\/span>\n\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ We get diagnostics at this point if there are problems with the input source code. Fail on any<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ non-ignored error.<\/span>\n<span class=\"w\">        <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">errors<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">outputCompilation<\/span><span class=\"p\">.<\/span><span class=\"n\">GetDiagnostics<\/span><span class=\"p\">().<\/span><span class=\"n\">Where<\/span><span class=\"p\">(<\/span><span class=\"n\">d<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">d<\/span><span class=\"p\">.<\/span><span class=\"n\">Severity<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"n\">DiagnosticSeverity<\/span><span class=\"p\">.<\/span><span class=\"n\">Error<\/span><span class=\"w\"> <\/span><span class=\"o\">&amp;&amp;<\/span><span class=\"w\"> <\/span><span class=\"o\">!<\/span><span class=\"n\">IgnoredErrors<\/span><span class=\"p\">.<\/span><span class=\"n\">Contains<\/span><span class=\"p\">(<\/span><span class=\"n\">d<\/span><span class=\"p\">.<\/span><span class=\"n\">Id<\/span><span class=\"p\">)).<\/span><span class=\"n\">ToList<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">Assert<\/span><span class=\"p\">.<\/span><span class=\"n\">That<\/span><span class=\"p\">(<\/span><span class=\"n\">errors<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Is<\/span><span class=\"p\">.<\/span><span class=\"n\">Empty<\/span><span class=\"p\">);<\/span>\n\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ We&#39;ll see a diagnostic at this point if the generator throws an exception,<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ or if the generator emits a diagnostic.<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">Assert<\/span><span class=\"p\">.<\/span><span class=\"n\">That<\/span><span class=\"p\">(<\/span><span class=\"n\">diagnostics<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Is<\/span><span class=\"p\">.<\/span><span class=\"n\">Empty<\/span><span class=\"p\">);<\/span>\n\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Get the result from the generator.<\/span>\n<span class=\"w\">        <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">generatorResult<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">runResult<\/span><span class=\"p\">.<\/span><span class=\"n\">Results<\/span><span class=\"p\">.<\/span><span class=\"n\">FirstOrDefault<\/span><span class=\"p\">();<\/span>\n\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Iterate over the expected source code files.<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">foreach<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">hintName<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">tester<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"n\">CodeTesters<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">            <\/span><span class=\"c1\">\/\/ GeneratedSourceResult is a struct, so check that we get a valid result.<\/span>\n<span class=\"w\">            <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">generated<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">generatorResult<\/span><span class=\"p\">.<\/span><span class=\"n\">GeneratedSources<\/span><span class=\"p\">.<\/span><span class=\"n\">FirstOrDefault<\/span><span class=\"p\">(<\/span><span class=\"n\">r<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">r<\/span><span class=\"p\">.<\/span><span class=\"n\">HintName<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"n\">hintName<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">            <\/span><span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">generated<\/span><span class=\"p\">.<\/span><span class=\"n\">HintName<\/span><span class=\"w\"> <\/span><span class=\"o\">!=<\/span><span class=\"w\"> <\/span><span class=\"n\">hintName<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">                <\/span><span class=\"k\">throw<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"nf\">InvalidOperationException<\/span><span class=\"p\">(<\/span><span class=\"s\">$&quot;No generated source found for: {hintName}&quot;<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">            <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">            <\/span><span class=\"n\">tester<\/span><span class=\"p\">(<\/span><span class=\"n\">generated<\/span><span class=\"p\">.<\/span><span class=\"n\">SyntaxTree<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>It&rsquo;s slightly simpler than the text-based verifier. Instead of accepting tuples that contain expected\ncode, it contains tuples with syntax tree testers - where &ldquo;tester&rdquo; in this case is nothing more than\nan action that receives a <code>SyntaxTree<\/code>.<\/p>\n<p>Based on this, we can create <code>ColorModelGeneratorWay2BTest<\/code>, which looks like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"na\">[TestFixture]<\/span>\n<span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">ColorModelGeneratorWay2BTest<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"na\">[Test]<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">Should_generate_an_accessor_class_for_a_color_model<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">verifier<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">SyntaxVerifier<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">ColorModelGenerator<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n\n<span class=\"w\">            <\/span><span class=\"n\">InputCode<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;&quot;&quot;<\/span>\n<span class=\"w\">                        <\/span><span class=\"na\">[generator.ColorModels]<\/span>\n<span class=\"w\">                        <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">TestColorModels<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">                            <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span><span class=\"p\">[]<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"p\">[];<\/span>\n<span class=\"w\">                        <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">                        <\/span><span class=\"s\">&quot;&quot;&quot;,<\/span>\n\n<span class=\"w\">            <\/span><span class=\"n\">CodeTesters<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span>\n<span class=\"w\">            <\/span><span class=\"na\">[<\/span>\n<span class=\"na\">                (<\/span>\n<span class=\"na\">                    &quot;colormodels.g.cs&quot;,<\/span>\n<span class=\"na\">                    tree =&gt; {<\/span>\n<span class=\"na\">                        var classNames = tree.GetRoot().DescendantNodes()<\/span>\n<span class=\"na\">                            .OfType&lt;ClassDeclarationSyntax&gt;()<\/span>\n<span class=\"na\">                            .Select(cls =&gt; cls.Identifier.Text)<\/span>\n<span class=\"na\">                            .ToList();<\/span>\n<span class=\"na\">                        Assert.That(classNames, Does.Contain(&quot;EmptyColorModelAccessor&quot;));<\/span>\n<span class=\"na\">                    }<\/span>\n<span class=\"na\">                )<\/span>\n<span class=\"na\">            ]<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">};<\/span>\n\n<span class=\"w\">        <\/span><span class=\"n\">verifier<\/span><span class=\"p\">.<\/span><span class=\"n\">Run<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>The syntax tree tester enumerates all class declarations found in the syntax tree, and\ntests that there is one with the correct name. This way of testing the generator output\nis much more robust than the text-based way, though the assertion is not as easy to read\n(nor to write, as it requires knowledge about the syntax tree).<\/p>\n<p>Another benefit is that\nspecific assertions like the one above can have a better <em>failure output<\/em> compared to a line diff.\nFor example, if the generator misspells the class name as <code>Accesor<\/code>, these are the failure outputs of\nthe tests written so far:<\/p>\n<p>Way 1:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">Expected<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">not<\/span><span class=\"w\"> <\/span><span class=\"kc\">null<\/span>\n<span class=\"w\">  <\/span><span class=\"n\">But<\/span><span class=\"w\"> <\/span><span class=\"n\">was<\/span><span class=\"o\">:<\/span><span class=\"w\">  <\/span><span class=\"kc\">null<\/span>\n<\/code><\/pre><\/div>\n\n<p>Way 2A:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nv\">Line<\/span><span class=\"w\"> <\/span><span class=\"nv\">mismatch<\/span><span class=\"w\"> <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"nv\">colormodels<\/span>.<span class=\"nv\">g<\/span>.<span class=\"nv\">cs<\/span>\n<span class=\"w\">  <\/span><span class=\"nv\">Expected<\/span><span class=\"w\"> <\/span><span class=\"nv\">and<\/span><span class=\"w\"> <\/span><span class=\"nv\">actual<\/span><span class=\"w\"> <\/span><span class=\"nv\">are<\/span><span class=\"w\"> <\/span><span class=\"nv\">both<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;<\/span><span class=\"nv\">System<\/span>.<span class=\"nv\">Collections<\/span>.<span class=\"nv\">Generic<\/span>.<span class=\"nv\">List<\/span>`<span class=\"mi\">1<\/span>[<span class=\"nv\">System<\/span>.<span class=\"nv\">String<\/span>]<span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"nv\">with<\/span><span class=\"w\"> <\/span><span class=\"mi\">6<\/span><span class=\"w\"> <\/span><span class=\"nv\">elements<\/span>\n<span class=\"w\">  <\/span><span class=\"nv\">Values<\/span><span class=\"w\"> <\/span><span class=\"nv\">differ<\/span><span class=\"w\"> <\/span><span class=\"nv\">at<\/span><span class=\"w\"> <\/span><span class=\"nv\">index<\/span><span class=\"w\"> <\/span>[<span class=\"mi\">4<\/span>]\n<span class=\"w\">  <\/span><span class=\"nv\">Expected<\/span><span class=\"w\"> <\/span><span class=\"nv\">string<\/span><span class=\"w\"> <\/span><span class=\"nv\">length<\/span><span class=\"w\"> <\/span><span class=\"mi\">74<\/span><span class=\"w\"> <\/span><span class=\"nv\">but<\/span><span class=\"w\"> <\/span><span class=\"nv\">was<\/span><span class=\"w\"> <\/span><span class=\"mi\">73<\/span>.<span class=\"w\"> <\/span><span class=\"nv\">Strings<\/span><span class=\"w\"> <\/span><span class=\"nv\">differ<\/span><span class=\"w\"> <\/span><span class=\"nv\">at<\/span><span class=\"w\"> <\/span><span class=\"nv\">index<\/span><span class=\"w\"> <\/span><span class=\"mi\">33<\/span>.\n<span class=\"w\">  <\/span><span class=\"nv\">Expected<\/span>:<span class=\"w\"> <\/span><span class=\"s2\">&quot;...EmptyColorModelAccessor(IDictionary&lt;string, double&gt; values) {&quot;<\/span>\n<span class=\"w\">  <\/span><span class=\"nv\">But<\/span><span class=\"w\"> <\/span><span class=\"nv\">was<\/span>:<span class=\"w\">  <\/span><span class=\"s2\">&quot;...EmptyColorModelAccesor(IDictionary&lt;string, double&gt; values) {&quot;<\/span>\n<span class=\"w\">  <\/span><span class=\"o\">----------------------------------^<\/span>\n<\/code><\/pre><\/div>\n\n<p>Way 2B:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">Expected<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">some<\/span><span class=\"w\"> <\/span><span class=\"n\">item<\/span><span class=\"w\"> <\/span><span class=\"n\">equal<\/span><span class=\"w\"> <\/span><span class=\"n\">to<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;EmptyColorModelAccessor&quot;<\/span>\n<span class=\"w\">  <\/span><span class=\"n\">But<\/span><span class=\"w\"> <\/span><span class=\"n\">was<\/span><span class=\"o\">:<\/span><span class=\"w\">  <\/span><span class=\"o\">&lt;<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;EmptyColorModelAccesor&quot;<\/span><span class=\"w\"> <\/span><span class=\"o\">&gt;<\/span>\n<\/code><\/pre><\/div>\n\n<p>I&rsquo;ll admit that 2A is clear enough in this particular case, but it also contains some noise.\n2B is concise and easy to understand, I think.<\/p>\n<h3>2C. Testing diagnostics<\/h3>\n<p>Let&rsquo;s look at testing generator diagnostics. As mentioned, doing so is not possible if we test the generated\ncode elements (way 1). If the generator emits an error diagnostics, there may be no generated code element to test,\nand there will be an error in the test project, preventing us from running the tests.<\/p>\n<p>Let&rsquo;s look at a verifier that allows us to test diagnostics:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">namespace<\/span><span class=\"w\"> <\/span><span class=\"nn\">generator.tests<\/span><span class=\"p\">;<\/span>\n\n<span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">DiagnosticVerifier<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">TGenerator<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">VerifierBase<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">TGenerator<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"k\">where<\/span><span class=\"w\"> <\/span><span class=\"n\">TGenerator<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">IIncrementalGenerator<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ The input code to run through the generator.<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"n\">required<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span><span class=\"w\"> <\/span><span class=\"n\">InputCode<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"k\">get<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"n\">init<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ List of error IDs to ignore. CS5001 is &quot;Program does not contain a static &#39;Main&#39; method suitable for an entry point&quot;.<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"n\">IList<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">string<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">IgnoredErrors<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"k\">get<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"n\">init<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"s\">&quot;CS5001&quot;<\/span><span class=\"p\">];<\/span>\n\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ Runs the verifier. The action will receive the diagnostics emitted by the generator.<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">Run<\/span><span class=\"p\">(<\/span><span class=\"n\">Action<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">IEnumerable<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Diagnostic<\/span><span class=\"o\">&gt;&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">tester<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Input validation omitted for brevity.<\/span>\n\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Compile the input code (the result is not used).<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">_<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">RunGenerator<\/span><span class=\"p\">(<\/span><span class=\"n\">InputCode<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"k\">out<\/span><span class=\"w\"> <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">outputCompilation<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"k\">out<\/span><span class=\"w\"> <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">diagnostics<\/span><span class=\"p\">);<\/span>\n\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ We get diagnostics if there are problems with the input source code. Fail on any<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ non-ignored error.<\/span>\n<span class=\"w\">        <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">errors<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">outputCompilation<\/span><span class=\"p\">.<\/span><span class=\"n\">GetDiagnostics<\/span><span class=\"p\">().<\/span><span class=\"n\">Where<\/span><span class=\"p\">(<\/span><span class=\"n\">d<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">d<\/span><span class=\"p\">.<\/span><span class=\"n\">Severity<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"n\">DiagnosticSeverity<\/span><span class=\"p\">.<\/span><span class=\"n\">Error<\/span><span class=\"w\"> <\/span><span class=\"o\">&amp;&amp;<\/span><span class=\"w\"> <\/span><span class=\"o\">!<\/span><span class=\"n\">IgnoredErrors<\/span><span class=\"p\">.<\/span><span class=\"n\">Contains<\/span><span class=\"p\">(<\/span><span class=\"n\">d<\/span><span class=\"p\">.<\/span><span class=\"n\">Id<\/span><span class=\"p\">)).<\/span><span class=\"n\">ToList<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">Assert<\/span><span class=\"p\">.<\/span><span class=\"n\">That<\/span><span class=\"p\">(<\/span><span class=\"n\">errors<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Is<\/span><span class=\"p\">.<\/span><span class=\"n\">Empty<\/span><span class=\"p\">);<\/span>\n\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Test the emitted diagnostics<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">tester<\/span><span class=\"p\">(<\/span><span class=\"n\">diagnostics<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Problems with the input source code will fail a test, unless ignored. However, emitted diagnostics will\nbe passed to a tester action that allows to verify them.<\/p>\n<p>Let&rsquo;s write a test that emits an error if a color is a known trademarked color, such as Vantablack&trade;:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"na\">[TestFixture]<\/span>\n<span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">ColorModelGeneratorWay2CTest<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"na\">[Test]<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">Should_detect_trademarked_color<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">verifier<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">DiagnosticVerifier<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">ColorModelGenerator<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n\n<span class=\"w\">            <\/span><span class=\"n\">InputCode<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;&quot;&quot;<\/span>\n<span class=\"w\">                        <\/span><span class=\"na\">[generator.ColorModels]<\/span>\n<span class=\"w\">                        <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">TestColorModels<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">                            <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span><span class=\"p\">[]<\/span><span class=\"w\"> <\/span><span class=\"n\">Sneaky<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"s\">&quot;red&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;Vantablack&quot;<\/span><span class=\"p\">];<\/span>\n<span class=\"w\">                        <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">                        <\/span><span class=\"s\">&quot;&quot;&quot;<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">};<\/span>\n\n<span class=\"w\">        <\/span><span class=\"n\">verifier<\/span><span class=\"p\">.<\/span><span class=\"n\">Run<\/span><span class=\"p\">(<\/span><span class=\"n\">diags<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">            <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">messages<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">diags<\/span><span class=\"p\">.<\/span><span class=\"n\">Select<\/span><span class=\"p\">(<\/span><span class=\"n\">diag<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">diag<\/span><span class=\"p\">.<\/span><span class=\"n\">GetMessage<\/span><span class=\"p\">()).<\/span><span class=\"n\">ToList<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">Assert<\/span><span class=\"p\">.<\/span><span class=\"n\">That<\/span><span class=\"p\">(<\/span><span class=\"n\">messages<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Does<\/span><span class=\"p\">.<\/span><span class=\"n\">Contain<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;The color &#39;Vantablack&#39; in the &#39;Sneaky&#39; color model is trademarked&quot;<\/span><span class=\"p\">));<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">});<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>There are of course other aspects to test as well, such as the diagnostic severity and location\n(i.e. which code element it refers to), but I think the message is the first thing to look at.<\/p>\n<p>As noted in the verifier comments, any exception thrown by the generator will also be reported as\na diagnostic. For example, if the generator throws <code>ArgumentException<\/code> when it encounters a color\nthat contains invalid characters, the (testable) diagnostic may look as follows:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">warning<\/span><span class=\"w\"> <\/span><span class=\"nx\">CS8785<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">Generator<\/span><span class=\"w\"> <\/span><span class=\"err\">&#39;<\/span><span class=\"nx\">ColorModelGenerator<\/span><span class=\"err\">&#39;<\/span><span class=\"w\"> <\/span><span class=\"nx\">failed<\/span><span class=\"w\"> <\/span><span class=\"nx\">to<\/span><span class=\"w\"> <\/span><span class=\"nx\">generate<\/span><span class=\"w\"> <\/span><span class=\"nx\">source<\/span><span class=\"p\">.<\/span>\n<span class=\"nx\">It<\/span><span class=\"w\"> <\/span><span class=\"nx\">will<\/span><span class=\"w\"> <\/span><span class=\"k\">not<\/span><span class=\"w\"> <\/span><span class=\"nx\">contribute<\/span><span class=\"w\"> <\/span><span class=\"nx\">to<\/span><span class=\"w\"> <\/span><span class=\"nx\">the<\/span><span class=\"w\"> <\/span><span class=\"nx\">output<\/span><span class=\"w\"> <\/span><span class=\"k\">and<\/span><span class=\"w\"> <\/span><span class=\"nx\">compilation<\/span><span class=\"w\"> <\/span><span class=\"nx\">errors<\/span><span class=\"w\"> <\/span><span class=\"nx\">may<\/span><span class=\"w\"> <\/span><span class=\"nx\">occur<\/span><span class=\"w\"> <\/span><span class=\"k\">as<\/span><span class=\"w\"> <\/span><span class=\"nx\">a<\/span><span class=\"w\"> <\/span><span class=\"nx\">result<\/span><span class=\"p\">.<\/span>\n<span class=\"nx\">Exception<\/span><span class=\"w\"> <\/span><span class=\"nx\">was<\/span><span class=\"w\"> <\/span><span class=\"nx\">of<\/span><span class=\"w\"> <\/span><span class=\"k\">type<\/span><span class=\"w\"> <\/span><span class=\"err\">&#39;<\/span><span class=\"nx\">ArgumentException<\/span><span class=\"err\">&#39;<\/span><span class=\"w\"> <\/span><span class=\"nx\">with<\/span><span class=\"w\"> <\/span><span class=\"nx\">message<\/span><span class=\"w\"> <\/span><span class=\"err\">&#39;<\/span><span class=\"c1\">\/\/ is not a valid color&#39;.<\/span>\n<\/code><\/pre><\/div>\n\n<h1>Generator implementation<\/h1>\n<p>Let&rsquo;s look at the implementation of the generator. I won&rsquo;t go into details about incremental generators -\nyou can find good documentation <a href=\"https:\/\/github.com\/dotnet\/roslyn\/blob\/main\/docs\/features\/incremental-generators.md\">here<\/a>.<\/p>\n<h2>Initialize<\/h2>\n<p>Let&rsquo;s implement the <code>Initialize<\/code> method. It can look like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">Initialize<\/span><span class=\"p\">(<\/span><span class=\"n\">IncrementalGeneratorInitializationContext<\/span><span class=\"w\"> <\/span><span class=\"n\">context<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Define a syntax provider to filter nodes based on the ColorModels attribute<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ and extract the color model variables.<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ The predicate is not needed, so it just returns true.<\/span>\n<span class=\"w\">        <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">variablesProvider<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">context<\/span><span class=\"p\">.<\/span><span class=\"n\">SyntaxProvider<\/span><span class=\"p\">.<\/span><span class=\"n\">ForAttributeWithMetadataName<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">                <\/span><span class=\"k\">typeof<\/span><span class=\"p\">(<\/span><span class=\"n\">ColorModelsAttribute<\/span><span class=\"p\">).<\/span><span class=\"n\">FullName<\/span><span class=\"o\">!<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">                <\/span><span class=\"n\">predicate<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">_<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">_<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"k\">true<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">                <\/span><span class=\"n\">transform<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">ctx<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">_<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">GetVariables<\/span><span class=\"p\">(<\/span><span class=\"n\">ctx<\/span><span class=\"p\">))<\/span>\n<span class=\"w\">            <\/span><span class=\"p\">.<\/span><span class=\"n\">SelectMany<\/span><span class=\"p\">((<\/span><span class=\"n\">fields<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">_<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">fields<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">            <\/span><span class=\"p\">.<\/span><span class=\"n\">Collect<\/span><span class=\"p\">();<\/span>\n\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Register the source output. The delegate receives the result from executing the provider.<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">context<\/span><span class=\"p\">.<\/span><span class=\"n\">RegisterSourceOutput<\/span><span class=\"p\">(<\/span><span class=\"n\">variablesProvider<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">spc<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">variables<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">Execute<\/span><span class=\"p\">(<\/span><span class=\"n\">spc<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">variables<\/span><span class=\"p\">));<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">    <\/span><span class=\"k\">private<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"n\">IEnumerable<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">VariableDeclaratorSyntax<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">GetVariables<\/span><span class=\"p\">(<\/span><span class=\"n\">GeneratorAttributeSyntaxContext<\/span><span class=\"w\"> <\/span><span class=\"n\">context<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"p\">...<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>The <code>ForAttributeWithMetadataName<\/code> method creates a provider that looks for attributes of the given\ntype. When an attribute node is found, it&rsquo;s transformed using the <code>GetVariables<\/code> method. As can be seen\nin the signature of <code>GetVariables<\/code>, it returns an enumerable of variables, which is why <code>SelectMany<\/code> is used\nto flatten all the transformed enumerables into a single one. The final provider result is passed to the <code>Execute<\/code> method.<\/p>\n<p>The <code>GetVariables<\/code> method looks like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"w\">    <\/span><span class=\"k\">private<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"n\">IEnumerable<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">VariableDeclaratorSyntax<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">GetVariables<\/span><span class=\"p\">(<\/span><span class=\"n\">GeneratorAttributeSyntaxContext<\/span><span class=\"w\"> <\/span><span class=\"n\">context<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">context<\/span><span class=\"p\">.<\/span><span class=\"n\">TargetNode<\/span><span class=\"w\"> <\/span><span class=\"k\">is<\/span><span class=\"w\"> <\/span><span class=\"n\">not<\/span><span class=\"w\"> <\/span><span class=\"n\">ClassDeclarationSyntax<\/span><span class=\"w\"> <\/span><span class=\"n\">classDeclarationSyntax<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"k\">yield<\/span><span class=\"w\"> <\/span><span class=\"k\">break<\/span><span class=\"p\">;<\/span>\n\n<span class=\"w\">        <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">fields<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">classDeclarationSyntax<\/span><span class=\"p\">.<\/span><span class=\"n\">Members<\/span><span class=\"p\">.<\/span><span class=\"n\">OfType<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">FieldDeclarationSyntax<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">foreach<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">fieldDecl<\/span><span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"n\">fields<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">            <\/span><span class=\"k\">foreach<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">variable<\/span><span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"n\">fieldDecl<\/span><span class=\"p\">.<\/span><span class=\"n\">Declaration<\/span><span class=\"p\">.<\/span><span class=\"n\">Variables<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">                <\/span><span class=\"k\">yield<\/span><span class=\"w\"> <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">variable<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">            <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<blockquote>\n<p>Side note: A field can have multiple variables, e.g. if you write <code>public static string[] RGB = [...], CMYK = [...];<\/code>.<\/p>\n<\/blockquote>\n<p>We expect the target node to be a class, since the <code>ColorModels<\/code> attribute only targets classes, and\nthe use of pattern matching is a convenient way of checking that and exiting if something is wrong.\nNext, we list fields in the class, and for each field, we list its variables.<\/p>\n<p>This is the minimum required by the tests written so far, but\nit&rsquo;s a good idea to make some additional filtering (driven by tests, of course):<\/p>\n<ul>\n<li>Require the field to be <code>public static<\/code>.<\/li>\n<li>Require the field to have type <code>string[]<\/code>.<\/li>\n<\/ul>\n<h2>Execute<\/h2>\n<p>In the <code>Execute<\/code> method, we act on the collected variables. Here is an implementation that satisfies\nthe current test suite:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">private<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">Execute<\/span><span class=\"p\">(<\/span><span class=\"n\">SourceProductionContext<\/span><span class=\"w\"> <\/span><span class=\"n\">context<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">IEnumerable<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">VariableDeclaratorSyntax<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">variables<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ Start building the code.<\/span>\n<span class=\"w\">    <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">sourceBuilder<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">StringBuilder<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;&quot;&quot;<\/span>\n<span class=\"w\">                                          <\/span><span class=\"err\">#<\/span><span class=\"n\">nullable<\/span><span class=\"w\"> <\/span><span class=\"n\">enable<\/span>\n<span class=\"w\">                                          <\/span><span class=\"k\">using<\/span><span class=\"w\"> <\/span><span class=\"nn\">System<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">                                          <\/span><span class=\"k\">using<\/span><span class=\"w\"> <\/span><span class=\"nn\">System.Collections.Generic<\/span><span class=\"p\">;<\/span>\n\n<span class=\"w\">                                          <\/span><span class=\"k\">namespace<\/span><span class=\"w\"> <\/span><span class=\"nn\">colormodels<\/span><span class=\"p\">;<\/span>\n\n<span class=\"w\">                                          <\/span><span class=\"s\">&quot;&quot;&quot;);<\/span>\n\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ Iterate over the collected color model variables.<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">foreach<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">variable<\/span><span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"n\">variables<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">colorNames<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">GetStrings<\/span><span class=\"p\">(<\/span><span class=\"n\">variable<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">        <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">modelName<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">variable<\/span><span class=\"p\">.<\/span><span class=\"n\">Identifier<\/span><span class=\"p\">.<\/span><span class=\"n\">ValueText<\/span><span class=\"p\">;<\/span>\n\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Generate the start of an accessor class for the current model.<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">sourceBuilder<\/span><span class=\"p\">.<\/span><span class=\"n\">AppendLine<\/span><span class=\"p\">(<\/span><span class=\"err\">$<\/span><span class=\"s\">$&quot;&quot;&quot;<\/span>\n<span class=\"w\">                                   <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"p\">{{<\/span><span class=\"n\">modelName<\/span><span class=\"p\">}}<\/span><span class=\"n\">ColorModelAccessor<\/span><span class=\"p\">(<\/span><span class=\"n\">IDictionary<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">string<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"kt\">double<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">values<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">                                   <\/span><span class=\"s\">&quot;&quot;&quot;);<\/span>\n\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Iterate over colors to generate properties.<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">foreach<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">color<\/span><span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"n\">colorNames<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">            <\/span><span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">TrademarkedColors<\/span><span class=\"p\">.<\/span><span class=\"n\">Contains<\/span><span class=\"p\">(<\/span><span class=\"n\">color<\/span><span class=\"p\">))<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">                <\/span><span class=\"c1\">\/\/ Trademarked color found!<\/span>\n<span class=\"w\">                <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">diagnostic<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Diagnostic<\/span><span class=\"p\">.<\/span><span class=\"n\">Create<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">                    <\/span><span class=\"n\">TrademarkedColorDescriptor<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">                    <\/span><span class=\"n\">variable<\/span><span class=\"p\">.<\/span><span class=\"n\">GetLocation<\/span><span class=\"p\">(),<\/span>\n<span class=\"w\">                    <\/span><span class=\"n\">color<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">categoryName<\/span><span class=\"p\">);<\/span>\n\n<span class=\"w\">                <\/span><span class=\"n\">context<\/span><span class=\"p\">.<\/span><span class=\"n\">ReportDiagnostic<\/span><span class=\"p\">(<\/span><span class=\"n\">diagnostic<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">            <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">            <\/span><span class=\"c1\">\/\/ TODO: Append the actual color component property here!<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">        <\/span><span class=\"n\">sourceBuilder<\/span><span class=\"p\">.<\/span><span class=\"n\">AppendLine<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;}&quot;<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ Emit the actual code.<\/span>\n<span class=\"w\">    <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">generatedCode<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">sourceBuilder<\/span><span class=\"p\">.<\/span><span class=\"n\">ToString<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">context<\/span><span class=\"p\">.<\/span><span class=\"n\">AddSource<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;colormodels.g.cs&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">SourceText<\/span><span class=\"p\">.<\/span><span class=\"n\">From<\/span><span class=\"p\">(<\/span><span class=\"n\">generatedCode<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Encoding<\/span><span class=\"p\">.<\/span><span class=\"n\">UTF8<\/span><span class=\"p\">));<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Since we haven&rsquo;t written any tests that verify the presence or behavior of a property for a color model component,\nthat code is omitted for now.<\/p>\n<p>The <code>GetStrings<\/code> function and the descriptor for the diagnostic are needed as well:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"w\">    <\/span><span class=\"k\">private<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span><span class=\"p\">[]<\/span><span class=\"w\"> <\/span><span class=\"nf\">GetStrings<\/span><span class=\"p\">(<\/span><span class=\"n\">VariableDeclaratorSyntax<\/span><span class=\"w\"> <\/span><span class=\"n\">variable<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">variable<\/span><span class=\"p\">.<\/span><span class=\"n\">Initializer<\/span><span class=\"o\">?.<\/span><span class=\"n\">Value<\/span><span class=\"w\"> <\/span><span class=\"k\">is<\/span><span class=\"w\"> <\/span><span class=\"n\">CollectionExpressionSyntax<\/span><span class=\"w\"> <\/span><span class=\"n\">collection<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">            <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">collection<\/span><span class=\"p\">.<\/span><span class=\"n\">Elements<\/span><span class=\"p\">.<\/span><span class=\"n\">SelectMany<\/span><span class=\"p\">(<\/span><span class=\"n\">elem<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span>\n<span class=\"w\">                <\/span><span class=\"n\">elem<\/span><span class=\"w\"> <\/span><span class=\"k\">is<\/span><span class=\"w\"> <\/span><span class=\"n\">ExpressionElementSyntax<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"n\">Expression<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">LiteralExpressionSyntax<\/span><span class=\"w\"> <\/span><span class=\"n\">literal<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">                    <\/span><span class=\"o\">?<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"n\">literal<\/span><span class=\"p\">.<\/span><span class=\"n\">Token<\/span><span class=\"p\">.<\/span><span class=\"n\">ValueText<\/span><span class=\"p\">]<\/span>\n<span class=\"w\">                    <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">Array<\/span><span class=\"p\">.<\/span><span class=\"n\">Empty<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">string<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">()<\/span>\n<span class=\"w\">            <\/span><span class=\"p\">).<\/span><span class=\"n\">ToArray<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">        <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"p\">[];<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">    <\/span><span class=\"k\">private<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"k\">readonly<\/span><span class=\"w\"> <\/span><span class=\"n\">DiagnosticDescriptor<\/span><span class=\"w\"> <\/span><span class=\"n\">TrademarkedColorDescriptor<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">id<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;CM001&quot;<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">title<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;Trademarked Color&quot;<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">messageFormat<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;The color &#39;{0}&#39; in the &#39;{1}&#39; color model is trademarked&quot;<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">category<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;Syntax&quot;<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">DiagnosticSeverity<\/span><span class=\"p\">.<\/span><span class=\"n\">Error<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">isEnabledByDefault<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"k\">true<\/span><span class=\"p\">);<\/span>\n\n<span class=\"w\">    <\/span><span class=\"k\">private<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span><span class=\"p\">[]<\/span><span class=\"w\"> <\/span><span class=\"n\">TrademarkedColors<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"s\">&quot;Vantablack&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;Barbie Pink&quot;<\/span><span class=\"p\">];<\/span>\n<\/code><\/pre><\/div>\n\n<p><code>GetStrings<\/code> verifies that the variable is a collection variable but nothing beyond that. As noted,\nthe filtering of fields should make sure that the type is correct.<\/p>\n<h1>Debugging<\/h1>\n<p>To be able to debug the source generator outside of the unit tests (e.g. when writing behavioral tests\nlike way 1), we can add a <code>Properties<\/code> folder to the <code>generator<\/code> project,\nand add a <code>launchSettings.json<\/code> file in that folder. The file should look like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">{<\/span>\n<span class=\"w\">  <\/span><span class=\"nt\">&quot;$schema&quot;<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;http:\/\/json.schemastore.org\/launchsettings.json&quot;<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">  <\/span><span class=\"nt\">&quot;profiles&quot;<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"nt\">&quot;Generators&quot;<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">      <\/span><span class=\"nt\">&quot;commandName&quot;<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;DebugRoslynComponent&quot;<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">      <\/span><span class=\"nt\">&quot;targetProject&quot;<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;..\\\\generator.tests\\\\generator.tests.csproj&quot;<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">  <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>(Note that backslashes have to be escaped, unlike in <code>csproj<\/code> files.)<\/p>\n<blockquote>\n<p>For debugging to work in Visual Studio, you may have to add the <code>.NET Compiler Platform SDK<\/code> component\nto your installation.<\/p>\n<\/blockquote>\n<p>To start debugging in Rider, click on the small play button that appears next to the &ldquo;Generators&rdquo; line\nin  <code>launchSettings.json<\/code>. In Visual Studio, right-click on the <code>generators<\/code> project, select Debug\nand then &ldquo;Start New Instance&rdquo;.<\/p>\n<h1>Final words<\/h1>\n<p>Source generators are powerful tools as they allow us to write less &ldquo;manual&rdquo; code, thus reducing the\nrisk for bugs. Using them correctly, we can lift our gaze and work with high-level concepts, but still\ninterface with the concepts in the codebase. The use case in this post is quite simple, but there are\nmany other interesting use cases. For example, properties in a class can be augmented\nto track changes, or a simple CRUD UI, API, and storage can be generated from a model class.<\/p>\n<p>And, as icing on the cake (or &ldquo;cream on the mashed potatoes&rdquo; as we say in Sweden), it&rsquo;s easy to\nwrite tests for our source generators, just as we would any other code!<\/p>\n<p>Happy generating!<\/p>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"csharp"}},{"@attributes":{"term":"coding"}},{"@attributes":{"term":"test"}},{"@attributes":{"term":"tdd"}}]},{"title":"Return on Investment for Test-Driven Development","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/return-on-investment-for-test-driven-development.html","rel":"alternate"}},"published":"2023-04-28T17:30:00+02:00","updated":"2023-04-28T17:30:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2023-04-28:\/return-on-investment-for-test-driven-development.html","summary":"<p>I recently came across a thread discussing Test-Driven Development (TDD) on one of the major social networks.\nThe discussion revolved around when to use TDD and when it can be skipped. \nAs a consistent TDD practitioner, I find these discussions interesting, especially when it comes to understanding the perspectives of \u2026<\/p>","content":"<p>I recently came across a thread discussing Test-Driven Development (TDD) on one of the major social networks.\nThe discussion revolved around when to use TDD and when it can be skipped. \nAs a consistent TDD practitioner, I find these discussions interesting, especially when it comes to understanding the perspectives of those who argue against TDD.<\/p>\n<p>One particular response in the thread caught my attention:<\/p>\n<blockquote>\n<p>TDD should not be used for simple functions because the return on investment is too low.<\/p>\n<\/blockquote>\n<p>I guess the reasoning behind this is that simple functions can be verified through manual inspection, and their simplicity makes them easy to change.\nWhile this argument makes <em>some<\/em> sense, it&rsquo;s not uncommon for functions that begin as simple to grow\ncomplex over time, thereby defeating manual verification.<\/p>\n<p>Recently, I reviewed a bug fix for a seemingly simple function that clearly lacked a test-driven approach, as it had no automated tests at all. Here&rsquo;s the original (but anonymized) Kotlin code:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">data<\/span><span class=\"w\"> <\/span><span class=\"kd\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">Colors<\/span><span class=\"p\">(<\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nv\">red<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kt\">Boolean?<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"kc\">false<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nv\">green<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kt\">Boolean?<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"kc\">false<\/span><span class=\"p\">)<\/span>\n\n<span class=\"kd\">fun<\/span><span class=\"w\"> <\/span><span class=\"nf\">describeColors<\/span><span class=\"p\">(<\/span><span class=\"n\">colors<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">Colors<\/span><span class=\"p\">):<\/span><span class=\"w\"> <\/span><span class=\"kt\">String<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">listOfNotNull<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">colors<\/span><span class=\"p\">.<\/span><span class=\"na\">red<\/span><span class=\"o\">?.<\/span><span class=\"na\">takeIf<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"nb\">it<\/span><span class=\"w\"> <\/span><span class=\"p\">}.<\/span><span class=\"na\">let<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;Red&quot;<\/span><span class=\"w\"> <\/span><span class=\"p\">},<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">colors<\/span><span class=\"p\">.<\/span><span class=\"na\">green<\/span><span class=\"o\">?.<\/span><span class=\"na\">takeIf<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"nb\">it<\/span><span class=\"w\"> <\/span><span class=\"p\">}.<\/span><span class=\"na\">let<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;Green&quot;<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">).<\/span><span class=\"na\">joinToString<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot; &amp; &quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>This code defines a <code>Colors<\/code> class with flags for red and green. There&rsquo;s a function that describes a <code>Colors<\/code> instance by listing the active colors, separated by &ldquo;&amp;&ldquo;.\nAt first glance, the function seems straightforward. You could argue that the implementation is more complex than necessary, but its functionality is relatively limited.<\/p>\n<p>However, the function has a critical flaw&mdash;it always returns &ldquo;Red &amp; Green&rdquo;, regardless of the contents of the <code>Colors<\/code> instance.<\/p>\n<p>Before examining the fix, let&rsquo;s consider the following:<\/p>\n<ul>\n<li>The original author seemingly deemed the function simple enough to skip TDD, saving some development time.\n  (They apparently also skipped manual testing, but that&rsquo;s a different topic.)<\/li>\n<li>The bug persisted in production for an extended period of time, causing confusion and frustration for users.<\/li>\n<li>Eventually, a user submitted a support case to address the issue.<\/li>\n<li>A JIRA ticket was created and prioritized.<\/li>\n<li>A developer diagnosed the problem, wrote unit tests, fixed the bug, and submitted a PR.<\/li>\n<li>Upon reviewing the fix, I found myself thinking, &ldquo;If only the original author had used TDD&hellip;&rdquo;<\/li>\n<\/ul>\n<p>I&rsquo;m not trying to be snarky, but this example highlights why the initial claim about TDD&rsquo;s low return on investment for simple functions is flawed.\nEven though the bug was easy to fix, it demanded time and attention from various parties, including users. This could have been easily avoided.<\/p>\n<p>Had the original author employed TDD, the bug would never have been committed to version control. The refactor step would likely have led to a simpler implementation.\nMost importantly, users would have received accurate information, and everyone involved in fixing the bug could have focused on other tasks.<\/p>\n<p>Now that&rsquo;s a high return on investment for TDD!<\/p>\n<h2>Epilogue<\/h2>\n<p>Here is a fixed version of the function:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">fun<\/span><span class=\"w\"> <\/span><span class=\"nf\">describeColors<\/span><span class=\"p\">(<\/span><span class=\"n\">colors<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">Colors<\/span><span class=\"p\">):<\/span><span class=\"w\"> <\/span><span class=\"kt\">String<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">listOfNotNull<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">colors<\/span><span class=\"p\">.<\/span><span class=\"na\">red<\/span><span class=\"o\">?.<\/span><span class=\"na\">takeIf<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"nb\">it<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span><span class=\"o\">?.<\/span><span class=\"na\">let<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;Red&quot;<\/span><span class=\"w\"> <\/span><span class=\"p\">},<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/                added: ^<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">colors<\/span><span class=\"p\">.<\/span><span class=\"na\">green<\/span><span class=\"o\">?.<\/span><span class=\"na\">takeIf<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"nb\">it<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span><span class=\"o\">?.<\/span><span class=\"na\">let<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;Green&quot;<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/                  added: ^<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">).<\/span><span class=\"na\">joinToString<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot; &amp; &quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>The problem with the original function is that, while <code>takeIf<\/code> correctly evaluates to <code>true<\/code> or\n<code>null<\/code> depending on the input, the <code>let<\/code> block is called in any case and doesn&rsquo;t care about the\nargument value. By using the safe call operator <code>?.<\/code>, the <code>let<\/code> block is only called if the\ninput value is <code>true<\/code>.<\/p>\n<p>As noted earlier, the implementation is unnecessarily complex, and there are multiple different\nways to make it simpler, but that&rsquo;s left as an exercise to the reader!<\/p>","category":[{"@attributes":{"term":"Methodology"}},{"@attributes":{"term":"tdd"}},{"@attributes":{"term":"roi"}}]},{"title":"Discovering Nim, part 1","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/discovering-nim-part-1.html","rel":"alternate"}},"published":"2022-12-02T08:00:00+01:00","updated":"2022-12-02T08:00:00+01:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2022-12-02:\/discovering-nim-part-1.html","summary":"<p>For this year&rsquo;s <a href=\"https:\/\/adventofcode.com\/\">Advent of Code<\/a>, I use the programming language <a href=\"https:\/\/nim-lang.org\/\">Nim<\/a>.\nI wrote a little bit about Advent of Code <a href=\"\/advent-of-code-2022-at-last.html\">yesterday<\/a>.<\/p>\n<p>For today&rsquo;s puzzle, I got stuck on something that normally is so trivial that you don&rsquo;t think twice\nabout it&mdash;accessing a variable in the \u2026<\/p>","content":"<p>For this year&rsquo;s <a href=\"https:\/\/adventofcode.com\/\">Advent of Code<\/a>, I use the programming language <a href=\"https:\/\/nim-lang.org\/\">Nim<\/a>.\nI wrote a little bit about Advent of Code <a href=\"\/advent-of-code-2022-at-last.html\">yesterday<\/a>.<\/p>\n<p>For today&rsquo;s puzzle, I got stuck on something that normally is so trivial that you don&rsquo;t think twice\nabout it&mdash;accessing a variable in the outer scope from a function. Suppose we have the following code,\nwhich is a <em>very simplified<\/em> version of the situation I was in:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">i<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span>\n\n<span class=\"k\">proc<\/span><span class=\"w\"> <\/span><span class=\"nf\">inc<\/span><span class=\"p\">(<\/span><span class=\"n\">n<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"nb\">int<\/span><span class=\"p\">):<\/span><span class=\"w\"> <\/span><span class=\"nb\">int<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">i<\/span><span class=\"w\"> <\/span><span class=\"o\">+=<\/span><span class=\"w\"> <\/span><span class=\"n\">n<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">i<\/span>\n\n<span class=\"k\">proc<\/span><span class=\"w\"> <\/span><span class=\"nf\">main<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">const<\/span><span class=\"w\"> <\/span><span class=\"n\">x<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">inc<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">echo<\/span><span class=\"w\"> <\/span><span class=\"n\">x<\/span>\n\n<span class=\"n\">main<\/span><span class=\"p\">()<\/span>\n<\/code><\/pre><\/div>\n\n<p>Anyone who codes Nim will immediately spot the error, of course, but it eluded me for quite a while, <em>even<\/em> though\nthe compiler was very clear:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>test.nim(4, 5) Error: cannot evaluate at compile time: i\n<\/code><\/pre><\/div>\n\n<p>I found this to be a little bit strange&mdash;why would the compiler try to evaluate <code>i<\/code> at compile time?\nThe access is clearly in a <code>proc<\/code>, which gets called at runtime, right? Instead of taking a moment to think a little bit about this, I figured it\nhad to do with the declaration of <code>i<\/code>&mdash;that I somehow had to tell Nim that access to the outer-scope variable\nwas ok, because of some odd scope rules that I hadn&rsquo;t learned about yet. I believe this belongs to the\n&ldquo;I&rsquo;m doing things right, clearly the compiler must be wrong&rdquo; phase of troubleshooting!<\/p>\n<p>No, the problem was this line:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">const<\/span><span class=\"w\"> <\/span><span class=\"n\">x<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">inc<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>By using <code>const<\/code>, the <code>inc<\/code> function was actually evaluated by the compiler as a <a href=\"https:\/\/nim-lang.org\/docs\/manual.html#constants-and-constant-expressions\">constant expression<\/a>,\nand a constant expression, being evaluated at compile time, cannot use a runtime variable.\nWhich the compiler tried to tell me, but I wasn&rsquo;t listening!<\/p>\n<p>This is a silly mistake that I attribute to coding in multiple different languages. I write quite a lot of TypeScript,\nwhere <code>const<\/code> is used for\nconstants, <code>let<\/code> is used for block-scoped variables, and <code>var<\/code> is used for function-scoped variables.\nIn Nim, <code>const<\/code> is used for compile-time constants, <code>let<\/code> for &ldquo;single assignment&rdquo; runtime variables, and <code>var<\/code>\nfor &ldquo;multiple assignment&rdquo; variables.\nClearly, my mind wasn&rsquo;t fully in &ldquo;Nim land,&rdquo; so my fingers typed <code>const<\/code> on auto pilot, and since it wasn&rsquo;t\na concious choice, I didn&rsquo;t connect it to the error.<\/p>\n<p>This reminds me of when I took both French and Spanish at the same time in school. In one class, I accidentally\nmixed the languages when counting (un, deux, tres&hellip;). My French teacher was NOT happy about it, much like the Nim compiler!<\/p>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"aoc"}},{"@attributes":{"term":"coding"}},{"@attributes":{"term":"nim"}}]},{"title":"\ud83c\udf84 Advent of Code 2022, at last! \ud83c\udf84","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/advent-of-code-2022-at-last.html","rel":"alternate"}},"published":"2022-12-01T21:30:00+01:00","updated":"2022-12-01T21:30:00+01:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2022-12-01:\/advent-of-code-2022-at-last.html","summary":"<p>The time has come for another December with the alarm clock set earlier than usual!\nThe yearly <a href=\"https:\/\/adventofcode.com\/\">Advent of Code<\/a> challenge opened its gates to\nthe first puzzle at 00:00 Eastern Time, meaning 06:00 in Sweden.<\/p>\n<p>This is my 6th year, and I&rsquo;m looking forward to a \u2026<\/p>","content":"<p>The time has come for another December with the alarm clock set earlier than usual!\nThe yearly <a href=\"https:\/\/adventofcode.com\/\">Advent of Code<\/a> challenge opened its gates to\nthe first puzzle at 00:00 Eastern Time, meaning 06:00 in Sweden.<\/p>\n<p>This is my 6th year, and I&rsquo;m looking forward to a number of interesting&mdash;and fun&mdash;morning\nchallenges. I try to solve the puzzles before starting the work day, though my brain is a bit mushy\nright after waking up, and it gets progressively harder and harder to actually complete a\npuzzle before it&rsquo;s time to feed the kids and get them to school.<\/p>\n<p>I don&rsquo;t aim for the global leader board (though I&rsquo;ve managed to be in the top 100 for an\nindividual puzzle twice, <a href=\"https:\/\/adventofcode.com\/2018\/day\/20\">day 20, 2018<\/a> and <a href=\"https:\/\/adventofcode.com\/2019\/day\/23\">day 23, 2019<\/a>).\nIt&rsquo;s crazy how fast some people solve non-trivial puzzles - but they have a lot of practice\nand are extremely skilled competitive programmers, of course! The things I like most with\nsolving the puzzles are:<\/p>\n<ul>\n<li>Trying out new programming languages.<\/li>\n<li>Implementing algorithms that I rarely encounter in my day job.<\/li>\n<li>Discussing puzzles and choice of programming language with my colleagues (<em>no spoilers until after a couple of days, and not in the main Slack channel!<\/em>).<\/li>\n<\/ul>\n<p>Choosing programming language is fun, and frustrating! I mostly stick to the same language the entire month,\nso that I get to try the language in multiple different situations that require using different\naspects of the language and different parts of the standard library. The first few days usually\ninvolve a lot of googling to figure out what the language and standard library are capable of, and\ngetting frustrated because something is so easy to do in &lt;insert familiar language here&gt;, but the new\nlanguage does things entirely differently&hellip;<\/p>\n<p>Historically, these are the languages I have used:<\/p>\n<ul>\n<li><a href=\"https:\/\/github.com\/provegard\/adventofcode2017\">2017<\/a> - <a href=\"https:\/\/www.haskell.org\/\">Haskell<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/provegard\/adventofcode2018\">2018<\/a> - <a href=\"https:\/\/elixir-lang.org\/\">Elixir<\/a> and JavaScript, 50\/50<\/li>\n<li><a href=\"https:\/\/github.com\/provegard\/aoc2019\">2019<\/a> - Python<\/li>\n<li><a href=\"https:\/\/github.com\/provegard\/aoc2020\">2020<\/a> - Mainly F#, but I tried <a href=\"https:\/\/www.jsoftware.com\/#\/\">J<\/a> for day 1<\/li>\n<li><a href=\"https:\/\/github.com\/provegard\/aoc2021\">2021<\/a> - Kotlin<\/li>\n<\/ul>\n<p>One of the years, I actually did the first day in Excel together with my son. I don&rsquo;t recall which year, but it worked quite well!<\/p>\n<p><a href=\"https:\/\/github.com\/provegard\/aoc2022\">This year<\/a>, I chickened out a bit (partly because 1st of December just\narrived out of the blue&mdash;where did November go!?) and chose Python for day 1. However, I then re-did the solution\nin <a href=\"https:\/\/nim-lang.org\/\">Nim<\/a> based on a recommendation from a colleague. It appears to be a nice language,\nso I&rsquo;ll probably try it out for at least a couple of days. I found the standard library to be a bit lacking when it comes to functional\naspects, but there&rsquo;s a <a href=\"https:\/\/github.com\/narimiran\/itertools\">port of Python&rsquo;s itertools<\/a> that seems useful!\nI also stumbled across <a href=\"https:\/\/github.com\/nim-lang\/Nim\/wiki\/Nim-for-Python-Programmers\">Nim for Python Programmers<\/a>,\nwhich seems to be a handy reference.<\/p>\n<p>If you haven&rsquo;t tried Advent of Code before, I strongly recommend it! Happy coding! \u2b50<\/p>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"aoc"}},{"@attributes":{"term":"coding"}}]},{"title":"A quick look at Cypress component testing","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/a-quick-look-at-cypress-component-testing.html","rel":"alternate"}},"published":"2022-06-29T08:00:00+02:00","updated":"2022-06-29T08:00:00+02:00","author":{"name":"Per, Andreas, Sebastian"},"id":"tag:programmaticallyspeaking.com,2022-06-29:\/a-quick-look-at-cypress-component-testing.html","summary":"<p>Co-authors: <a href=\"https:\/\/se.linkedin.com\/in\/cederstrom\">Andreas Cederstr\u00f6m<\/a> and <a href=\"https:\/\/se.linkedin.com\/in\/sebastian-porling\">Sebastian Porling<\/a>.<\/p>\n<p><a href=\"https:\/\/www.cypress.io\/\">Cypress<\/a> has recently released support for component testing in their 10.0 release.\nYou read the <a href=\"https:\/\/www.cypress.io\/blog\/2022\/06\/01\/cypress-10-release\/\">announcement here<\/a>.\nWe decided to take a quick look and try it out, to gather some first impressions and see how it can fit into\nour development workflow \u2026<\/p>","content":"<p>Co-authors: <a href=\"https:\/\/se.linkedin.com\/in\/cederstrom\">Andreas Cederstr\u00f6m<\/a> and <a href=\"https:\/\/se.linkedin.com\/in\/sebastian-porling\">Sebastian Porling<\/a>.<\/p>\n<p><a href=\"https:\/\/www.cypress.io\/\">Cypress<\/a> has recently released support for component testing in their 10.0 release.\nYou read the <a href=\"https:\/\/www.cypress.io\/blog\/2022\/06\/01\/cypress-10-release\/\">announcement here<\/a>.\nWe decided to take a quick look and try it out, to gather some first impressions and see how it can fit into\nour development workflow.<\/p>\n<p>The new Cypress app helped us get up and running in a very elegant way. Cypress made it easy for us to write\nthe first test, by providing commands for cloning a demo repository with sample code. Once that was in place,\nwe opened Cypress, selected the web browser to use and were met by a guide for creating the component test configuration\nbased on frontend framework (React or Vue) and bundler (Webpack or Vite). We then proceeded to create the\nfirst component test case.<\/p>\n<p>Writing a component test was just as easy as writing regular Cypress tests. There&rsquo;s no special magic needed\napart from importing the appropriate <code>mount<\/code> function for the selected frontend framework, in our case React.\nUnlike regular Cypress tests, there is no need for starting your application. It&rsquo;s sufficient to import and\nmount you component under test. This is the first test we wrote for the sample component (the base cases\nwere already covered by sample tests):<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">import<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"nx\">mount<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span><span class=\"w\"> <\/span><span class=\"kr\">from<\/span><span class=\"w\"> <\/span><span class=\"s1\">&#39;cypress\/react&#39;<\/span>\n<span class=\"k\">import<\/span><span class=\"w\"> <\/span><span class=\"nx\">Stepper<\/span><span class=\"w\"> <\/span><span class=\"kr\">from<\/span><span class=\"w\"> <\/span><span class=\"s1\">&#39;..\/..\/src\/Stepper&#39;<\/span>\n\n<span class=\"kd\">const<\/span><span class=\"w\"> <\/span><span class=\"nx\">stepperSelector<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s1\">&#39;[data-testid=stepper]&#39;<\/span>\n<span class=\"kd\">const<\/span><span class=\"w\"> <\/span><span class=\"nx\">incrementSelector<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s1\">&#39;[aria-label=increment]&#39;<\/span>\n\n<span class=\"nx\">it<\/span><span class=\"p\">(<\/span><span class=\"s1\">&#39;should be able to step up by one&#39;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">  <\/span><span class=\"nx\">mount<\/span><span class=\"p\">(&lt;<\/span><span class=\"nt\">Stepper<\/span><span class=\"w\"> <\/span><span class=\"p\">\/&gt;)<\/span>\n<span class=\"w\">  <\/span><span class=\"nx\">cy<\/span><span class=\"p\">.<\/span><span class=\"nx\">get<\/span><span class=\"p\">(<\/span><span class=\"nx\">incrementSelector<\/span><span class=\"p\">).<\/span><span class=\"nx\">click<\/span><span class=\"p\">()<\/span>\n<span class=\"w\">  <\/span><span class=\"nx\">cy<\/span><span class=\"p\">.<\/span><span class=\"nx\">get<\/span><span class=\"p\">(<\/span><span class=\"nx\">stepperSelector<\/span><span class=\"p\">).<\/span><span class=\"nx\">should<\/span><span class=\"p\">(<\/span><span class=\"s1\">&#39;contain.text&#39;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">1<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">})<\/span>\n<\/code><\/pre><\/div>\n\n<p>This looks almost identical to a &ldquo;regular&rdquo; unit test with Jest or Karma. The main upside as we see it\nis the instant visual feedback since the test runs in a regular browser. This is what a test run\nmight look like:<\/p>\n<p><center>\n<img src=\"\/images\/cypress-component-test.png\"\/>\n<\/center><\/p>\n<p>Another benefit is that upon test failure you get a screenshot of the problem. This is not a specific\nfeature of component testing, of course, but it&rsquo;s one more advantage compared to a regular unit test.<\/p>\n<p>We noticed that running the component tests was fairly quick, but it does take longer time than running\ntypical component unit tests. For example, running 120 tests took 7 seconds with Cypress <em>open<\/em> and 11 seconds with Cypress <em>run<\/em>.<\/p>\n<p>As always, using demo code is simple since everything is laid out for you. When we tried to write a\ncomponent test in one of our existing projects, it became obvious what we already knew:<\/p>\n<blockquote>\n<p>The first test is always the hardest!<\/p>\n<\/blockquote>\n<p>In the project we use Parcel, and since Cypress only supports Webpack and Vite, we had to\nmigrate the bundler configuration first. Furthermore (and this is not a Cypress problem of course),\nwe were faced with a number of errors that turned out to be caused by the lack of a router context.\nOnce we wrapped the component in a router context, we could proceed:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">import<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"nx\">PageHeader<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span><span class=\"w\"> <\/span><span class=\"kr\">from<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;..\/..\/src\/Components\/PageHeader&quot;<\/span>\n<span class=\"k\">import<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"nx\">mount<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span><span class=\"w\"> <\/span><span class=\"kr\">from<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;cypress\/react&quot;<\/span>\n<span class=\"k\">import<\/span><span class=\"w\"> <\/span><span class=\"nx\">React<\/span><span class=\"w\"> <\/span><span class=\"kr\">from<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;react&quot;<\/span>\n<span class=\"k\">import<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"nx\">MemoryRouter<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"nx\">Routes<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"nx\">Route<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span><span class=\"w\"> <\/span><span class=\"kr\">from<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;react-router-dom&quot;<\/span>\n\n<span class=\"nx\">describe<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;PageHeader&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">it<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;Can be mounted&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"nx\">mount<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">            <\/span><span class=\"p\">&lt;<\/span><span class=\"nt\">MemoryRouter<\/span><span class=\"w\"> <\/span><span class=\"na\">initialEntries<\/span><span class=\"o\">=<\/span><span class=\"p\">{[<\/span><span class=\"s2\">&quot;\/&quot;<\/span><span class=\"p\">]}&gt;<\/span>\n<span class=\"w\">                <\/span><span class=\"p\">&lt;<\/span><span class=\"nt\">Routes<\/span><span class=\"p\">&gt;<\/span>\n<span class=\"w\">                    <\/span><span class=\"p\">&lt;<\/span><span class=\"nt\">Route<\/span>\n<span class=\"w\">                        <\/span><span class=\"na\">path<\/span><span class=\"o\">=<\/span><span class=\"p\">{<\/span><span class=\"s2\">&quot;\/&quot;<\/span><span class=\"p\">}<\/span>\n<span class=\"w\">                        <\/span><span class=\"na\">element<\/span><span class=\"o\">=<\/span><span class=\"p\">{&lt;<\/span><span class=\"nt\">PageHeader<\/span><span class=\"w\"> <\/span><span class=\"p\">\/&gt;}<\/span>\n<span class=\"w\">                    <\/span><span class=\"p\">\/&gt;<\/span>\n<span class=\"w\">                <\/span><span class=\"p\">&lt;\/<\/span><span class=\"nt\">Routes<\/span><span class=\"p\">&gt;<\/span>\n<span class=\"w\">            <\/span><span class=\"p\">&lt;\/<\/span><span class=\"nt\">MemoryRouter<\/span><span class=\"p\">&gt;<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">})<\/span>\n<span class=\"p\">})<\/span>\n<\/code><\/pre><\/div>\n\n<p>Cypress presented the errors clearly, so it was quite\neasy to understand what was going on. Had we used Cypress component testing from the start in a TDD fashion, we would have\nbeen faced with the same problem, but since TDD encourages code to be written in small steps, we&rsquo;d have\nseen the exact cause immediately. <em>Test-after is always tricky<\/em>!<\/p>\n<p>In conclusion, we think this is an interesting way of writing tests for your applications components. The visual feedback and the ability to use browser developer tools is a great benefit.\nWe definitely will be using Cypress component testing in real projects in the future. However, due to longer execution time compared to regular unit testing we will keep writing the bulk of our tests as unit tests.<\/p>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"ui-testing"}},{"@attributes":{"term":"cypress"}}]},{"title":"Consequences of array covariance in C#","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/consequences-of-array-covariance-in-csharp.html","rel":"alternate"}},"published":"2021-10-22T18:00:00+02:00","updated":"2021-10-22T18:00:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2021-10-22:\/consequences-of-array-covariance-in-csharp.html","summary":"<p>In today&rsquo;s post, I&rsquo;ll talk about <em>array covariance<\/em> in C#, how it hid a bug\nin code that was covered by a passing unit test (*gasp*), and some ideas\nfor how to avoid such bugs.<\/p>\n<h2>What is covariance?<\/h2>\n<p>In computer science, <em>variance<\/em> has to do with how complex \u2026<\/p>","content":"<p>In today&rsquo;s post, I&rsquo;ll talk about <em>array covariance<\/em> in C#, how it hid a bug\nin code that was covered by a passing unit test (*gasp*), and some ideas\nfor how to avoid such bugs.<\/p>\n<h2>What is covariance?<\/h2>\n<p>In computer science, <em>variance<\/em> has to do with how complex types relate to each other based on\nthe relation between their components. For example, consider the two types <code>Car<\/code> and <code>Vehicle<\/code>. A car is a vehicle,\nso the relationship can be expressed in code as:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">Car<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">Vehicle<\/span>\n<span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">...<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Now that there is a relation between the two types&mdash;<code>Car<\/code> is a subtype of <code>Vehicle<\/code>&mdash;what\nis the relation between the following types?<\/p>\n<ul>\n<li><code>IList&lt;Car&gt;<\/code> and <code>IList&lt;Vehicle&gt;<\/code>?<\/li>\n<li><code>Action&lt;Car&gt;<\/code> and <code>Action&lt;Vehicle&gt;<\/code>?<\/li>\n<\/ul>\n<p>This is where variance rules come in&mdash;they define how such types relate.<\/p>\n<p>Covariance, then, means that two complex types are related to each other in the same way as\ntheir components. We&rsquo;ll come back to the built-in .NET types in a moment, but for now\nlet&rsquo;s consider a custom interface, <code>IParkingSpace&lt;T&gt;<\/code>. If this interface is covariant on <code>T<\/code>,\nthen <code>IParkingSpace&lt;Car&gt;<\/code> is a subtype of <code>IParkingSpace&lt;Vehicle&gt;<\/code>, because <code>Car<\/code> is a subtype of <code>Vehicle<\/code>.\nPut differently, parking space covariance means that if you have a parking space for cars, you can say that it is a parking space for\nvehicles. As you can imagine, whether or not this holds true in real life depends very much on what you intend\nto do with the parking space. Saying &ldquo;yes, a vehicle is parked&rdquo; is fine, but &ldquo;let&rsquo;s park an arbitrary vehicle&rdquo;\nwill likely not turn out well.<\/p>\n<p>Covariance on a type parameter is declared as follows:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">interface<\/span><span class=\"w\"> <\/span><span class=\"n\">IParkingSpace<\/span><span class=\"o\">&lt;<\/span><span class=\"k\">out<\/span><span class=\"w\"> <\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span>\n<\/code><\/pre><\/div>\n\n<p>One might ask why the keyword to specify covariance is <code>out<\/code>. How does that make sense?\nThe answer is that is has to do with how the type <code>T<\/code> is used inside the interface. If <code>T<\/code>\nonly occurs as the <em>return type<\/em> of members of the interface, then <code>T<\/code> only occurs &ldquo;on the way out&rdquo;:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>                      +------------+\n    Arguments in ---&gt; |   method   | --&gt; Return value out\n                      +------------+\n<\/code><\/pre><\/div>\n\n<p>This means that we can have:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">interface<\/span><span class=\"w\"> <\/span><span class=\"n\">IParkingSpace<\/span><span class=\"o\">&lt;<\/span><span class=\"k\">out<\/span><span class=\"w\"> <\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span>\n<span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">T<\/span><span class=\"w\"> <\/span><span class=\"nf\">GetCurrentlyParked<\/span><span class=\"p\">();<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>But we <em>cannot<\/em> have:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">interface<\/span><span class=\"w\"> <\/span><span class=\"n\">IParkingSpace<\/span><span class=\"o\">&lt;<\/span><span class=\"k\">out<\/span><span class=\"w\"> <\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span>\n<span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ THIS DOES NOT COMPILE!<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">Park<\/span><span class=\"p\">(<\/span><span class=\"n\">T<\/span><span class=\"w\"> <\/span><span class=\"n\">parkee<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Since we have specified <code>out T<\/code> to indicate covariance on type <code>T<\/code>, we cannot use <code>T<\/code> as an input\nparameter, only as a return type.<\/p>\n<blockquote>\n<p>Side note: Confusingly, covariant <code>T<\/code> cannot appears as an <code>out<\/code> parameter of a method. For example,\n<code>void GetCurrentlyParked(out T parked)<\/code> doesn&rsquo;t compile.<\/p>\n<p>Side note 2: If the return type of a member is a complex type, then that complex type must also be covariant\non <code>T<\/code>.<\/p>\n<\/blockquote>\n<p>Ok, but so far we have at best specified a mnemonic for covariance being declared using <code>out<\/code>. Why is it\nimportant that covariance requires <code>T<\/code> to appear as return type only?<\/p>\n<p>To understand that, consider a non-variant version of the type <code>IParkingSpace&lt;T&gt;<\/code>:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">interface<\/span><span class=\"w\"> <\/span><span class=\"n\">IParkingSpace<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span>\n<span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">T<\/span><span class=\"w\"> <\/span><span class=\"nf\">GetCurrentlyParked<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">Park<\/span><span class=\"p\">(<\/span><span class=\"n\">T<\/span><span class=\"w\"> <\/span><span class=\"n\">parkee<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Since <code>T<\/code> isn&rsquo;t qualified with <code>out<\/code>, we can use it both as a return type and as a parameter type.\nThen consider this piece of incorrect code:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">IParkingSpace<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Car<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">parkingSpaceForCars<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">ParkingSpace<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Car<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">();<\/span>\n<span class=\"n\">IParkingSpace<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Vehicle<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">parkingSpaceForAnyVehicle<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">(<\/span><span class=\"n\">IParkingSpace<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Vehicle<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"n\">parkingSpaceForCars<\/span><span class=\"p\">;<\/span>\n\n<span class=\"n\">parkingSpaceForAnyVehicle<\/span><span class=\"p\">.<\/span><span class=\"n\">Park<\/span><span class=\"p\">(<\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">FreightTrain<\/span><span class=\"p\">());<\/span><span class=\"w\"> <\/span><span class=\"c1\">\/\/ FreightTrain is a Vehicle<\/span>\n<\/code><\/pre><\/div>\n\n<p>Do you see the problem? We cast the parking space for cars to a parking space that accepts\nany vehicle, and then try to park a freight train there. Just as in real life, that won&rsquo;t\nend well!<\/p>\n<p>It turns out that the code won&rsquo;t even execute successfully. The cast in the second statement will fail and throw an <code>InvalidCastException<\/code>,\nthereby preventing the illegal <code>Park<\/code> call, precisely because the interface in this example is non-variant.<\/p>\n<p>Since compile-time errors are infinitely better than runtime errors, we&rsquo;d like to have a mechanism\nthat allows the compiler to prevent us from making mistakes like the above. This is why declaring\ncovariance on a complex type is useful!<\/p>\n<blockquote>\n<p>In the example above, if we declare <code>IParkingSpace<\/code> to be\ncovariant on <code>T<\/code>, the compiler will prevent us from adding the <code>Park<\/code> method, and furthermore\nthe cast from <code>IParkingSpace&lt;Car&gt;<\/code> to <code>IParkingSpace&lt;Vehicle&gt;<\/code> will succeed.<\/p>\n<\/blockquote>\n<h2>.NET collection type covariance<\/h2>\n<p>In .NET we have two commonly used collection types, <code>IList&lt;T&gt;<\/code> and <code>IEnumerable&lt;T&gt;<\/code>. The former is read\/write\nand the latter is read-only. Since <code>IList&lt;T&gt;<\/code> is read\/write, it follows that <code>T<\/code> must appear as both return\ntype and parameter type of methods in the interface, and that the interface therefore cannot be covariant on <code>T<\/code>.<\/p>\n<p>We can confirm that <code>IList&lt;T&gt;<\/code> is not covariant on <code>T<\/code>:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">IList<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Car<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">cars<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">List<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Car<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">();<\/span>\n<span class=\"n\">IList<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Vehicle<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">vehicles<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">cars<\/span><span class=\"w\"> <\/span><span class=\"k\">as<\/span><span class=\"w\"> <\/span><span class=\"n\">IList<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Vehicle<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">;<\/span>\n<span class=\"n\">Console<\/span><span class=\"p\">.<\/span><span class=\"n\">WriteLine<\/span><span class=\"p\">(<\/span><span class=\"s\">$&quot;Is IList&lt;T&gt; covariant? {vehicles != null}&quot;<\/span><span class=\"p\">);<\/span>\n<\/code><\/pre><\/div>\n\n<p>(Remember, a direct cast throws <code>InvalidCastException<\/code> for an invalid cast, whereas the <code>as<\/code> operator returns <code>null<\/code>.)<\/p>\n<p>If you run the snippet above, it will print:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>Is IList&lt;T&gt; covariant? False\n<\/code><\/pre><\/div>\n\n<p>Similarly, we can confirm that <code>IEnumerable&lt;T&gt;<\/code> <em>is<\/em> covariant on <code>T<\/code>:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">IEnumerable<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Car<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">cars<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">List<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Car<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">();<\/span>\n<span class=\"n\">IEnumerable<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Vehicle<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">vehicles<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">cars<\/span><span class=\"w\"> <\/span><span class=\"k\">as<\/span><span class=\"w\"> <\/span><span class=\"n\">IEnumerable<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Vehicle<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">;<\/span>\n<span class=\"n\">Console<\/span><span class=\"p\">.<\/span><span class=\"n\">WriteLine<\/span><span class=\"p\">(<\/span><span class=\"s\">$&quot;Is IEnumerable&lt;T&gt; covariant? {vehicles != null}&quot;<\/span><span class=\"p\">);<\/span>\n<\/code><\/pre><\/div>\n\n<p>This snippet will print:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>Is IEnumerable&lt;T&gt; covariant? True\n<\/code><\/pre><\/div>\n\n<p>Great! Everything seems to work as expected. Next up, <em>array covariance<\/em>!<\/p>\n<h2>Array covariance<\/h2>\n<p>In C#, an array <code>T[]<\/code> is covariant on <code>T<\/code>, except for value types.\nYou can read up on the details <a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/csharp\/language-reference\/language-specification\/arrays#array-covariance\">here<\/a>, but for now let&rsquo;s consider an example similar to the previous ones:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">Car<\/span><span class=\"p\">[]<\/span><span class=\"w\"> <\/span><span class=\"n\">cars<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">Car<\/span><span class=\"p\">[<\/span><span class=\"m\">1<\/span><span class=\"p\">];<\/span>\n<span class=\"n\">Vehicle<\/span><span class=\"p\">[]<\/span><span class=\"w\"> <\/span><span class=\"n\">vehicles<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">cars<\/span><span class=\"w\"> <\/span><span class=\"k\">as<\/span><span class=\"w\"> <\/span><span class=\"n\">Vehicle<\/span><span class=\"p\">[];<\/span>\n\n<span class=\"n\">Console<\/span><span class=\"p\">.<\/span><span class=\"n\">WriteLine<\/span><span class=\"p\">(<\/span><span class=\"s\">$&quot;Is T[] covariant? {vehicles != null}&quot;<\/span><span class=\"p\">);<\/span>\n<\/code><\/pre><\/div>\n\n<p>This snippet will print:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>Is T[] covariant? True\n<\/code><\/pre><\/div>\n\n<p>Fantastic! Arrays behave just like <code>IEnumerable&lt;T&gt;<\/code> in this case, it appears.<\/p>\n<p>So, why does C# have array covariance? Well, let&rsquo;s say that we want to write a function that\ncounts the number of non-null objects in an array, but we live in the past where <em>generics have not yet been introduced in the language<\/em>.\nWhat would the signature of such a function look like? To avoid having to create an infinite number of overloads,\nit makes sense to go for:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"kt\">int<\/span><span class=\"w\"> <\/span><span class=\"nf\">CountNonNullObjects<\/span><span class=\"p\">(<\/span><span class=\"kt\">object<\/span><span class=\"p\">[]<\/span><span class=\"w\"> <\/span><span class=\"n\">objects<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>Thanks to array covariance, it&rsquo;s possible to pass almost any kind of array to the function, for example <code>Car[]<\/code>.\nAgain, array covariance doesn&rsquo;t apply to value types, so it won&rsquo;t be possible to pass <code>int[]<\/code>, for example.<\/p>\n<p>So, at this point we know that <code>IList&lt;T&gt;<\/code> is not covariant on <code>T<\/code>, but <code>T[]<\/code> is. But wait a minute&mdash;doesn&rsquo;t\nan array <code>T[]<\/code> implement <code>IList&lt;T&gt;<\/code>??<\/p>\n<h2><code>T[]<\/code> implements <code>IList&lt;T&gt;<\/code><\/h2>\n<p>Yes, yes it does! We can write:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">IList<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Car<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">cars<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">Car<\/span><span class=\"p\">[<\/span><span class=\"m\">1<\/span><span class=\"p\">];<\/span>\n<\/code><\/pre><\/div>\n\n<p>Now, this is interesting from a covariance perspective. What happens if we run the following?<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">IList<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Car<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">cars<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">Car<\/span><span class=\"p\">[<\/span><span class=\"m\">1<\/span><span class=\"p\">];<\/span>\n<span class=\"n\">IList<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Vehicle<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">vehicles<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">cars<\/span><span class=\"w\"> <\/span><span class=\"k\">as<\/span><span class=\"w\"> <\/span><span class=\"n\">IList<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Vehicle<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">;<\/span>\n<span class=\"n\">Console<\/span><span class=\"p\">.<\/span><span class=\"n\">WriteLine<\/span><span class=\"p\">(<\/span><span class=\"s\">$&quot;Is T[] disguised as IList&lt;T&gt; covariant? {vehicles != null}&quot;<\/span><span class=\"p\">);<\/span>\n<\/code><\/pre><\/div>\n\n<p>The result is:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>Is T[] disguised as IList&lt;T&gt; covariant? True\n<\/code><\/pre><\/div>\n\n<p>In other words, the fact that an array is covariant takes precedence over the fact that\n<code>IList&lt;T&gt;<\/code> isn&rsquo;t. This is a bit problematic, because it means that the statement\n<em>IList&lt;T&gt; is not covariant on <code>T<\/code><\/em> is demonstrably false&mdash;it depends on the list\nimplementation.<\/p>\n<p>And this, dear reader, is the source of the aforementioned bug.<\/p>\n<h2>The bug<\/h2>\n<p>The bug was introduced in a proxy function, initially similar to the following:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">IList<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Vehicle<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">GetVehicles<\/span><span class=\"p\">()<\/span>\n<span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">Configuration<\/span><span class=\"w\"> <\/span><span class=\"n\">configuration<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">GetConfiguration<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">IList<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Vehicle<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">vehicles<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">configuration<\/span><span class=\"p\">.<\/span><span class=\"n\">Vehicles<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">vehicles<\/span><span class=\"p\">;<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>An important detail is how <code>Configuration<\/code> was defined:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">Configuration<\/span>\n<span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">...<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">IList<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Vehicle<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">Vehicles<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"k\">get<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"k\">set<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">...<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>One of the test cases was similar to this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"na\">[Test]<\/span>\n<span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">Should_return_vehicles<\/span><span class=\"p\">()<\/span>\n<span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">Configuration<\/span><span class=\"w\"> <\/span><span class=\"n\">configuration<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">Configuration<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">Vehicles<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">Vehicle<\/span><span class=\"p\">[]<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"n\">Volvo<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Tesla<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">};<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">VehicleProxy<\/span><span class=\"w\"> <\/span><span class=\"n\">proxy<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">VehicleProxy<\/span><span class=\"p\">(<\/span><span class=\"n\">configuration<\/span><span class=\"p\">);<\/span>\n\n<span class=\"w\">    <\/span><span class=\"n\">IList<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">string<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">makes<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">proxy<\/span><span class=\"p\">.<\/span><span class=\"n\">GetVehicles<\/span><span class=\"p\">().<\/span><span class=\"n\">Select<\/span><span class=\"p\">(<\/span><span class=\"n\">v<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">v<\/span><span class=\"p\">.<\/span><span class=\"n\">Name<\/span><span class=\"p\">).<\/span><span class=\"n\">ToList<\/span><span class=\"p\">();<\/span>\n\n<span class=\"w\">    <\/span><span class=\"n\">Assert<\/span><span class=\"p\">.<\/span><span class=\"n\">That<\/span><span class=\"p\">(<\/span><span class=\"n\">makes<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Is<\/span><span class=\"p\">.<\/span><span class=\"n\">EqualTo<\/span><span class=\"p\">(<\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span><span class=\"p\">[]<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;Volvo&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;Tesla&quot;<\/span><span class=\"w\"> <\/span><span class=\"p\">}));<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>At some point, there was a need to change the signature of <code>Configuration.Vehicles<\/code> so that it was\na list of <code>Car<\/code>s instead of <code>Vehicle<\/code>s:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">Configuration<\/span>\n<span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">...<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">IList<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Car<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">Vehicles<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"k\">get<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"k\">set<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">...<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>The test case was updated accordingly:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"na\">[Test]<\/span>\n<span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">Should_return_vehicles<\/span><span class=\"p\">()<\/span>\n<span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">Configuration<\/span><span class=\"w\"> <\/span><span class=\"n\">configuration<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">Configuration<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">Vehicles<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">Car<\/span><span class=\"p\">[]<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"n\">Volvo<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Tesla<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span><span class=\"w\"> <\/span><span class=\"c1\">\/\/ &lt;== change initialization here<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">};<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">VehicleProxy<\/span><span class=\"w\"> <\/span><span class=\"n\">proxy<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">VehicleProxy<\/span><span class=\"p\">(<\/span><span class=\"n\">configuration<\/span><span class=\"p\">);<\/span>\n\n<span class=\"w\">    <\/span><span class=\"n\">IList<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">string<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">makes<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">proxy<\/span><span class=\"p\">.<\/span><span class=\"n\">GetVehicles<\/span><span class=\"p\">().<\/span><span class=\"n\">Select<\/span><span class=\"p\">(<\/span><span class=\"n\">v<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">v<\/span><span class=\"p\">.<\/span><span class=\"n\">Name<\/span><span class=\"p\">).<\/span><span class=\"n\">ToList<\/span><span class=\"p\">();<\/span>\n\n<span class=\"w\">    <\/span><span class=\"n\">Assert<\/span><span class=\"p\">.<\/span><span class=\"n\">That<\/span><span class=\"p\">(<\/span><span class=\"n\">makes<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Is<\/span><span class=\"p\">.<\/span><span class=\"n\">EqualTo<\/span><span class=\"p\">(<\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span><span class=\"p\">[]<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;Volvo&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;Tesla&quot;<\/span><span class=\"w\"> <\/span><span class=\"p\">}));<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>And finally, the proxy function was updated:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">IList<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Vehicle<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">GetVehicles<\/span><span class=\"p\">()<\/span>\n<span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">Configuration<\/span><span class=\"w\"> <\/span><span class=\"n\">configuration<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">GetConfiguration<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">IList<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Vehicle<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">vehicles<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">configuration<\/span><span class=\"p\">.<\/span><span class=\"n\">Vehicles<\/span><span class=\"w\"> <\/span><span class=\"k\">as<\/span><span class=\"w\"> <\/span><span class=\"n\">IList<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Vehicle<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"c1\">\/\/ &lt;== add cast here<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">vehicles<\/span><span class=\"p\">;<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Do you see the problem? The test case didn&rsquo;t&mdash;it was as green as it could ever be!<\/p>\n<p>As we have seen before, <code>IList&lt;T&gt;<\/code> is <em>not covariant<\/em>, so the cast to <code>IList&lt;Vehicle&gt;<\/code> is simply not valid.\nWhen the code was run in production, the <code>as<\/code> operator returned <code>null<\/code>, and we got a <code>NullReferenceException<\/code>\ndownstream.<\/p>\n<p>But why didn&rsquo;t the test case detect the problem? It&rsquo;s because of this property initialization:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">Vehicles<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">Car<\/span><span class=\"p\">[]<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"n\">Volvo<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Tesla<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Since arrays are covariant even when treated as <code>IList&lt;T&gt;<\/code>, the cast succeeded when\n<code>GetVehicles<\/code> was excercised by the test case. <strong>However, in the real code, the property was initialized\nusing a <code>List&lt;Car&gt;<\/code> instance, in which case the non-variance of <code>IList&lt;T&gt;<\/code> applied and the cast failed.<\/strong><\/p>\n<h2>Lessons learned<\/h2>\n<p><strong>Avoid <code>IList&lt;T&gt;<\/code> casting<\/strong><\/p>\n<p>In general, casting that involves <code>IList&lt;T&gt;<\/code> must be carefully scrutinized.<\/p>\n<p>Unless there are special performance and\/or memory requirements, using the LINQ method <a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/api\/system.linq.enumerable.cast?view=net-5.0\"><code>Cast<\/code><\/a> is a lot safer:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">IList<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Vehicle<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">vehicles<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">configuration<\/span><span class=\"p\">.<\/span><span class=\"n\">Vehicles<\/span><span class=\"p\">.<\/span><span class=\"n\">Cast<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Vehicle<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">().<\/span><span class=\"n\">ToList<\/span><span class=\"p\">();<\/span>\n<\/code><\/pre><\/div>\n\n<p><a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/api\/system.linq.enumerable.oftype?view=net-5.0\"><code>OfType<\/code><\/a> is an option\nas well; it depends on what you know about the element types.<\/p>\n<p><strong>Use good property types<\/strong><\/p>\n<p>Using type <code>IList&lt;...&gt;<\/code> for a property has a number of problems, for example that the caller\ncan grab the list and mutate it. To prevent that, you have to ensure the returned list is read-only.<\/p>\n<p>A much better option is to use <code>IEnumerable&lt;...&gt;<\/code>, which is both read-only in itself and covariant\non the element type&mdash;and thus safe to cast.<\/p>\n<p><strong>Enable nullable references?<\/strong><\/p>\n<p>Since the <code>as<\/code> operator may return <code>null<\/code>, it can be argued that the function above should be\nchanged further:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"err\">#<\/span><span class=\"n\">nullable<\/span><span class=\"w\"> <\/span><span class=\"n\">enable<\/span><span class=\"w\">               <\/span><span class=\"c1\">\/\/ &lt;== enable nullable reference types<\/span>\n<span class=\"n\">IList<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Vehicle<\/span><span class=\"o\">&gt;?<\/span><span class=\"w\"> <\/span><span class=\"n\">GetVehicles<\/span><span class=\"p\">()<\/span><span class=\"w\">  <\/span><span class=\"c1\">\/\/ &lt;== add ? to the return type<\/span>\n<span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">Configuration<\/span><span class=\"w\"> <\/span><span class=\"n\">configuration<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">GetConfiguration<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">IList<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Vehicle<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">vehicles<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">configuration<\/span><span class=\"p\">.<\/span><span class=\"n\">Vehicles<\/span><span class=\"w\"> <\/span><span class=\"k\">as<\/span><span class=\"w\"> <\/span><span class=\"n\">IList<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Vehicle<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">vehicles<\/span><span class=\"p\">;<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>While this makes the code more <em>correct<\/em>, it wouldn&rsquo;t have helped in our case. The use of a nullable reference type\nwould have propagated downstream, and at some point <code>null<\/code> would likely have been converted to an empty\nlist, so we would still have a functional breakage (albeit an exception-less one).<\/p>\n<p><strong>Test case setup must be true to the production code setup<\/strong><\/p>\n<p>This is the most important lesson learned!<\/p>\n<p>You may have thought about this in the context of mocks, stubs and fakes. If you use\na mock with a behavior that differs even the slightest from the code it mimics, the\nusefulness of your tests will suffer.<\/p>\n<p>As we\ncan see here, the principle is also important when it comes to choosing the implementation type\nfor an interface. Had the test case used <code>List&lt;Car&gt;<\/code>, the problem would have been spotted immediately.<\/p>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"csharp"}},{"@attributes":{"term":"covariance"}},{"@attributes":{"term":"cast"}}]},{"title":"TDD and prototyping\u2014a love story?","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/tdd-and-prototyping-a-love-story.html","rel":"alternate"}},"published":"2018-07-10T08:40:00+02:00","updated":"2018-07-10T08:40:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2018-07-10:\/tdd-and-prototyping-a-love-story.html","summary":"<p>Can you combine Test-Driven Development (TDD) with prototyping?\nHow can you write tests for functionality that is largely unknown?\nWhere do you even start if you&rsquo;re on unfamiliar ground and you need\nto explore to learn about possibilities and constraints? \n<em>How can you write tests when you don&rsquo;t \u2026<\/em><\/p>","content":"<p>Can you combine Test-Driven Development (TDD) with prototyping?\nHow can you write tests for functionality that is largely unknown?\nWhere do you even start if you&rsquo;re on unfamiliar ground and you need\nto explore to learn about possibilities and constraints? \n<em>How can you write tests when you don&rsquo;t know which code you need to write<\/em>?<\/p>\n<p>These are questions I often hear from people who don&rsquo;t regularly\npractice TDD. Sometimes rhetorically as an excuse to stay away from TDD,\nbut taken seriously the questions are very\nrelevant and interesting to discuss! Due to the nature of software, there\nwill always be unknowns. Software development is an activity\nwhere all stakeholders learn more and more about the domain and infrastructure\nas time passes. It is important to be able to work systematically in such an environment.<\/p>\n<p>People who work with me know that I think TDD is extremely important\n(though they&rsquo;d probably use stronger words). Not in a zealous way, because\nTDD is just a means to an end (it&rsquo;s in the name&mdash;it Drives Development). \nBut I do believe it to be one of the most important tools a software developer can\nuse for producing high-quality code.<\/p>\n<p>I rarely deploy untested code,\nbut if I do I always get a feeling that bad things will happen. Something like this:<\/p>\n<p><center>\n<img src=\"\/images\/oh-no.webp\"\/>\n<\/center><\/p>\n<p>So yeah, I use TDD a lot, and I really like the level of control it gives \nme and my colleagues who work with (or will work with) the code. <\/p>\n<blockquote>\n<p>Topic for an \nupcoming blog post: How TDD makes you a better team player!<\/p>\n<\/blockquote>\n<p>That said, I also from time to time end up in a situation where I need to\ndo exploratory development. It can be that I need to integrate with a \nservice that is sparsely documented, or that I need to develop a new feature but\nit&rsquo;s not obvious where in the stack it should live. In such cases, using\nTDD can be non-trivial.<\/p>\n<p>Here&rsquo;s what I usually do!<\/p>\n<h2>Production-ready prototype<\/h2>\n<p>I <em>don&rsquo;t<\/em> do this. I just want to mention it \nas a contrast to the other things I talk about.<\/p>\n<p>Production-ready prototype is an oxymoron. A prototype is by definition something that is\nonly ever a first version and never the final version. (Yes, software is never &ldquo;final,&rdquo; but\nhere I mean final for production.)<\/p>\n<p>I see direct productization of prototypes as an anti pattern \nthat typically happens\nwhen you create a prototype that works sufficiently well that people around\nyou (*cough* project managers *cough*) mark the feature as complete and\ndecide to ship it.<\/p>\n<p>This is bad. A prototype needs to be <em>formalized<\/em> in some way. When a prototype is formalized,\nit stops being a prototype and instead becomes production-ready code.<\/p>\n<h2>Throw-away prototyping<\/h2>\n<p>Actually, I do this a lot less than I&rsquo;d like to. With throw-away prototyping,\nyou build a prototype as a pure learning exercise, then throw the prototype\naway. There&rsquo;s no need to use TDD, because the resulting code will never\nsee a production server.<\/p>\n<p>The beauty of throw-away prototyping is that mental constraints (resulting \nfrom ideas about production quality) disappear, but first and foremost that\nthe second time you do something it usually becomes a lot better than the\nfirst time! If you have ever lost your code in a computer crash, you&rsquo;re well aware\nof this.<\/p>\n<p>After throwing away the prototype, there&rsquo;s no excuse for not using TDD to\nbuild the feature\/integration\/whatever for real. Most&mdash;if not all&mdash;unknowns\nshould be gone. If they are not, perhaps more prototyping is needed.<\/p>\n<p>Throw-away prototyping\nis an excellent way to formalize a prototype, though the basis for\nformalization is the <em>learnings<\/em> achieved through the prototyping activity\nrather than the prototype code itself.<\/p>\n<h2>High-level blackbox test<\/h2>\n<p>I do this a lot. Regardless of the nature of the thing I&rsquo;m going to build,\nand regardless of the amount of exploration needed, I always write one\nhigh-level test. Some important characteristics of such a test are:<\/p>\n<ul>\n<li>It must be completely implementation independent (which follows from it\n  being blackbox, but it&rsquo;s worth pointing out).<\/li>\n<li>It should encode a central and representative happy path. \n  Failure modes and edge cases come later.<\/li>\n<li>It doesn&rsquo;t need to contain an actual assertion. It&rsquo;s perfectly fine for it to just\n  produce console output, such as performance numbers or the transformed\/processed\n  response from a service call.<\/li>\n<li>It is in itself a prototype, meaning that it will not remain in the\n  test suite after prototype formalization.<\/li>\n<\/ul>\n<p>To me, such a test serves three very important purposes:<\/p>\n<ol>\n<li>It keeps me on track and in <em>some way<\/em> indicates when I have reached\n   my initial goal (even if that goal might be a bit lofty, e.g. when I\n   do performance optimizations).<\/li>\n<li>It allows me to avoid the slow and tedious run-click-crash<sup><a href=\"#run_click_crash\">1<\/a><\/sup> approach. A test is quick to run and makes \n   development a lot more pleasant!<\/li>\n<li>It demonstrates some degree of testability, which is important when\n   the prototype will be formalized later.<\/li>\n<\/ol>\n<p>As an example, I recently did some robustness improvements in code that\ntalks to a Cassandra database. I had no idea which exceptions I would get\nin various problematic situations (such as network outage) and I only had\na vague idea about how a connection problem would affect the existing\noperation-level retry behavior. I ended up writing a test that fired off\na steady stream of operations against the storage facade and in the end\nprinted some metrics and verified that all operations went through. As an\nadded bonus, writing that test forced me to think about the best way to\nsimulate load on the component in question.<\/p>\n<p>Can you use a small program (&ldquo;main method&rdquo;) instead of a test? Sure, absolutely!\nA benefit with a test, however, is that it lives in a test context,\nwhich means that all the constraints (test dependencies, test data, etc.) that\ninevitably will apply later on are present already.<\/p>\n<p>It should be noted that a high-level blackbox test is very useful also if the\nprototype is meant to be thrown away. Bullets 1 and 2 above still apply.<\/p>\n<h2>Test-Driven Uncommenting<\/h2>\n<p>This is something I like a lot, because it is like a gentle version of\nthrow-away prototyping. I need to work on the name a bit, but the general idea is:<\/p>\n<ol>\n<li>Build the prototype. Use a high-level blackbox test to guide development.<\/li>\n<li>Comment out all prototype code.<\/li>\n<li>Use TDD to demonstrate the need for the commented-out code, uncommenting\n   as you go.<\/li>\n<\/ol>\n<p>The important thing here is that the TDD activity can be carried out by the book. Normally, using Test-After Development is very dangerous since the resulting tests\nare very likely (at least in my experience) to be buggy (not detect regressions) and\/or\nto test the wrong things. With Test-Driven Uncommenting (or TDU), you get the correct red-green-refactor cycle:<\/p>\n<ol>\n<li>Write a test (always start with a base case) that initially fails.<\/li>\n<li>Uncomment the smallest amount of code necessary to make the test pass,\n   preferrably a single line. Thus, the test must prove that the code is\n   necessary. If it cannot prove it, then the code might be a candidate\n   for removal.<\/li>\n<li>Refactor the uncommented code as necessary.<\/li>\n<li>Go back to step 1.<\/li>\n<\/ol>\n<p>When I do this, I usually discover two things. First, that the prototype code\ncontains bugs&mdash;sometimes subtle, sometimes obvious.\nSecond, that it is convoluted and contains unnecessary\/redundant code. The end result is typically something that\nvaguely resembles the prototype but a lot slimmer and of course very much\nmore stable.<\/p>\n<p>A crucial mindset to have when writing tests in this fashion is that the\ntests should drive the design and implementation of the production code <em>in the correct\ndirection<\/em>, as opposed to just parroting the design and implementation of the\nprototype. The prototype code is most likely\na bit unclean and rough around the edges, and we definitely don&rsquo;t want\nto write tests that reinforce that.<\/p>\n<p>Put differently, <em>pretend<\/em> that the prototype code doesn&rsquo;t exist (as if it\nwas thrown away) when you write tests, but uncomment relevant and reusable\nparts of it for the actual implementation.<\/p>\n<p>It follows that TDU is most useful when the structure of the prototype is\ndecent. Otherwise, it might not make sense to uncomment code into a design that\nis wildly different than the one for which the code was written. On the other\nhand, I often find that there are pieces (methods, typically) worth saving in\nany case. YMMV!<\/p>\n<p>As noted before, since the prototype has been created,\nthe ground is now familiar and possibilities and constraints are known. It\nbecomes a lot easier to have a good idea about the kinds of tests that\nneed to be written on different levels (layers) in the code.<\/p>\n<h2>Summary<\/h2>\n<p>TDD and prototyping are excellent companions!<\/p>\n<p>A prototype that is thrown away removes a lot of unknowns that otherwise would make\nTDD difficult, but doesn&rsquo;t leak into the production code.<\/p>\n<p>A prototype\ncan be test-driven with a high-level blackbox test which later on is thrown away.\nSuch a test is most likely an integration test of some sort, perhaps even a UI\ntest. It is not a unit test, as unit tests tend to be tied to a particular implementation.<\/p>\n<p>Using Test-Driven Uncommenting, you can prototype freely and then use proper TDD to\nbring in relevant code from the prototype in order to formalize it. The best of two worlds!<\/p>\n<p>Please let me known your thoughts on this in the comments below!<\/p>\n<hr \/>\n<p><a name=\"run_click_crash\">1<\/a>: With run-click-crash, you have to <em>run<\/em>\nthe application, <em>click<\/em> buttons\/links until you get to where the feature resides, then \nwatch as the application <em>crashes<\/em> because you forgot some simple detail.<\/p>","category":[{"@attributes":{"term":"Methodology"}},{"@attributes":{"term":"test"}},{"@attributes":{"term":"tdd"}},{"@attributes":{"term":"prototyping"}}]},{"title":"Git-diffing Excel files, part 2","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/git-diffing-excel-files-part-2.html","rel":"alternate"}},"published":"2018-01-02T23:30:00+01:00","updated":"2018-01-02T23:30:00+01:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2018-01-02:\/git-diffing-excel-files-part-2.html","summary":"<p>I <a href=\"\/git-diffing-excel-files.html\">previously wrote<\/a> about how to get a useful diff for binary Excel files that reside in a Git repository.<\/p>\n<p>This post adds some details that are big enough to deserve a separate\npost. They are:<\/p>\n<ul>\n<li>User-level configuration of Excel diffing.<\/li>\n<li>How to get an Excel diff from <code>git show \u2026<\/code><\/li><\/ul>","content":"<p>I <a href=\"\/git-diffing-excel-files.html\">previously wrote<\/a> about how to get a useful diff for binary Excel files that reside in a Git repository.<\/p>\n<p>This post adds some details that are big enough to deserve a separate\npost. They are:<\/p>\n<ul>\n<li>User-level configuration of Excel diffing.<\/li>\n<li>How to get an Excel diff from <code>git show<\/code>.<\/li>\n<\/ul>\n<h2>User-level configuration<\/h2>\n<p>In the previous post, I outlined how to add a <em>diff driver<\/em> to the\n<code>.git\/config<\/code> file in a repository. To make the diff driver available to\nall repositories for the current user, update the <code>$HOME\/.gitconfig<\/code> file\ninstead (that&rsquo;s <code>%HOME%\\.gitconfig<\/code> in Windows):<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>[diff &quot;excel&quot;]\n  command = c:\/apps\/excelcompare\/exceldiff.cmd\n<\/code><\/pre><\/div>\n\n<p>(See the previous post for path details and <a href=\"https:\/\/github.com\/na-ka-na\/ExcelCompare\">Excel Compare<\/a>.)<\/p>\n<p>To instruct Git to use the <em>excel<\/em> diff driver for *.xlsx files, edit\n<code>$HOME\/.config\/git\/attributes<\/code> to contain the following:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>*.xlsx diff=excel\n<\/code><\/pre><\/div>\n\n<p>Note that the location of the user-level gitattributes file can be configured\nvia the <code>core.attributesfile<\/code> setting, so make sure you use the correct\nlocation if you have changed that setting. <\/p>\n<h2>git show<\/h2>\n<p>By default, <code>git show<\/code> won&rsquo;t use a custom diff driver. Thus, if you show\na commit you will see the standard &ldquo;Binary files &hellip; differ&rdquo; message. To\nget a proper diff, use the <code>--ext-diff<\/code> option:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"gp\">$ <\/span>git<span class=\"w\"> <\/span>show<span class=\"w\"> <\/span>--ext-diff<span class=\"w\"> <\/span>&lt;object&gt;\n<\/code><\/pre><\/div>\n\n<p>It might be a good idea to define an alias for <code>git show<\/code> that includes\nthis option, for example:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"gp\">$ <\/span>git<span class=\"w\"> <\/span>config<span class=\"w\"> <\/span>--global<span class=\"w\"> <\/span>alias.sh<span class=\"w\"> <\/span><span class=\"s2\">&quot;show --ext-diff&quot;<\/span>\n<\/code><\/pre><\/div>\n\n<h2>Final words<\/h2>\n<p>Feel free to leave a comment below if you found this post useful or\nif you have questions!<\/p>","category":[{"@attributes":{"term":"Tools"}},{"@attributes":{"term":"git"}},{"@attributes":{"term":"diff"}},{"@attributes":{"term":"excel"}}]},{"title":"Nashorn's JSObject in context","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/nashorns-jsobject-in-context.html","rel":"alternate"}},"published":"2017-11-12T23:00:00+01:00","updated":"2017-11-12T23:00:00+01:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2017-11-12:\/nashorns-jsobject-in-context.html","summary":"<p>The JSObject interface in Nashorn makes it possible to expose an object to script code and control in detail how it appears and behaves. The purpose of this article is to explain when the different JSObject methods are called during script execution and in some cases how they should be implemented.<\/p>","content":"<p>The <a href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/jdk\/api\/nashorn\/jdk\/nashorn\/api\/scripting\/JSObject.html\">JSObject<\/a> interface\nin Nashorn (the JavaScript engine in Java 8 and later)\nmakes it possible to expose an object to script code and control in detail how it appears and behaves. \nNashorn offers plenty of options for Java interop, so JSObject is certainly not the only way. However, unlike other\nways it allows for a high degree of flexibility and dynamic behavior.\nFor example, you could\nexpose a Directory &ldquo;class&rdquo; and then allow script code to access files as properties:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nx\">d<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"ow\">new<\/span><span class=\"w\"> <\/span><span class=\"nx\">Directory<\/span><span class=\"p\">(<\/span><span class=\"s1\">&#39;.&#39;<\/span><span class=\"p\">);<\/span>\n<span class=\"nx\">print<\/span><span class=\"p\">(<\/span><span class=\"nx\">d<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;myfile.txt&#39;<\/span><span class=\"p\">]);<\/span>\n<\/code><\/pre><\/div>\n\n<p>The JSObject API <a href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/jdk\/api\/nashorn\/jdk\/nashorn\/api\/scripting\/JSObject.html\">documentation<\/a>\nstates that:<\/p>\n<blockquote>\n<p>&ldquo;Nashorn will treat objects of such classes just like nashorn script objects.&rdquo;<\/p>\n<\/blockquote>\n<p>This is not entirely true. Many <code>Object<\/code> methods are not implemented for JSObject\nand will behave erratically. For example, assuming X is a JSObject object, <code>Object.prototype.hasOwnProperty.call(X, prop)<\/code>\nalways returns <code>false<\/code>, whereas <code>Object(X)<\/code> throws an exception.<\/p>\n<p>There is another problem with the documentation though. As is common with API documentation, it correctly explains\nwhat each method is for, but fails to put it in context or give examples.<\/p>\n<p><strong>The purpose of this article is to explain when the different JSObject methods are called during script \nexecution and in some cases how they should be implemented.<\/strong><\/p>\n<blockquote>\n<p>&#128712; Specific behavior explained here has been tested with Java 8u151 and Java 9.0.1.<\/p>\n<\/blockquote>\n<!-- -->\n<blockquote>\n<p>&#128712; In the examples, I typically use &ldquo;X&rdquo; to refer to an instance of a class derived from JSObject.<\/p>\n<\/blockquote>\n<h2>AbstractJSObject<\/h2>\n<p>Nashorn provides an abstract base class, AbstractJSObject with default implementations for all JSObject\nmethods. It is recommended to extend this class and only override methods as needed. In addition, AbstractJSObject.getDefaultValue\ncan be overridden to provide a custom <a href=\"https:\/\/www.ecma-international.org\/ecma-262\/5.1\/#sec-8.12.8\">default value<\/a> \nfor the object. Read on for details.<\/p>\n<blockquote>\n<p>&#128712; Java 9 moves the implementation of getDefaultValue from AbstractJSObject to a default method\non the JSObject interface.<\/p>\n<\/blockquote>\n<h2>Property operations<\/h2>\n<p>There are six methods that deal with object properties. Most of them use terminology based on <em>member<\/em>, but\nthe <a href=\"https:\/\/www.ecma-international.org\/ecma-262\/5.1\/\">ECMAScript spec<\/a> doesn&rsquo;t use the word <em>member<\/em>, only\n<em>property<\/em> and <em>method<\/em> (referring to a property with a function value). Therefore, I will use <em>property<\/em> throughout\nthis article.<\/p>\n<h3>hasMember<\/h3>\n<p>This method is called when the <code>in<\/code> operator is used. For example, the following script expression will result\nin a call to hasMember with argument &ldquo;foo&rdquo;:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"s1\">&#39;foo&#39;<\/span><span class=\"w\"> <\/span><span class=\"ow\">in<\/span><span class=\"w\"> <\/span><span class=\"nx\">X<\/span>\n<\/code><\/pre><\/div>\n\n<p>Note that Nashorn will not call hasMember before arbitrary property access. In other words, you cannot\nassume that getMember is only called for properties for which hasMember is positive.<\/p>\n<h3>getMember<\/h3>\n<p>This method is called to retrieve the value of a named property. For example, any of\nthe following script expressions will result in a call to getMember with argument &ldquo;foo&rdquo;:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">X<\/span><span class=\"p\">.<\/span><span class=\"nx\">foo<\/span>\n<span class=\"nx\">X<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;foo&#39;<\/span><span class=\"p\">]<\/span>\n<span class=\"nx\">X<\/span><span class=\"p\">.<\/span><span class=\"nx\">foo<\/span><span class=\"p\">()<\/span>\n<\/code><\/pre><\/div>\n\n<p>Note the last one&mdash;Nashorn will first retrieve the value of the &ldquo;foo&rdquo; property and then call it. If the\nvalue isn&rsquo;t a function, the call will (obviously) fail.<\/p>\n<p>To implement method support, getMember can return a regular Java function object (i.e., an object that implements\na public interface annotated with <a href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/lang\/FunctionalInterface.html\">FunctionalInterface<\/a>.\nFor example:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"n\">Object<\/span><span class=\"w\"> <\/span><span class=\"nf\">getMember<\/span><span class=\"p\">(<\/span><span class=\"n\">String<\/span><span class=\"w\"> <\/span><span class=\"n\">name<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;foo&quot;<\/span><span class=\"p\">.<\/span><span class=\"na\">equals<\/span><span class=\"p\">(<\/span><span class=\"n\">name<\/span><span class=\"p\">))<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">Supplier<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">String<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;bar&quot;<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"kc\">null<\/span><span class=\"p\">;<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>It is also possible to return a JSObject function. This is required for the default value algorithm,\nas we will see later. How to create a JSObject function is also covered later.<\/p>\n<blockquote>\n<p>&#9888; Java 9 adds support for ES6 symbols. As of this writing, JSObject does not support property access based\non symbols&mdash;no call to getMember will be made and the result will be <code>null<\/code>.<\/p>\n<\/blockquote>\n<h3>setMember<\/h3>\n<p>This method is called when the value of a property is set. For example, any of the following script statements will result\nin a call to setMember with arguments &ldquo;foo&rdquo; and &ldquo;bar&rdquo;:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">X<\/span><span class=\"p\">.<\/span><span class=\"nx\">foo<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s1\">&#39;bar&#39;<\/span><span class=\"p\">;<\/span>\n<span class=\"nx\">X<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;foo&#39;<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s1\">&#39;bar&#39;<\/span><span class=\"p\">;<\/span>\n<\/code><\/pre><\/div>\n\n<blockquote>\n<p>&#9888; As with getMember, symbol-based access is not supported. Setting a property based on a symbol is\nsimply ignored.<\/p>\n<\/blockquote>\n<h3>removeMember<\/h3>\n<p>This method is called when the <code>delete<\/code> operator is used. For example, any of the following script statements \nwill result in a call to removeMember with argument &ldquo;foo&rdquo;:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"ow\">delete<\/span><span class=\"w\"> <\/span><span class=\"nx\">X<\/span><span class=\"p\">.<\/span><span class=\"nx\">foo<\/span><span class=\"p\">;<\/span>\n<span class=\"ow\">delete<\/span><span class=\"w\"> <\/span><span class=\"nx\">X<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;foo&#39;<\/span><span class=\"p\">];<\/span>\n<\/code><\/pre><\/div>\n\n<p>Furthermore, removeMember is also called for array element deletion (there is no removeSlot method):<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"ow\">delete<\/span><span class=\"w\"> <\/span><span class=\"nx\">X<\/span><span class=\"p\">[<\/span><span class=\"mf\">1<\/span><span class=\"p\">];<\/span>\n<\/code><\/pre><\/div>\n\n<h3>keySet<\/h3>\n<p>This method is used when the properties of an object are enumerated. The following script code will result in\na call to keySet:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nx\">k<\/span><span class=\"w\"> <\/span><span class=\"ow\">in<\/span><span class=\"w\"> <\/span><span class=\"nx\">X<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ ...<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>With JSObject, there is no notion of <em>own<\/em> versus <em>prototype<\/em> properties, so the customary call to\n<code>Object.prototype.hasOwnProperty<\/code> should be omitted (and in fact, must be omitted since, as noted, it\nwould always return <code>false<\/code>).<\/p>\n<p>The returned set should only include enumerable properties; both hasMember and getMember can\nbe implemented for a member that is not in the key set.<\/p>\n<blockquote>\n<p>&#128712; To be consistent with a native array, a JSObject array should return indices but not\nthe &ldquo;length&rdquo; property as keys. However, it&rsquo;s possible to implement an &ldquo;infinite&rdquo; array\n(at least up to length 2<sup>32<\/sup>),\ne.g. where the value of the Nth index is the Nth prime, in which case returning all keys is of course infeasible.<\/p>\n<\/blockquote>\n<!-- -->\n<blockquote>\n<p>&#9888; You&rsquo;d think <code>Object.keys<\/code> would use keySet, but it doesn&rsquo;t. <code>Object.keys<\/code> doesn&rsquo;t have\nJSObject support and will throw an exception if passed such an object.<\/p>\n<\/blockquote>\n<h3>values<\/h3>\n<p>This method is only used to support the Nashorn <code>for each<\/code> extension:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"nx\">each<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nx\">v<\/span><span class=\"w\"> <\/span><span class=\"ow\">in<\/span><span class=\"w\"> <\/span><span class=\"nx\">X<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">print<\/span><span class=\"p\">(<\/span><span class=\"nx\">v<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>My recommendation is to return values only for keys returned from the keySet method, since it makes a lot\nof sense to be consistent.<\/p>\n<blockquote>\n<p>&#9888; The values method is unfortunately not used to implement <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Statements\/for...of\"><code>for...of<\/code><\/a>.\nin ES6. <code>for...of<\/code> is specified to use an iterator retrieved via the <code>@@iterator<\/code> symbol, and as noted JSObject\ndoesn&rsquo;t support symbol properties.<\/p>\n<\/blockquote>\n<h2>Object character<\/h2>\n<p>For the lack of a better method category&hellip; there are two methods that can be said to control\nthe <em>character<\/em> of an object: getClassName and getDefaultValue.<\/p>\n<h3>getClassName<\/h3>\n<p>This method is called by <code>Object.prototype.toString<\/code>. If you were to return &ldquo;MyClass&rdquo; from getClassName,\nthe following script statement would print &ldquo;[object MyClass]&rdquo; (without the quotes):<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">print<\/span><span class=\"p\">(<\/span><span class=\"nb\">Object<\/span><span class=\"p\">.<\/span><span class=\"nx\">prototype<\/span><span class=\"p\">.<\/span><span class=\"nx\">toString<\/span><span class=\"p\">.<\/span><span class=\"nx\">call<\/span><span class=\"p\">(<\/span><span class=\"nx\">X<\/span><span class=\"p\">));<\/span>\n<\/code><\/pre><\/div>\n\n<blockquote>\n<p>&#128712; Note that to make it possible to call <code>X.toString()<\/code>, you have to return a function from the resulting\ncall to getMember; there are no built-in methods that are callable on a JSObject object.<\/p>\n<\/blockquote>\n<p>AbstractJSObject by default returns the name of the current class. To emulate a native object, return &ldquo;Object&rdquo; instead.<\/p>\n<h3>getDefaultValue<\/h3>\n<p>This method is called to obtain the <a href=\"https:\/\/www.ecma-international.org\/ecma-262\/5.1\/#sec-8.12.8\">default value<\/a> for an\nobject. AbstractJSObject delegates to an implementation that follows the algorithm outlined in the previous link,\nso there is no need to provide your own implementation. In case you still want to, here is how it works.<\/p>\n<p>getDefaultValue is called with a hint, which is (as of this writing) one of the following values:<\/p>\n<ul>\n<li><code>Number.class<\/code><\/li>\n<li><code>String.class<\/code><\/li>\n<li><code>null<\/code> (equivalent to <code>Number.class<\/code> here)<\/li>\n<\/ul>\n<p><code>null<\/code> is used as hint to get the default value in cases such as:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"s1\">&#39;&#39;<\/span><span class=\"w\"> <\/span><span class=\"o\">+<\/span><span class=\"w\"> <\/span><span class=\"nx\">X<\/span>\n<span class=\"mf\">42<\/span><span class=\"w\"> <\/span><span class=\"o\">+<\/span><span class=\"w\"> <\/span><span class=\"nx\">X<\/span>\n<span class=\"s1\">&#39;&#39;<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"nx\">X<\/span>\n<\/code><\/pre><\/div>\n\n<p><code>Number.class<\/code> is used as hint when a numeric operator other than <code>+<\/code> is used, when \nnon-strict equality is tested with a number or a boolean and in cases where a number is needed, \nfor example:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"mf\">42<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"w\"> <\/span><span class=\"nx\">X<\/span>\n<span class=\"mf\">42<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"nx\">X<\/span>\n<span class=\"kc\">true<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"nx\">X<\/span>\n<span class=\"nb\">Math<\/span><span class=\"p\">.<\/span><span class=\"nx\">floor<\/span><span class=\"p\">(<\/span><span class=\"nx\">X<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>https:\/\/www.ecma-international.org\/ecma-262\/5.1\/#sec-11.6.1<\/p>\n<p>Finally, <code>String.class<\/code> is used as hint in cases such as:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">objectOrArray<\/span><span class=\"p\">[<\/span><span class=\"nx\">X<\/span><span class=\"p\">]<\/span>\n<span class=\"nb\">parseInt<\/span><span class=\"p\">(<\/span><span class=\"nx\">X<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">10<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>Nashorn will in its implementation of the default value algorithm make calls to getMember to \nretrieve one of the &ldquo;toString&rdquo; and &ldquo;valueOf&rdquo; methods. If you implement support for either of these, it has to be \na JSObject function, not a regular Java function! If you see an error with message &ldquo;cannot.get.default.number&rdquo;\nor &ldquo;cannot.get.default.string&rdquo;, Nashorn failed to obtain a default value.<\/p>\n<blockquote>\n<p>&#9888; For some reason, getDefaultValue isn&rsquo;t called in the expression <code>X[X]<\/code>, i.e. when a JSObject object\nis used as property accessor for another JSObject object. The result is always <code>null<\/code>.<\/p>\n<\/blockquote>\n<!-- -->\n<blockquote>\n<p>&#9888; There is unfortunately no way to control the default value in a pure boolean context (e.g. <code>if(X)<\/code>). This would have been\nvery useful, e.g. to implement a <a href=\"https:\/\/en.wikipedia.org\/wiki\/Null_object_pattern\">null object<\/a>.<\/p>\n<\/blockquote>\n<!-- -->\n<blockquote>\n<p>&#128712; To learn more about the behavior in the equality cases, read about <a href=\"https:\/\/www.ecma-international.org\/ecma-262\/5.1\/#sec-11.9.3\">abstract equality<\/a>. To learn about the behavior for the binary\naddition cases, read about <a href=\"https:\/\/www.ecma-international.org\/ecma-262\/5.1\/#sec-11.6.1\">the addition operator<\/a>.<\/p>\n<\/blockquote>\n<h2>Array operations<\/h2>\n<p>The following methods are used for array operations: isArray, getSlot, setSlot and hasSlot.<\/p>\n<blockquote>\n<p>&#128712; For an array, you may want to return &ldquo;Array&rdquo; from getClassName, to be compatible with libraries\nthat use <code>Object.prototype.toString<\/code> to test for an array. You should also implement support for the &ldquo;length&rdquo;\nproperty in hasMember and getMember.<\/p>\n<\/blockquote>\n<h3>isArray<\/h3>\n<p>This method determines the result of <code>Array.isArray(X)<\/code>. It has no bearing on the result of the <code>typeof<\/code> operator; \n<code>typeof X<\/code> for an object where isArray returns <code>true<\/code> is &ldquo;object&rdquo; (without the quotes).<\/p>\n<h3>getSlot<\/h3>\n<p>This method returns the value of the Nth array element. The following script expression results in a call to\ngetSlot with argument 0:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">X<\/span><span class=\"p\">[<\/span><span class=\"mf\">0<\/span><span class=\"p\">]<\/span>\n<\/code><\/pre><\/div>\n\n<blockquote>\n<p>&#128712; getSlot will be called also for a negative index. However, if the index is a negative non-integer,\nsuch as -1.0d, getMember will be called instead.<\/p>\n<\/blockquote>\n<h3>setSlot<\/h3>\n<p>This method is called to set the value of the Nth array element. The following script statement results in a call to\nsetSlot with arguments 0 and &ldquo;testing&rdquo;:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">X<\/span><span class=\"p\">[<\/span><span class=\"mf\">0<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s1\">&#39;testing&#39;<\/span><span class=\"p\">;<\/span>\n<\/code><\/pre><\/div>\n\n<p>The behavior for a negative index is the same as for getSlot.<\/p>\n<h3>hasSlot<\/h3>\n<p>This method is used to create function arguments in a call to <code>Function.prototype.apply<\/code>. Suppose we have a\nregular JavaScript function f, and X is our JSObject array. Next, suppose the following script statement is\nexecuted:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">f<\/span><span class=\"p\">.<\/span><span class=\"nx\">apply<\/span><span class=\"p\">(<\/span><span class=\"kc\">null<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"nx\">X<\/span><span class=\"p\">);<\/span>\n<\/code><\/pre><\/div>\n\n<p>To create arguments for f, Nashorn does the following:<\/p>\n<ol>\n<li>Calls hasMember with argument &ldquo;length&rdquo; to determine if the array length is available.<\/li>\n<li>If the length is available, calls getMember to retrieve it, otherwise assumes length 0.<\/li>\n<li>For index 0 up to but not including the array length, calls hasSlot to determine if the array\n   has an element for that index (remember, an array may be sparse).<\/li>\n<li>If there is an element for a particular index, calls getSlot to retrieve the value of the\n   element at that index.<\/li>\n<\/ol>\n<h2>Function operations<\/h2>\n<p>The following methods are used for a JSObject function: isFunction, isStrictFunction and call.\nTechnically there are more, since a function in JavaScript also can be seen as a class (type), \nbut class-related methods are covered separately.<\/p>\n<blockquote>\n<p>&#128712; For a function, you may want to return &ldquo;Function&rdquo; from getClassName, to be compatible with libraries\nthat use <code>Object.prototype.toString<\/code> to test for a function.<\/p>\n<\/blockquote>\n<h3>isFunction<\/h3>\n<p>This method has two purposes. First and foremost, Nashorn sometimes uses it to determine if a JSObject instance is callable,\ni.e. if it represents a function. It is not always called prior to a function invocation, so the following statement will\n<em>not<\/em> result in a call to isFunction:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">X<\/span><span class=\"p\">();<\/span>\n<\/code><\/pre><\/div>\n\n<p>However, in the default value algorithm, Nashorn calls isFunction on a JSObject object\nrespresenting one of the &ldquo;valueOf&rdquo; and &ldquo;toString&rdquo; methods to determine if it is callable. Creating a bound\nfunction also calls isFunction to determine if binding is possible:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nx\">boundFun<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"nb\">Function<\/span><span class=\"p\">.<\/span><span class=\"nx\">prototype<\/span><span class=\"p\">.<\/span><span class=\"nx\">bind<\/span><span class=\"p\">.<\/span><span class=\"nx\">call<\/span><span class=\"p\">(<\/span><span class=\"nx\">X<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"kc\">null<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">1<\/span><span class=\"p\">);<\/span>\n<\/code><\/pre><\/div>\n\n<p>Another case is to test if a callback function is indeed callable:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nx\">mapped<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"mf\">1<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">2<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">3<\/span><span class=\"p\">].<\/span><span class=\"nx\">map<\/span><span class=\"p\">(<\/span><span class=\"nx\">X<\/span><span class=\"p\">);<\/span>\n<\/code><\/pre><\/div>\n\n<p>The second purpose is for the <code>typeof<\/code> operator. The result of calling <code>typeof X<\/code> when isFunction returns\n<code>true<\/code> is &ldquo;function&rdquo; (without the quotes).<\/p>\n<h3>call<\/h3>\n<p>This method is called to handle the actual function call. The first argument is the &ldquo;this&rdquo; object and subsequent\narguments are arguments passed to the function. Nashorn marshals arguments as follows:<\/p>\n<table>\n  <thead>\n    <tr>\n      <th>JavaScript<\/th>\n      <th>Java<\/th>\n    <\/tr>\n  <\/thead>\n  <tbody>\n    <tr>\n      <td><code>undefined<\/code><\/td>\n      <td>jdk.nashorn.internal.runtime.Undefined (singleton)<\/td>\n    <\/tr>\n    <tr>\n      <td><code>null<\/code><\/td>\n      <td><code>null<\/code><\/td>\n    <\/tr>\n    <tr>\n      <td>string<\/td>\n      <td>java.lang.String<\/td>\n    <\/tr>\n    <tr>\n      <td>primitive value<\/td>\n      <td>boxed primitive<\/td>\n    <\/tr>\n    <tr>\n      <td>script object\/array\/function<\/td>\n      <td>wrapped in an instance of jdk.nashorn.api.scripting.ScriptObjectMirror *<\/td>\n    <\/tr>\n    <tr>\n      <td>JSObject instance or other Java object<\/td>\n      <td>the instance itself (no wrapping occurs)<\/td>\n    <\/tr>\n  <\/tbody>\n<\/table>\n\n<p>*) It is beyond the scope of this article to go through the ScriptObjectMirror API.<\/p>\n<h3>isStrictFunction<\/h3>\n<p>This method is called to decide what the &ldquo;this&rdquo; argument passed to call should be when the function is\nnot called as an object method or otherwise bound to a particular instance).<\/p>\n<p>For a strict function, the &ldquo;this&rdquo; argument is <code>undefined<\/code>. For a non-strict function, it is the global object.\nExamples of cases where strictness plays a role are when a non-bound function is called by itself and when\na function is used as a callback:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">X<\/span><span class=\"p\">(<\/span><span class=\"mf\">1<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">2<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">[<\/span><span class=\"mf\">1<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">2<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">3<\/span><span class=\"p\">].<\/span><span class=\"nx\">map<\/span><span class=\"p\">(<\/span><span class=\"nx\">X<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<blockquote>\n<p>&#9888; Nashorn in Java 8 behaves differently in the two cases above. In the first one, it does <em>not<\/em> call isStrictFunction\nand always passes <code>undefined<\/code> for &ldquo;this&rdquo;. In other words, it always behaves as if the function is strict.<\/p>\n<\/blockquote>\n<h2>Class operations<\/h2>\n<p>In JavaScript, a function is similar to a class, in that you can &ldquo;instantiate&rdquo; a function using the\n<code>new<\/code> keyword. JSObject supports the following class operations: newObject, isInstance and isInstanceOf.<\/p>\n<h3>newObject<\/h3>\n<p>This method is called when the <code>new<\/code> operator is used. For example, the following script expression calls\nnewObject with arguments &ldquo;foo&rdquo; and &ldquo;bar&rdquo;:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"ow\">new<\/span><span class=\"w\"> <\/span><span class=\"nx\">X<\/span><span class=\"p\">(<\/span><span class=\"s1\">&#39;foo&#39;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s1\">&#39;bar&#39;<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>Arguments are marshalled in the same way as for call. <\/p>\n<p>The return value can be anything, but it&rsquo;d make sense to return something that can be considered\nto be an instance of the &ldquo;class&rdquo;.<\/p>\n<h3>isInstance<\/h3>\n<p>This method is used to implement the <code>instanceof<\/code> operator when a JSObject object is on the right-hand side. \nFor example, given two JSObject\nobjects X and Y, the following expression would call isInstance of X with Y as argument:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>Y instanceof X\n<\/code><\/pre><\/div>\n\n<h3>isInstanceOf<\/h3>\n<p>This method is used for reverse <code>instanceof<\/code>. For example, the following expression would call isInstanceOf\nwith argument &ldquo;foo&rdquo;:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">X<\/span><span class=\"w\"> <\/span><span class=\"ow\">instanceof<\/span><span class=\"w\"> <\/span><span class=\"s1\">&#39;foo&#39;<\/span>\n<\/code><\/pre><\/div>\n\n<p>However, not all uses of <code>instanceof<\/code> with the JSObject object on the left-hand side results in a call to\nisInstanceOf. The following does not, for example:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">X<\/span><span class=\"w\"> <\/span><span class=\"ow\">instanceof<\/span><span class=\"w\"> <\/span><span class=\"nb\">Date<\/span>\n<\/code><\/pre><\/div>\n\n<h2>JSON<\/h2>\n<p>To create a JSON representation of a JSObject object when <code>JSON.stringify(X)<\/code> is called, Nashorn first\ncalls getMember with the argument &ldquo;toJSON&rdquo;. If the result is a function (not necessarily a JSObject function),\nit is called to obtain the value to use to create a JSON representation. The returned value should not be\nJSON in itself, but rather the value to serialize to JSON.<\/p>\n<p>If there is no &ldquo;toJSON&rdquo; method, the following steps are taken for a non-array:<\/p>\n<ol>\n<li>Call keySet to obtain all keys.<\/li>\n<li>For each key, call getMember with the key as argument to obtain the value to serialize as value for that key.<\/li>\n<\/ol>\n<p>For an array, the following steps are taken:<\/p>\n<ol>\n<li>Call getMember with argument &ldquo;length&rdquo; to obtain the array length.<\/li>\n<li>For each index in the array, call getSlot to obtain the value to serialize as value for that index.<\/li>\n<\/ol>\n<p>If the &ldquo;toJSON&rdquo; method returns a JSObject instance, the above steps are taken to serialize that instance.<\/p>\n<h2>Other<\/h2>\n<p>There are two methods that can\/should be ignored: toNumber and eval.<\/p>\n<h3>toNumber<\/h3>\n<p>This method is deprecated and should not be implemented\/overridden. getDefaultValue is called with hint <code>Number.class<\/code>\ninstead.<\/p>\n<h3>eval<\/h3>\n<p>This method is supposedly called to evaluate JavaScript code, but as far as I can see it is never called on\na JSObject object.<\/p>\n<h2>Miscellaneous<\/h2>\n<p>This article is drawing to its end. Before we part ways, there are two pieces of information I think\nare relevant in relation to what has been discussed. The first is how to return <code>undefined<\/code> from a JSObject\nmethod, the second is how to call non-JSObject methods on a JSObject object.<\/p>\n<h3>undefined<\/h3>\n<p>jdk.nashorn.internal.runtime.Undefined belongs to an internal package and should therefore not be\nreferenced. In fact, in Java 9 the package isn&rsquo;t exposed at all. If you want to return <code>undefined<\/code> from\na call to getMember, for example, you can obtain the singleton instance of the Undefined class using the\nfollowing Java function:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kd\">static<\/span><span class=\"w\"> <\/span><span class=\"n\">Object<\/span><span class=\"w\"> <\/span><span class=\"nf\">getUndefined<\/span><span class=\"p\">(<\/span><span class=\"n\">ScriptEngine<\/span><span class=\"w\"> <\/span><span class=\"n\">engine<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"kd\">throws<\/span><span class=\"w\"> <\/span><span class=\"n\">ScriptException<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">ScriptObjectMirror<\/span><span class=\"w\"> <\/span><span class=\"n\">arrayMirror<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">ScriptObjectMirror<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"n\">engine<\/span><span class=\"p\">.<\/span><span class=\"na\">eval<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;[undefined]&quot;<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">arrayMirror<\/span><span class=\"p\">.<\/span><span class=\"na\">getSlot<\/span><span class=\"p\">(<\/span><span class=\"mi\">0<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Why wrap <code>undefined<\/code> inside an array? Because <code>engine.eval(\"undefined\")<\/code> returns <code>null<\/code>.<\/p>\n<h3>Calling a non-JSObject method<\/h3>\n<p>It is possible to call a regular Java method on a JSObject object from a script. Suppose our\nfamous object X is an instance of this class:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">class<\/span> <span class=\"nc\">MyObj<\/span><span class=\"w\"> <\/span><span class=\"kd\">extends<\/span><span class=\"w\"> <\/span><span class=\"n\">AbstractJSObject<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kt\">int<\/span><span class=\"w\"> <\/span><span class=\"nf\">multiply<\/span><span class=\"p\">(<\/span><span class=\"kt\">int<\/span><span class=\"w\"> <\/span><span class=\"n\">a<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"kt\">int<\/span><span class=\"w\"> <\/span><span class=\"n\">b<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">a<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"w\"> <\/span><span class=\"n\">b<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>To call the multiply method from JavaScript, we can write:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nx\">multiply<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"nx\">X<\/span><span class=\"p\">[<\/span><span class=\"s1\">&#39;multiply(int,int)&#39;<\/span><span class=\"p\">];<\/span>\n<span class=\"nx\">print<\/span><span class=\"p\">(<\/span><span class=\"nx\">multiply<\/span><span class=\"p\">(<\/span><span class=\"mf\">5<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">6<\/span><span class=\"p\">));<\/span>\n<\/code><\/pre><\/div>\n\n<p>In this case, Nashorn will verify that the passed arguments match the parameter types.\nType names in a method signature should be simple names for primitive types (e.g. <em>int<\/em> as\nabove), or the fully qualified class name (e.g. <em>java.lang.String<\/em>).<\/p>\n<h2>Final remarks<\/h2>\n<p>Exposing script objects based on JSObject is very useful and allows for great flexibility\nand control over script behavior. In this article, I have covered the different JSObject\nmethods and shown how they are called during script execution. Please let me know if\nanything is unclear, if you have found errors or omissions, or simply if the article\nhas been useful to you!<\/p>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"java"}},{"@attributes":{"term":"nashorn"}}]},{"title":"Scala pattern matching & lowercase case objects","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/scala-pattern-matching-lowercase-case-objects.html","rel":"alternate"}},"published":"2016-11-30T22:54:00+01:00","updated":"2016-11-30T22:54:00+01:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2016-11-30:\/scala-pattern-matching-lowercase-case-objects.html","summary":"<p>I just learned something about pattern matching and case objects in Scala which I thought I&rsquo;d share.<\/p>","content":"<p>I just learned something about pattern matching and case objects in Scala which I thought I&rsquo;d share. Consider the following code:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">object<\/span><span class=\"w\"> <\/span><span class=\"nc\">Messages<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">  <\/span><span class=\"k\">case<\/span><span class=\"w\"> <\/span><span class=\"k\">object<\/span><span class=\"w\"> <\/span><span class=\"nc\">foo<\/span>\n\n<span class=\"w\">  <\/span><span class=\"k\">case<\/span><span class=\"w\"> <\/span><span class=\"k\">object<\/span><span class=\"w\"> <\/span><span class=\"nc\">bar<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"k\">import<\/span><span class=\"w\"> <\/span><span class=\"nc\">Messages<\/span><span class=\"p\">.<\/span><span class=\"n\">_<\/span>\n\n<span class=\"k\">def<\/span><span class=\"w\"> <\/span><span class=\"nf\">identify<\/span><span class=\"p\">(<\/span><span class=\"n\">msg<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"nc\">AnyRef<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">msg<\/span><span class=\"w\"> <\/span><span class=\"k\">match<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">  <\/span><span class=\"k\">case<\/span><span class=\"w\"> <\/span><span class=\"n\">foo<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;foo&quot;<\/span>\n<span class=\"w\">  <\/span><span class=\"k\">case<\/span><span class=\"w\"> <\/span><span class=\"n\">bar<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;bar&quot;<\/span>\n<span class=\"w\">  <\/span><span class=\"k\">case<\/span><span class=\"w\"> <\/span><span class=\"n\">_<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;unknown&quot;<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"n\">identify<\/span><span class=\"p\">(<\/span><span class=\"n\">bar<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>What does it print?<\/p>\n<p>If your answer is &ldquo;bar&rdquo;, you&rsquo;re wrong - the correct answer is &ldquo;foo&rdquo;. But why is that?<\/p>\n<p>The problem here is that the case objects (in particular <code>foo<\/code>, which comes first in the pattern matching block)\nhave names that start with a lowercase letter.\nWhen the Scala compiler comes\nacross the pattern matching block, section 8.1.1 from the <a href=\"http:\/\/www.scala-lang.org\/docu\/files\/ScalaReference.pdf\">Scala Language Specification<\/a> \n(SLS) kicks in and tells the\ncompiler that <code>foo<\/code> and <code>bar<\/code> are variable patterns:<\/p>\n<blockquote>\n<p><strong>8.1.1 Variable Patterns<\/strong><\/p>\n<p>[&hellip;]<\/p>\n<p>A variable pattern x is a simple identifier which starts with a <em>lower case<\/em> letter. It\nmatches any value, and binds the variable name to that value. [&hellip;]<\/p>\n<\/blockquote>\n<p>(Note the bold part&ndash;trying to use a variable name that starts with an uppercase letter in pattern matching\nresults in a compile error.)\nLuckily, the compiler is extremely helpful in describing the problem and suggesting a solution:<\/p>\n<blockquote>\n<p>example.scala:8: warning: patterns after a variable pattern cannot match (SLS 8.1.1)<\/p>\n<p>If you intended to match against object foo in package &lt;empty&gt;, you must use backticks, like: case `foo` =&gt;<\/p>\n<\/blockquote>\n<p>My excuse? Uh, compiler warnings flash by quite quickly in my editor and are typically replaced\nwith the result of a unit test run or something similar&hellip; :-) But I also (vividly) recall thinking something\nalong the lines of &ldquo;surely the compiler is smart enough to know that I intend to match against the case objects.&rdquo;\nIn retrospect, having a compiler that guesses at my intentions rather than following a spec seems like a Bad Thing&trade;!<\/p>\n<p>Thus:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">def<\/span><span class=\"w\"> <\/span><span class=\"nf\">identify<\/span><span class=\"p\">(<\/span><span class=\"n\">msg<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"nc\">AnyRef<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">msg<\/span><span class=\"w\"> <\/span><span class=\"k\">match<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">  <\/span><span class=\"k\">case<\/span><span class=\"w\"> <\/span><span class=\"n\">`foo`<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;foo&quot;<\/span>\n<span class=\"w\">  <\/span><span class=\"k\">case<\/span><span class=\"w\"> <\/span><span class=\"n\">`bar`<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;bar&quot;<\/span>\n<span class=\"w\">  <\/span><span class=\"k\">case<\/span><span class=\"w\"> <\/span><span class=\"n\">_<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;unknown&quot;<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Note that the situation doesn&rsquo;t apply when pattern-matching a lowercase-named case <em>class<\/em>, since that\nis interpreted as <em>constructor pattern<\/em> matching (SLS 8.1.6).<\/p>\n<p>If you for some reason don&rsquo;t want to use backticks, you can also qualify the case object names:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">def<\/span><span class=\"w\"> <\/span><span class=\"nf\">identify<\/span><span class=\"p\">(<\/span><span class=\"n\">msg<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"nc\">AnyRef<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">msg<\/span><span class=\"w\"> <\/span><span class=\"k\">match<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">  <\/span><span class=\"k\">case<\/span><span class=\"w\"> <\/span><span class=\"nc\">Messages<\/span><span class=\"p\">.<\/span><span class=\"n\">foo<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;foo&quot;<\/span>\n<span class=\"w\">  <\/span><span class=\"k\">case<\/span><span class=\"w\"> <\/span><span class=\"nc\">Messages<\/span><span class=\"p\">.<\/span><span class=\"n\">bar<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;bar&quot;<\/span>\n<span class=\"w\">  <\/span><span class=\"k\">case<\/span><span class=\"w\"> <\/span><span class=\"n\">_<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;unknown&quot;<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Or just avoid lowercase case object names altogether!<\/p>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"scala"}},{"@attributes":{"term":"functional"}}]},{"title":"Git-diffing Excel files","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/git-diffing-excel-files.html","rel":"alternate"}},"published":"2016-03-04T16:00:00+01:00","updated":"2016-03-04T16:00:00+01:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2016-03-04:\/git-diffing-excel-files.html","summary":"<p>In this post, I&rsquo;m going to demonstrate how to get a useful diff for binary Excel files\nthat reside in a Git repository. I assume that you&rsquo;re familiar with Git, and in that case\nyou know that having binary files in a repository is generally not a good \u2026<\/p>","content":"<p>In this post, I&rsquo;m going to demonstrate how to get a useful diff for binary Excel files\nthat reside in a Git repository. I assume that you&rsquo;re familiar with Git, and in that case\nyou know that having binary files in a repository is generally not a good idea.\nNonetheless, sometimes it&rsquo;s useful&mdash;perhaps they contain test data, or import data,\nor base data for bootstrapping, or some other useful data that aren&rsquo;t suitable for text form.<\/p>\n<h2>Diffing a binary file<\/h2>\n<p>For whatever reason you have an Excel file in your repository, finding a difference in\nthe file between two commits is by default not possible. Let&rsquo;s say that you have\nuncommitted changes to an Excel file called <code>document.xlsx<\/code>. This is what happens if\nyou try to see what has changed:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"gp\">$ <\/span>git<span class=\"w\"> <\/span>diff<span class=\"w\"> <\/span>document.xlsx\n<span class=\"go\">diff --git a\/document.xlsx b\/document.xlsx<\/span>\n<span class=\"go\">index b22099f..ebebbb9 100644<\/span>\n<span class=\"go\">Binary files a\/document.xlsx and b\/document.xlsx differ<\/span>\n<\/code><\/pre><\/div>\n\n<p>Since the file is binary rather than text, Git gives up and just prints that there is a\ndifference. But that will soon change! :-)<\/p>\n<h2>Defining an Excel diff driver<\/h2>\n<p>First, download the <a href=\"https:\/\/github.com\/na-ka-na\/ExcelCompare\">ExcelCompare<\/a> tool. Click\non <a href=\"https:\/\/github.com\/na-ka-na\/ExcelCompare\/releases\">Releases<\/a> and get the latest one&mdash;I used\n0.5.1 when testing. Unpack the ZIP file in a folder of your choosing, but make sure it&rsquo;s in a \npersistent location (i.e., unpacking it in a Downloads folder is probably a bad idea). I unpacked to\n<code>c:\\apps\\excelcompare<\/code>.<\/p>\n<p>By now, it&rsquo;s probably a good time to mention that I use Git Bash on Windows. That affects\nthe path handling a bit, as you&rsquo;ll see.<\/p>\n<p>We will write a script to perform the actual diffing. To begin, edit the <code>.git\/config<\/code> file in\nyour repository and amend the following:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>[diff &quot;excel&quot;]\n  command = c:\/apps\/excelcompare\/exceldiff.cmd\n<\/code><\/pre><\/div>\n\n<p>This registers a <em>diff driver<\/em> in your repository, telling Git which command to use when diffing\nfiles of <em>excel<\/em> type. The <code>exceldiff.cmd<\/code> script doesn&rsquo;t\nexist yet, but it will in a minute. If you want to place the script somewhere else, or name it\ndifferently, feel free to do so.<\/p>\n<p>Do you see the path oddity? The command path looks <em>almost<\/em> like a regular Windows path, except\nit has forward slashes instead of backward slashes. Using backward slashes, even if they are\nproperly escaped, did not work for me.<\/p>\n<p>Next, we must tell Git to associate certain files with the <em>excel<\/em> diff driver. To do so, edit \n<code>.gitattributes<\/code> in the root of your repository and amend the following:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>*.xlsx diff=excel\n<\/code><\/pre><\/div>\n\n<p>Feel free to add more file patterns (one per line) if you wish. ExcelCompare supports a number of different \nExcel file types.<\/p>\n<p>Note that <code>.gitattributes<\/code> (unlike <code>.gitignore<\/code>) <a href=\"https:\/\/git-scm.com\/docs\/git-archive#ATTRIBUTES\">must be committed<\/a> \nto have any effect, so add it to a commit at this point.<\/p>\n<p>Finally, open up an editor and create <code>exceldiff.cmd<\/code> in the correct location (as specified in <code>.git\/config<\/code>):<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">@<\/span><span class=\"k\">echo<\/span> off\nc<span class=\"p\">:<\/span><span class=\"nl\">\\apps\\excelcompare\\excel_cmp.bat<\/span><span class=\"c1\"> %2 %5<\/span>\n<\/code><\/pre><\/div>\n\n<p>(Adjust the path to <code>excel_cmp.bat<\/code> so that it matches the location where you unpacked ExcelCompare.)<\/p>\n<p>Why arguments <strong>two<\/strong> and <strong>five<\/strong>? It&rsquo;s because Git passes seven arguments to a diff command, of \nwhich the second is the path to the old file (which likely is a temporary file) and the fifth is\nthe path to the new file. For more detailed information, have a look at the \n<a href=\"http:\/\/git-scm.com\/docs\/git\">Git documentation<\/a>, specifically under GIT_EXTERNAL_DIFF.<\/p>\n<h2>Back to diffing<\/h2>\n<p>Once the script has been saved, we can attempt the diff again:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"gp\">$ <\/span>git<span class=\"w\"> <\/span>diff<span class=\"w\"> <\/span>document.xlsx\n<span class=\"go\">DIFF  Cell at     Sheet1!A3 =&gt; &#39;X&#39; v\/s &#39;Y&#39;<\/span>\n<span class=\"go\">----------------- DIFF -------------------<\/span>\n<span class=\"go\">Sheets: [Sheet1]<\/span>\n<span class=\"go\">Rows: [3]<\/span>\n<span class=\"go\">Cols: [A]<\/span>\n<span class=\"go\">----------------- EXTRA WB1 -------------------<\/span>\n<span class=\"go\">Sheets: []<\/span>\n<span class=\"go\">Rows: []<\/span>\n<span class=\"go\">Cols: []<\/span>\n<span class=\"go\">----------------- EXTRA WB2 -------------------<\/span>\n<span class=\"go\">Sheets: []<\/span>\n<span class=\"go\">Rows: []<\/span>\n<span class=\"go\">Cols: []<\/span>\n<span class=\"go\">-----------------------------------------<\/span>\n<span class=\"go\">Excel files C:\\...\\AppData\\Local\\Temp\\TRAkga_document.xlsx and document.xlsx differ<\/span>\n<\/code><\/pre><\/div>\n\n<p>This is the raw output from ExcelCompare. As can be seen, the uncommitted change is apparently\nthat I changed the value of cell A3 on sheet Sheet1 from X to Y (which happens to be exactly\nwhat I did).<\/p>\n<p>And that&rsquo;s it! Much, much more useful than before!<\/p>\n<h2>A small note<\/h2>\n<p>As can be seen from the example above, the diff output doesn&rsquo;t have the same format as\na &ldquo;native&rdquo; textual Git diff, which may look like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"gp\">$ <\/span>git<span class=\"w\"> <\/span>diff<span class=\"w\"> <\/span>foo\n<span class=\"go\">diff --git a\/foo b\/foo<\/span>\n<span class=\"go\">index 9972d7e..8320b47 100644<\/span>\n<span class=\"go\">--- a\/foo<\/span>\n<span class=\"go\">+++ b\/foo<\/span>\n<span class=\"go\">@@ -1,2 +1,2 @@<\/span>\n<span class=\"go\">-bar<\/span>\n<span class=\"go\">+baz<\/span>\n<\/code><\/pre><\/div>\n\n<p>Specifically, the initial metadata lines are not present, and the differences are\nnot in patch format. This means that an Excel diff cannot be used for patching an Excel\nfile. If you attempt to use <code>git format-patch<\/code>, you&rsquo;ll see that it just ignores the Excel diff.<\/p>\n<h2>Summary<\/h2>\n<p>In this post, I have shown how to configure a Git repository to use a custom command for\nshowing the difference between different revisions of an Excel file. If you found it useful,\nplease let me know in the comments!<\/p>\n<h3>Update 2016-04-17<\/h3>\n<ul>\n<li>Fixed some typos.<\/li>\n<li>Fixed incorrect <code>.git\/config<\/code> entry.<\/li>\n<li>Added a paragraph about committing the <code>.gitattributes<\/code> files.<\/li>\n<\/ul>","category":[{"@attributes":{"term":"Tools"}},{"@attributes":{"term":"git"}},{"@attributes":{"term":"diff"}},{"@attributes":{"term":"excel"}}]},{"title":"How Enumerable.Concat brought down a production server","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/how-enumerableconcat-brought-down-a-production-server.html","rel":"alternate"}},"published":"2014-11-26T23:30:00+01:00","updated":"2014-11-26T23:30:00+01:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2014-11-26:\/how-enumerableconcat-brought-down-a-production-server.html","summary":"<p>TL;DR Using <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/vstudio\/bb302894.aspx\" title=\"Enumerable.Concat at MSDN\">Enumerable.Concat<\/a> to build a long sequence one item at a time is a particularly bad idea, since enumerating the items will consume a lot of stack space.<\/p>\n<p>A while ago, a customer reported that our .NET application running in IIS started crashing on user registration after \u2026<\/p>","content":"<p>TL;DR Using <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/vstudio\/bb302894.aspx\" title=\"Enumerable.Concat at MSDN\">Enumerable.Concat<\/a> to build a long sequence one item at a time is a particularly bad idea, since enumerating the items will consume a lot of stack space.<\/p>\n<p>A while ago, a customer reported that our .NET application running in IIS started crashing on user registration after an application\nupgrade. The crash happened as the application was about to send an activation e-mail. Since there had been no changes to this particular\ncode since the last version, this was quite a mystery. Furthermore, since the crash didn&rsquo;t happen on a test server, I suspected an\nenvironmental problem. In the end, it turned out to be an environmental factor that revealed a bug in the code.<\/p>\n<p>It&rsquo;s of course impossible to fix something based on suspicions - you need hard evidence. After more testing on a copy of the production\nserver, we could pinpoint the problem to updating a user in general (which happens during user registration) rather than sending e-mail - changing user\nsettings would reliably reproduce the crash. After studying the Windows event log while doing so, I got the hard evidence I needed:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>...\nFaulting application name: w3wp.exe, ...\n...\nException code: 0xc00000fd\n...\n<\/code><\/pre><\/div>\n\n<p>0xc00000fd is STATUS_STACK_OVERFLOW, i.e. a <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.stackoverflowexception.aspx\" title=\"StackOverflowException at MSDN\">StackOverflowException<\/a> was thrown. The next step was to figure out where it came from. To do that, I\ndownloaded  <a href=\"http:\/\/www.microsoft.com\/en-us\/download\/details.aspx?id=42933\" title=\"Debug Diagnostic Tool\">Debug Diagnostic Tool<\/a> (DebugDiag) from Microsoft and installed it on the production server. I found a useful <a href=\"http:\/\/www.codeproject.com\/Articles\/93138\/Diagnosing-Tricky-ASP-NET-Production-Issues-with-D\" title=\"Diagnosing Tricky ASP.NET Production Issues with DebugDiag and winDbg\">CodeProject article<\/a> about how to use \nDebugDiag. While it is written for an older version than the one I installed (v2 Update 1), the only difference I found was that DebugDiag nowadays is split into two applications, \nDebugDiag Collection and DebugDiag Analysis.<\/p>\n<p>By using DebugDiag to collect and analyze a process dump, I was able to pinpoint the location in the application code that caused the crash. The code was part of\nan in-memory index, and was quite innocent-looking:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">newEnum<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">@enum<\/span><span class=\"p\">.<\/span><span class=\"n\">Where<\/span><span class=\"p\">(<\/span><span class=\"n\">item<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">someItem<\/span><span class=\"w\"> <\/span><span class=\"o\">!=<\/span><span class=\"w\"> <\/span><span class=\"n\">item<\/span><span class=\"p\">).<\/span><span class=\"n\">ToList<\/span><span class=\"p\">();<\/span>\n<\/code><\/pre><\/div>\n\n<p>In other words, enumerate items, exclude a particular one and create a list out of the result. What this line resulted in was the following stack trace:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>...\nSystem_Core_ni!System.Linq.Enumerable+&lt;ConcatIterator&gt;d__71`1[[System.__Canon, mscorlib]].MoveNext()+126 \nSystem_Core_ni!System.Linq.Enumerable+&lt;ConcatIterator&gt;d__71`1[[System.__Canon, mscorlib]].MoveNext()+126 \nSystem_Core_ni!System.Linq.Enumerable+&lt;ConcatIterator&gt;d__71`1[[System.__Canon, mscorlib]].MoveNext()+126 \nSystem_Core_ni!System.Linq.Enumerable+&lt;ConcatIterator&gt;d__71`1[[System.__Canon, mscorlib]].MoveNext()+126 \nSystem_Core_ni!System.Linq.Enumerable+&lt;ConcatIterator&gt;d__71`1[[System.__Canon, mscorlib]].MoveNext()+126 \nSystem_Core_ni!System.Linq.Enumerable+&lt;ConcatIterator&gt;d__71`1[[System.__Canon, mscorlib]].MoveNext()+126 \n...\n<\/code><\/pre><\/div>\n\n<p><code>ConcatIterator<\/code> is a method called from <code>Enumerable.Concat<\/code> that yields results from the two enumerables that are concatenated together:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">private<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"n\">IEnumerable<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">TSource<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">ConcatIterator<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">TSource<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">(<\/span><span class=\"n\">IEnumerable<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">TSource<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">first<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">IEnumerable<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">TSource<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">second<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">{<\/span>\n<span class=\"w\">  <\/span><span class=\"k\">foreach<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">TSource<\/span><span class=\"w\"> <\/span><span class=\"n\">source<\/span><span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"n\">first<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">yield<\/span><span class=\"w\"> <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">source<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">  <\/span><span class=\"k\">foreach<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">TSource<\/span><span class=\"w\"> <\/span><span class=\"n\">source<\/span><span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"n\">second<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">yield<\/span><span class=\"w\"> <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">source<\/span><span class=\"p\">;<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Concatenating enumerables is in general not a problem, nor is enumerating the result. However, in this case a one-item enumerable was extended\none item at a time using <code>Enumerable.Concat<\/code>, like so:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\">\/\/ initial creation:<\/span>\n<span class=\"n\">@enum<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"p\">[]<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"n\">item<\/span><span class=\"w\"> <\/span><span class=\"p\">};<\/span>\n<span class=\"c1\">\/\/ later on, done repeatedly:<\/span>\n<span class=\"n\">@enum<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">@enum<\/span><span class=\"p\">.<\/span><span class=\"n\">Concat<\/span><span class=\"p\">(<\/span><span class=\"k\">new<\/span><span class=\"p\">[]<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"n\">itemToAppend<\/span><span class=\"w\"> <\/span><span class=\"p\">});<\/span>\n<\/code><\/pre><\/div>\n\n<p>And herein lies the bug.\nWhen I wrote this code, I thought of it as building a linear sequence of identifiers, but what it does is rather\nthe opposite - it builds an unbalanced binary tree. This is fairly obvious if you think about it for a second,\nwhich I clearly didn&rsquo;t, so this entire thing is a bit embarassing&hellip; Anyway, here&rsquo;s an illustation of what happens:<\/p>\n<p><img alt=\"tree\" src=\".\/images\/enumerable-concat-tree.png\" title=\"Enumerable.Concat tree\" \/><\/p>\n<p>In the first step (left), we have the initial enumerable (array) of a single item (black). When we concatenate with another\nenumerable (array) of one item (white), we get the tree in the middle, where the resulting enumerable (grey) refers to \nits two constituent enumerables. Another concatenation, and we get the tree to the right, where another level has\nbeen added. Continue concatenating, and the tree will grow quite high.<\/p>\n<p>To enumerate items, <code>ConcatIterator<\/code> effectively does a depth-first traversal of the entire tree structure. And that eats as many stack\nframes as the tree is high, which corresponds to the number of items in the tree.<\/p>\n<p>The solution was simple: Just use a regular list instead of building a super-concatenated enumerable.<\/p>\n<p>There&rsquo;s one more thing I&rsquo;d like to share. I rarely, if ever, fix a bug without reproducing it in a test case. Given the same number of items\nas on the production server, I couldn&rsquo;t reproduce the crash though. It was first when I increased the number of items quite a bit that I\nsaw the crash. The explanation for this is documented in this <a href=\"http:\/\/support.microsoft.com\/kb\/932909\" title=\"Microsoft Knowledge Base\">Knowledge Base article<\/a>:<\/p>\n<blockquote>\n<p>In Windows Server 2008 and higher, the maximum stack size of a thread running\non 32-bit version of IIS is 256 KB, and on an x64 server is 512 KB.<\/p>\n<\/blockquote>\n<p>However, the default stack size of a thread in Windows is 1 MB, and that&rsquo;s what I got when running my test case.<\/p>\n<p>By the way, the reason the application worked on the test server? Fewer items in the in-memory index!<\/p>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":".net"}},{"@attributes":{"term":"linq"}},{"@attributes":{"term":"iis"}}]},{"title":"The mysteriously escaped request path in ASP.NET","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/the-mysteriously-escaped-request-path-in-aspnet.html","rel":"alternate"}},"published":"2013-11-19T22:30:00+01:00","updated":"2013-11-19T22:30:00+01:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2013-11-19:\/the-mysteriously-escaped-request-path-in-aspnet.html","summary":"<p>This blog post answers the question &ldquo;Why does <code>Uri.AbsolutePath<\/code> sometimes return an escaped path and sometimes an unescaped path\nfor the request URL in an ASP.NET application?&rdquo;<\/p>\n<p>I spent some time googling for a possible reason, but search terms like URL\/URI, request, path, encoding, and escaping are \u2026<\/p>","content":"<p>This blog post answers the question &ldquo;Why does <code>Uri.AbsolutePath<\/code> sometimes return an escaped path and sometimes an unescaped path\nfor the request URL in an ASP.NET application?&rdquo;<\/p>\n<p>I spent some time googling for a possible reason, but search terms like URL\/URI, request, path, encoding, and escaping are so overloaded that the\nsignal-to-noise ratio is extremely low. My searches turned up nothing.<\/p>\n<p>Some background first! For a web application at work, we use a REST server built with <a href=\"http:\/\/nancyfx.org\/\" title=\"Nancy web site\">Nancy<\/a>. After a recent upgrade, we\nnoticed that images (non-static, loaded via the REST API) with pluses in their names stopped working. Instead of getting images\nback, we got 404 responses.<\/p>\n<p>Checking the logs, we found that when Nancy saw the image path parameter of the request, pluses had been converted into spaces.\nAt this point, an alarm bell rang, of course! <a href=\"http:\/\/tools.ietf.org\/html\/rfc3986\" title=\"RFC 3986\">RFC 3986<\/a> (Uniform Resource Identifier (URI): Generic Syntax) defines\nplus (+) as a reserved character, but does not give it any\nspecial meaning in the path component of an URI. Furthermore, <a href=\"http:\/\/tools.ietf.org\/html\/rfc2616\" title=\"RFC 2616\">RFC 2616<\/a> (Hypertext Transfer Protocol - HTTP\/1.1)\nrefers to a predecessor of RFC 3986 as defining the meaning of a path component, among other things.\nThus, a plus character in a path component should not be escaped in any way. Replacing pluses with spaces comes\nfrom the form content type <a href=\"http:\/\/www.w3.org\/TR\/html401\/interact\/forms.html#h-17.13.4.1\" title=\"HTML 4.01 Forms\">application\/x-www-form-urlencoded<\/a> used in HTML. So, this appeared to be a Nancy bug, and\nwe found the issue to have been <a href=\"https:\/\/github.com\/NancyFx\/Nancy\/issues\/1280\" title=\"Nancy issue 1280 @ GitHub\">reported already<\/a>, albeit in a slightly different context.<\/p>\n<p>Now to the strange part. On our build server, running Windows Server 2012 and IIS 8.0, we observed the bug in action. However, on\nmy development machine running Windows 8.1 and IIS 8.5, the bug did not show. Why was that? To understand what was happening, I\ndecided to exclude Nancy and write a simple HTTP handler of my own:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">Handler<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">IHttpHandler<\/span>\n<span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">ProcessRequest<\/span><span class=\"p\">(<\/span><span class=\"n\">HttpContext<\/span><span class=\"w\"> <\/span><span class=\"n\">context<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">context<\/span><span class=\"p\">.<\/span><span class=\"n\">Response<\/span><span class=\"p\">.<\/span><span class=\"n\">StatusCode<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"m\">200<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">        <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">url<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">context<\/span><span class=\"p\">.<\/span><span class=\"n\">Request<\/span><span class=\"p\">.<\/span><span class=\"n\">Url<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">using<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">writer<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span>\n<span class=\"w\">            <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"nf\">StreamWriter<\/span><span class=\"p\">(<\/span><span class=\"n\">context<\/span><span class=\"p\">.<\/span><span class=\"n\">Response<\/span><span class=\"p\">.<\/span><span class=\"n\">OutputStream<\/span><span class=\"p\">))<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">writer<\/span><span class=\"p\">.<\/span><span class=\"n\">WriteLine<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;Request.Path = &quot;<\/span><span class=\"w\"> <\/span><span class=\"o\">+<\/span><span class=\"w\"> <\/span><span class=\"n\">context<\/span><span class=\"p\">.<\/span><span class=\"n\">Request<\/span><span class=\"p\">.<\/span><span class=\"n\">Path<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">writer<\/span><span class=\"p\">.<\/span><span class=\"n\">WriteLine<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;Request.Url.AbsolutePath = &quot;<\/span><span class=\"w\"> <\/span><span class=\"o\">+<\/span>\n<span class=\"w\">                <\/span><span class=\"n\">url<\/span><span class=\"p\">.<\/span><span class=\"n\">AbsolutePath<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">writer<\/span><span class=\"p\">.<\/span><span class=\"n\">WriteLine<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;Request.Url.OriginalString = &quot;<\/span><span class=\"w\"> <\/span><span class=\"o\">+<\/span>\n<span class=\"w\">                <\/span><span class=\"n\">url<\/span><span class=\"p\">.<\/span><span class=\"n\">OriginalString<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Deploying my little HTTP handler to our build server and locally, I saw:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>curl<span class=\"w\"> <\/span>http:\/\/remote.server.com\/a+b\nRequest.Path<span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span>\/a+b\nRequest.Url.AbsolutePath<span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span>\/a+b\nRequest.Url.OriginalString<span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span>http:\/\/remote.server.com\/a+b\n\n$<span class=\"w\"> <\/span>curl<span class=\"w\"> <\/span>http:\/\/localhost:15080\/a+b\nRequest.Path<span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span>\/a+b\nRequest.Url.AbsolutePath<span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span>\/a%2Bb\nRequest.Url.OriginalString<span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span>http:\/\/localhost:15080\/a%2Bb\n<\/code><\/pre><\/div>\n\n<p>Now we&rsquo;re getting somewhere! Locally, the <code>AbsolutePath<\/code> property of <code>Request.Url<\/code> (which is of type <code>System.Uri<\/code>) contained an\n<strong>escaped<\/strong> path. Remotely, the path was <strong>not escaped<\/strong>. As can be seen above, the difference in escaping was also reflected in the value of the\n<code>OriginalString<\/code> property, which is the string with which the <code>Uri<\/code> object was created in the first place! This indicated that\neither there was a difference in how the .NET framework produced the <code>Uri<\/code> objects between the machines, or there was a difference\nin how the IIS servers where configured, possibly because of the version difference.<\/p>\n<p>Since I couldn&rsquo;t find any differences in the IIS configurations, and no relevant information regarding changes between IIS 8.0 and\n8.5 (again, low signal-to-noise ratio in search results), I started digging into the .NET framework code!<\/p>\n<p>After spending more time reading .NET code than I would like to admit, I finally found the culprit: an application setting by\nthe name &ldquo;<strong>aspnet:UseLegacyRequestUrlGeneration<\/strong>.&rdquo; The <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/hh975440.aspx\" title=\"MSDN documentation for aspnet:UseLegacyRequestUrlGeneration\">documentation<\/a> for the setting is essentially\nworthless. It simply states that with the setting set to <code>false<\/code>, <strong>the default value<\/strong>, &ldquo;the ASP.NET runtime generates a Uri that has better standards\ncompliance than previous versions of ASP.NET.&rdquo; Some reflections on this:<\/p>\n<ul>\n<li>The setting cannot be found on the .NET 4.5 version of the page, indicating that it was introduced with .NET 4.5.1.<\/li>\n<li>The default value changes the behavior of how request URIs are passed to HTTP handler. That&rsquo;s right, the behavior changes\n  in a minor update of the framework. Way to go, Microsoft!<\/li>\n<li>Which standards are better complied to? Given that pluses in URI paths should not be escaped (at least as far as I can tell),\n  I would say that that there is at least one standard being complied to in a worse way.<\/li>\n<li>The method responsible for escaping is\n  <code>Uri.EscapeDataString<\/code>, the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.uri.escapedatastring(v=vs.110).aspx\" title=\"MSDN documentation for Uri.EscapeDataString\">documentation of which<\/a> indicates that reserved characters like plus are\n  escaped.<\/li>\n<\/ul>\n<p>Now, our build server had .NET 4 and my local machine .NET 4.5.1, so this was clearly the reason for the difference in escaping.\nAlso, setting the application setting\nto <code>true<\/code> in Web.config changed the behavior as expected:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nt\">&lt;configuration&gt;<\/span>\n<span class=\"w\">    <\/span><span class=\"nt\">&lt;appSettings&gt;<\/span>\n<span class=\"w\">        <\/span><span class=\"nt\">&lt;add<\/span><span class=\"w\"> <\/span><span class=\"na\">key=<\/span><span class=\"s\">&quot;aspnet:UseLegacyRequestUrlGeneration&quot;<\/span><span class=\"w\"> <\/span><span class=\"na\">value=<\/span><span class=\"s\">&quot;true&quot;<\/span><span class=\"w\"> <\/span><span class=\"nt\">\/&gt;<\/span>\n<span class=\"w\">    <\/span><span class=\"nt\">&lt;\/appSettings&gt;<\/span>\n<\/code><\/pre><\/div>\n\n<p><br\/><\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>curl<span class=\"w\"> <\/span>http:\/\/localhost:15080\/a+b\nRequest.Path<span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span>\/a+b\nRequest.Url.AbsolutePath<span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span>\/a+b\nRequest.Url.OriginalString<span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span>http:\/\/localhost:15080\/a+b\n<\/code><\/pre><\/div>\n\n<p>How do you check the value of the setting, given that it doesn&rsquo;t exist prior to .NET 4.5.1? Unfortunately, I didn&rsquo;t find a decent\nway to do it, but some reflection hacking does the trick:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"kt\">bool<\/span><span class=\"w\"> <\/span><span class=\"nf\">UseLegacyRequestUrlGeneration<\/span><span class=\"p\">()<\/span>\n<span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">appSettingsType<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">typeof<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">System<\/span><span class=\"p\">.<\/span><span class=\"n\">Web<\/span><span class=\"p\">.<\/span><span class=\"n\">Util<\/span><span class=\"p\">.<\/span><span class=\"n\">HttpEncoder<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">.<\/span><span class=\"n\">Assembly<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">.<\/span><span class=\"n\">GetTypes<\/span><span class=\"p\">()<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">.<\/span><span class=\"n\">FirstOrDefault<\/span><span class=\"p\">(<\/span><span class=\"n\">t<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">t<\/span><span class=\"p\">.<\/span><span class=\"n\">Name<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;AppSettings&quot;<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">prop<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">appSettingsType<\/span><span class=\"w\"> <\/span><span class=\"o\">!=<\/span><span class=\"w\"> <\/span><span class=\"k\">null<\/span>\n<span class=\"w\">        <\/span><span class=\"o\">?<\/span><span class=\"w\"> <\/span><span class=\"n\">appSettingsType<\/span><span class=\"p\">.<\/span><span class=\"n\">GetProperty<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;UseLegacyRequestUrlGeneration&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span>\n<span class=\"w\">            <\/span><span class=\"n\">BindingFlags<\/span><span class=\"p\">.<\/span><span class=\"n\">Static<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"n\">BindingFlags<\/span><span class=\"p\">.<\/span><span class=\"n\">NonPublic<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span>\n<span class=\"w\">        <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"k\">null<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">prop<\/span><span class=\"w\"> <\/span><span class=\"o\">!=<\/span><span class=\"w\"> <\/span><span class=\"k\">null<\/span><span class=\"w\"> <\/span><span class=\"o\">?<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"kt\">bool<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"n\">prop<\/span><span class=\"p\">.<\/span><span class=\"n\">GetValue<\/span><span class=\"p\">(<\/span><span class=\"k\">null<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"k\">null<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"k\">true<\/span><span class=\"p\">;<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>The method reads the setting from the internal <code>System.Web.Util.AppSettings<\/code> class, and if the corresponding property does not\nexist, it returns <code>true<\/code> since pre-4.5.1 behavior is considered legacy.<\/p>\n<p>Back to Nancy then. Why didn&rsquo;t I observe the bug locally? Because instead of decoding plus into a space, it now decoded &ldquo;%2B&rdquo; into a plus!\nThe issue at hand must clearly be fixed, but for the Nancy.Hosting.Aspnet project, it is important to also consider\nthe value of the &ldquo;aspnet:UseLegacyRequestUrlGeneration&rdquo; setting, because the HTTP handler uses <code>Uri.AbsolutePath<\/code> to construct\nthe request URL passed into the Nancy core.<\/p>\n<hr \/>\n<p>Side notes:<\/p>\n<ul>\n<li>\n<p>For IIS to accept a request URL containing a plus in a path segment, you must turn on <code>allowDoubleEscaping<\/code> in Web.config:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nt\">&lt;configuration&gt;<\/span>\n<span class=\"w\">    <\/span><span class=\"nt\">&lt;system.webServer&gt;<\/span>\n<span class=\"w\">        <\/span><span class=\"nt\">&lt;security&gt;<\/span>\n<span class=\"w\">            <\/span><span class=\"nt\">&lt;requestFiltering<\/span><span class=\"w\"> <\/span><span class=\"na\">allowDoubleEscaping=<\/span><span class=\"s\">&quot;true&quot;<\/span><span class=\"w\"> <\/span><span class=\"nt\">\/&gt;<\/span>\n<span class=\"w\">        <\/span><span class=\"nt\">&lt;\/security&gt;<\/span>\n<\/code><\/pre><\/div>\n\n<\/li>\n<li>\n<p>To use a custom HTTP handler, add it to Web.config like so:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nt\">&lt;configuration&gt;<\/span>\n<span class=\"w\">    <\/span><span class=\"nt\">&lt;system.webServer&gt;<\/span>\n<span class=\"w\">        <\/span><span class=\"nt\">&lt;handlers&gt;<\/span>\n<span class=\"w\">            <\/span><span class=\"nt\">&lt;add<\/span><span class=\"w\"> <\/span><span class=\"na\">name=<\/span><span class=\"s\">&quot;MyHandler&quot;<\/span><span class=\"w\"> <\/span><span class=\"na\">verb=<\/span><span class=\"s\">&quot;*&quot;<\/span>\n<span class=\"w\">                 <\/span><span class=\"na\">type=<\/span><span class=\"s\">&quot;SomeAssembly.SomeHandler&quot;<\/span>\n<span class=\"w\">                 <\/span><span class=\"na\">path=<\/span><span class=\"s\">&quot;*&quot;<\/span><span class=\"w\"> <\/span><span class=\"nt\">\/&gt;<\/span>\n<span class=\"w\">        <\/span><span class=\"nt\">&lt;\/handlers&gt;<\/span>\n<\/code><\/pre><\/div>\n\n<\/li>\n<\/ul>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"asp.net"}},{"@attributes":{"term":"nancy"}},{"@attributes":{"term":"uri"}}]},{"title":"How git changed my commit behavior","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/how-git-changed-my-commit-behavior.html","rel":"alternate"}},"published":"2013-10-11T12:00:00+02:00","updated":"2013-10-11T12:00:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2013-10-11:\/how-git-changed-my-commit-behavior.html","summary":"<p>Git is my version control system of choice nowadays. Its feature set fits extremely\nwell with my usual software development workflow, and there are so many aspects of\ngit that I could write about, but this particular blog post is about commit behavior.<\/p>\n<p>There is nothing religious about this post \u2026<\/p>","content":"<p>Git is my version control system of choice nowadays. Its feature set fits extremely\nwell with my usual software development workflow, and there are so many aspects of\ngit that I could write about, but this particular blog post is about commit behavior.<\/p>\n<p>There is nothing religious about this post, as I&rsquo;m not religious about git. It baffles\nme how people can be religious over a certain piece of technology and it seems as if\nversion control systems in particular trigger a lot of emotional responses. But I digress.<\/p>\n<p>In the past, I have used CVS, SourceSafe, Subversion and ClearCase. While they are quite\ndifferent in many ways, with these I always felt that the primary vehicle of change is \nthe file; what you check in to the VCS is a number of edits to a number of files, at best\nheld together by a common check in message or tag. But when you look at what&rsquo;s in the VCS,\nit&rsquo;s still just a set of files. You may disagree with this, but that was the feeling I had\nwhen using them.<\/p>\n<p>When I started using git, things changed drastically. The primary vehicle of change was now\nthe commit instead of the file. A commit is a single entity that captures a change. That\nchange may of course be distributed over a number of files, but all the edits are held\ntogether by something stronger than a message.<\/p>\n<p>Dealing with commits instead of files opens up for a lot of interesting workflow changes.\nIn my team back then, we started using <a href=\"http:\/\/code.google.com\/p\/gerrit\/\" title=\"Gerrit Code Review\">Gerrit<\/a> for gated checkins. A colleague\nhad to review a commit as encapsulating a single change, and could reject it for a number\nof reasons, such as:<\/p>\n<ul>\n<li>It is too big and thus too hard to review.<\/li>\n<li>It does not, in fact, contain a single change, meaning that it is not coherent.<\/li>\n<li>It mixes changes to functionality with changes to formatting.<\/li>\n<li>It is not consistent with other commits in a series of commits.<\/li>\n<\/ul>\n<p>Pretty quickly, a number of rules for what constitutes a good commit emerged, and with that\na behavior of making small, coherent commits that &ldquo;get to the point.&rdquo; And the great thing\nwith git is that it provides tools for splitting up a bad commit into manageable pieces if\nyou for some reason should end up with one. Go ahead and lookup <a href=\"https:\/\/www.kernel.org\/pub\/software\/scm\/git\/docs\/git-rebase.html\" title=\"git-rebase(1) Manual Page\"><code>git rebase -i<\/code><\/a> and\n<a href=\"https:\/\/www.kernel.org\/pub\/software\/scm\/git\/docs\/git-add.html\" title=\"git-add(1) Manual Page\"><code>git add -p\/-i<\/code><\/a>, for example!<\/p>\n<p>If I have to pick a single git feature that I think mostly affects good commit behavior I choose\n<a href=\"https:\/\/www.kernel.org\/pub\/software\/scm\/git\/docs\/git-revert.html\" title=\"git-revert(1) Manual Page\"><code>git revert<\/code><\/a>. Given a commit, <code>git revert<\/code> adds a new commit that is the exact inverse, thus\ncanceling out the old one. How well this works obviously depends on what has happened since that\nold commit was added, but in essence undoing a change is very straightforward. A colleague once\nhad to undo a change in ClearCase, and his hair was a lot thinner when he was finished&hellip;<\/p>\n<p>So what does <code>git revert<\/code> has to do with commit behavior? Well, I always think about what happens\nif I need to undo a certain change, i.e. revert the corresponding commit. In other words, I consider\nthe &ldquo;<em>revertability<\/em>&rdquo; of commits I make. If I pack two changes into a single commit, I will lose\nboth if I need to undo one. If I do some code cleanup together with a change, just because I&rsquo;m\n&ldquo;touching the file anyway,&rdquo; the entropy will increase again as I undo the change. If I format code\nwith a change&hellip; Well, you get the point!<\/p>\n<p>Once you start thinking in terms of commit revertability, following the rules of a good commit comes\nnaturally:<\/p>\n<ul>\n<li>Keep it small and manageable.<\/li>\n<li>Only pack a single change.<\/li>\n<li>Stick to a single theme - functionality change, bug fix, code cleanup, code formatting, etc.<\/li>\n<li>If you&rsquo;re on a feature branch, keep all commits in line with the feature.<\/li>\n<\/ul>\n<p>I&rsquo;m sure there are other version control systems that are comparable to git in terms of what I have\njust described, and that&rsquo;s fine. I&rsquo;m not saying that git is unique. My point is that once I became\nfamiliar with git, my commit behavior had changed from being file oriented to being change oriented,\nwhich from a software development perspective makes a lot more sense!<\/p>\n<p>What&rsquo;s your commit behavior?<\/p>","category":[{"@attributes":{"term":"Opinion"}},{"@attributes":{"term":"git"}},{"@attributes":{"term":"vcs"}},{"@attributes":{"term":"commit"}}]},{"title":"Why I hate implicit return in CoffeeScript","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/why-i-hate-implicit-return-in-coffeescript.html","rel":"alternate"}},"published":"2012-10-26T13:04:00+02:00","updated":"2012-10-26T13:04:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2012-10-26:\/why-i-hate-implicit-return-in-coffeescript.html","summary":"<p>CoffeeScript is &ldquo;a little language that compiles into JavaScript.&rdquo; If\nyou haven&rsquo;t seen or tried it, go <a href=\"http:\/\/coffeescript.org\/\">check it out<\/a>! I&rsquo;ve been using it in\na project for a while now, and its obvious advantage over pure\nJavaScript is that it is very concise and has high expressive \u2026<\/p>","content":"<p>CoffeeScript is &ldquo;a little language that compiles into JavaScript.&rdquo; If\nyou haven&rsquo;t seen or tried it, go <a href=\"http:\/\/coffeescript.org\/\">check it out<\/a>! I&rsquo;ve been using it in\na project for a while now, and its obvious advantage over pure\nJavaScript is that it is very concise and has high expressive power. For\nexample, <a href=\"http:\/\/coffeescript.org\/#loops\">comprehensions<\/a> takes away a whole class of tedious\nprogramming problems. Instead of writing this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nx\">names<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"p\">[];<\/span>\n<span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nx\">i<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mf\">0<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"nx\">i<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;<\/span><span class=\"w\"> <\/span><span class=\"nx\">persons<\/span><span class=\"p\">.<\/span><span class=\"nx\">length<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"nx\">i<\/span><span class=\"o\">++<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">names<\/span><span class=\"p\">.<\/span><span class=\"nx\">push<\/span><span class=\"p\">(<\/span><span class=\"nx\">persons<\/span><span class=\"p\">[<\/span><span class=\"nx\">i<\/span><span class=\"p\">].<\/span><span class=\"nx\">name<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>You write this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nv\">names<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"nx\">p<\/span><span class=\"p\">.<\/span><span class=\"nx\">name<\/span><span class=\"w\"> <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"nx\">p<\/span><span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"nx\">persons<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>Neat! Another great feature is the lambda-like anonymous function\nsyntax. Instead of:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">array<\/span><span class=\"p\">.<\/span><span class=\"nx\">sort<\/span><span class=\"p\">(<\/span><span class=\"kd\">function<\/span><span class=\"p\">(<\/span><span class=\"nx\">a<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"nx\">b<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"nx\">a<\/span><span class=\"p\">.<\/span><span class=\"nx\">index<\/span><span class=\"w\"> <\/span><span class=\"o\">-<\/span><span class=\"w\"> <\/span><span class=\"nx\">b<\/span><span class=\"p\">.<\/span><span class=\"nx\">index<\/span><span class=\"p\">;<\/span>\n<span class=\"p\">});<\/span>\n<\/code><\/pre><\/div>\n\n<p>You write:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">array<\/span><span class=\"p\">.<\/span><span class=\"nx\">sort<\/span><span class=\"p\">(<\/span><span class=\"nf\">(a, b) -&gt;<\/span><span class=\"w\">  <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"nx\">a<\/span><span class=\"p\">.<\/span><span class=\"nx\">index<\/span><span class=\"w\"> <\/span><span class=\"o\">-<\/span><span class=\"w\"> <\/span><span class=\"nx\">b<\/span><span class=\"p\">.<\/span><span class=\"nx\">index<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>But it can get even more concise! Parentheses are optional and so is the\n<code>return<\/code> keyword. Thus, a shorter version is:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">array<\/span><span class=\"p\">.<\/span><span class=\"nx\">sort<\/span><span class=\"w\"> <\/span><span class=\"nf\">(a, b) -&gt;<\/span><span class=\"w\"> <\/span><span class=\"nx\">a<\/span><span class=\"p\">.<\/span><span class=\"nx\">index<\/span><span class=\"w\"> <\/span><span class=\"o\">-<\/span><span class=\"w\"> <\/span><span class=\"nx\">b<\/span><span class=\"p\">.<\/span><span class=\"nx\">index<\/span>\n<\/code><\/pre><\/div>\n\n<p>The reason this works is that <a href=\"http:\/\/coffeescript.org\/#expressions\">everything in CoffeeScript is an\nexpression<\/a>. But while it allows you to write more expressive code, it\ncan also have very surprising side effects. And in general, I don&rsquo;t like\nwhen a programming language <a href=\"https:\/\/programmaticallyspeaking.com\/nothing-surprises-me-in-vbnet.html\" title=\"Nothing surprises me in VB.NET\">surprises me<\/a>! No, not in general. Never!<\/p>\n<p>I will show two examples where implicit return can be very surprising:<\/p>\n<h2>1) Returning the value of a for loop<\/h2>\n<p>Consider the following contrived and pointless, but ultimately pretty\ninnocent JavaScript code:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nx\">dostuff<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"kd\">function<\/span><span class=\"p\">(<\/span><span class=\"nx\">i<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"p\">};<\/span>\n\n<span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nx\">x<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"kd\">function<\/span><span class=\"p\">(<\/span><span class=\"nx\">n<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nx\">i<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mf\">0<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"nx\">i<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;<\/span><span class=\"w\"> <\/span><span class=\"nx\">n<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"nx\">i<\/span><span class=\"o\">++<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"nx\">dostuff<\/span><span class=\"p\">(<\/span><span class=\"nx\">i<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">};<\/span>\n\n<span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nx\">start<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"ow\">new<\/span><span class=\"w\"> <\/span><span class=\"nb\">Date<\/span><span class=\"p\">().<\/span><span class=\"nx\">getTime<\/span><span class=\"p\">();<\/span>\n<span class=\"nx\">x<\/span><span class=\"p\">(<\/span><span class=\"mf\">1000000000<\/span><span class=\"p\">);<\/span>\n<span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nx\">elapsed<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"ow\">new<\/span><span class=\"w\"> <\/span><span class=\"nb\">Date<\/span><span class=\"p\">().<\/span><span class=\"nx\">getTime<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"o\">-<\/span><span class=\"w\"> <\/span><span class=\"nx\">start<\/span><span class=\"p\">;<\/span>\n<span class=\"nx\">console<\/span><span class=\"p\">.<\/span><span class=\"nx\">log<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;Time in ms = &quot;<\/span><span class=\"w\"> <\/span><span class=\"o\">+<\/span><span class=\"w\"> <\/span><span class=\"nx\">elapsed<\/span><span class=\"p\">);<\/span>\n<\/code><\/pre><\/div>\n\n<p>This piece of code does absolutely nothing, but it does nothing one\nbillion times! Node.js version 0.6.7 runs it in just under 7 seconds on\none of my VMs. What would the corresponding CoffeeScript code look like?\nA na\u00efve translation would probably result in something like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nv\">dostuff<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"nf\">(i) -&gt;<\/span>\n\n<span class=\"nv\">x<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"nf\">(n) -&gt;<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"nx\">i<\/span><span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"mi\">0<\/span><span class=\"p\">...<\/span><span class=\"nx\">n<\/span><span class=\"p\">]<\/span>\n<span class=\"w\">        <\/span><span class=\"nx\">dostuff<\/span><span class=\"w\"> <\/span><span class=\"nx\">i<\/span>\n\n<span class=\"nv\">start<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"nb\">Date<\/span><span class=\"p\">().<\/span><span class=\"nx\">getTime<\/span><span class=\"p\">()<\/span>\n<span class=\"nx\">x<\/span><span class=\"w\"> <\/span><span class=\"mi\">1000000000<\/span>\n<span class=\"nv\">elapsed<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"nb\">Date<\/span><span class=\"p\">().<\/span><span class=\"nx\">getTime<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"o\">-<\/span><span class=\"w\"> <\/span><span class=\"nx\">start<\/span>\n<span class=\"nx\">console<\/span><span class=\"p\">.<\/span><span class=\"nx\">log<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;Time in ms = &quot;<\/span><span class=\"w\"> <\/span><span class=\"o\">+<\/span><span class=\"w\"> <\/span><span class=\"nx\">elapsed<\/span>\n<\/code><\/pre><\/div>\n\n<p>However, when this code is run using CoffeeScript 1.3.3 on the same VM\nas before, the process eats more and more memory until it hits a 1 Gb\nmemory limit and dies:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>FATAL ERROR: JS Allocation failed - process out of memory\n<\/code><\/pre><\/div>\n\n<p>So what happened? Well, the for loop is not really a for loop, but\nrather a comprehension over the numbers from 0 to <code>n<\/code> (exclusive, since\nwe use <code>...<\/code> rather than <code>..<\/code>). It&rsquo;s equivalent to writing\n<code>dostuff i for i in [0...n]<\/code>, which reveals its expression nature a bit\nbetter. There&rsquo;s one more thing into play: in the absence of a return\nstatement, a function returns its final value. And in this case, the\nfinal value is the result of the comprehension. The <code>x<\/code> function in the\ncompiled JavaScript code looks like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">x<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"kd\">function<\/span><span class=\"p\">(<\/span><span class=\"nx\">n<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nx\">i<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"nx\">_i<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"nx\">_results<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">_results<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"p\">[];<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"nx\">i<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"nx\">_i<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mf\">0<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"mf\">0<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;=<\/span><span class=\"w\"> <\/span><span class=\"nx\">n<\/span><span class=\"w\"> <\/span><span class=\"o\">?<\/span><span class=\"w\"> <\/span><span class=\"nx\">_i<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;<\/span><span class=\"w\"> <\/span><span class=\"nx\">n<\/span><span class=\"w\"> <\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">_i<\/span><span class=\"w\"> <\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"nx\">n<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"nx\">i<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mf\">0<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;=<\/span><span class=\"w\"> <\/span><span class=\"nx\">n<\/span><span class=\"w\"> <\/span><span class=\"o\">?<\/span><span class=\"w\"> <\/span><span class=\"o\">++<\/span><span class=\"nx\">_i<\/span><span class=\"w\"> <\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"o\">--<\/span><span class=\"nx\">_i<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"nx\">_results<\/span><span class=\"p\">.<\/span><span class=\"nx\">push<\/span><span class=\"p\">(<\/span><span class=\"nx\">dostuff<\/span><span class=\"p\">(<\/span><span class=\"nx\">i<\/span><span class=\"p\">));<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"nx\">_results<\/span><span class=\"p\">;<\/span>\n<span class=\"p\">};<\/span>\n<\/code><\/pre><\/div>\n\n<p>From this, the out of memory error is pretty obvious - pushing one\nbillion item onto an array is bound to fail!<\/p>\n<p>The solution? Just add an empty return statement to the end of the <code>x<\/code>\nfunction. The CoffeeScript compiler detects that the result of the\ncomprehension isn&rsquo;t used and thus won&rsquo;t generate the array-pushing code.<\/p>\n<p>I tend to forget to put empty return statements whenever I don&rsquo;t want a\nfunction to return anything, which means that there is a lot of\nunnecessary array juggling going on under the hood. Most of the time\nthis isn&rsquo;t a problem, of course, since the created arrays will be small.\nBut not only does it <em>feel<\/em> wrong, it doesn&rsquo;t help performance! And\nwhile the solution is simple, littering otherwise concise code with\nempty return statements is a bit annoying!<\/p>\n<h2>2) Returning unexpected values to the caller<\/h2>\n<p>I ran into a very peculiar problem when writing unit tests for an\n<a href=\"http:\/\/angularjs.org\/\" title=\"AngularJS\">AngularJS<\/a> controller written in CoffeeScript (AngularJS is a\nJavaScript MVC framework). I used the <a href=\"http:\/\/docs.angularjs.org\/api\/ng.$controller\"><code>$controller<\/code><\/a> service to\ncreate a controller instance, and I expected to get the instance back as\nstated by the (rather miserable) documentation. But I got back something\nelse entirely! What was going on?<\/p>\n<p>After a bit of detective work, it turned out that what I got back was\nthe result of an initialization function called by the controller\nfunction as its last statement. And what happens with the return value\nof the last statement in a function? That&rsquo;s right, it becomes the return\nvalue of the function!<\/p>\n<p>What the <code>$controller<\/code> documentation doesn&rsquo;t say is that if the\ncontroller function returns a proper object, that object is returned\ninstead of the controller instance! Had I written the controller in\nJavaScript, the absence of an explicit return statement would cause the\nfunction return value to be <code>undefined<\/code>, which in turn would cause\n<code>$controller<\/code> to return the controller instance.<\/p>\n<h2>Lessons learned<\/h2>\n<p>Unless you&rsquo;re in complete control of the call chain, make sure that you\nunderstand what a CoffeeScript function actually returns and what the\nimplications of that are. Also, beware of using comprehensions as the\nlast statement of a function!<\/p>\n<p>CoffeeScript gives you great power, but with great power comes great\nresponsibility!<\/p>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"coffeescript"}},{"@attributes":{"term":"javascript"}}]},{"title":"Tricked by the IDE, broke the build","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/tricked-by-the-ide-broke-the-build.html","rel":"alternate"}},"published":"2012-09-18T00:45:00+02:00","updated":"2012-09-18T00:45:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2012-09-18:\/tricked-by-the-ide-broke-the-build.html","summary":"<p>Over the last year, I&rsquo;ve written a fair amount of Visual Basic .NET code\nfor a customer project. As a result, I know a lot more VB.NET than I\nwould like to, and I&rsquo;ve run into a number of peculiar behaviors, such as\n<a href=\"https:\/\/programmaticallyspeaking.com\/nothing-surprises-me-in-vbnet.html\">this one<\/a>. In this \u2026<\/p>","content":"<p>Over the last year, I&rsquo;ve written a fair amount of Visual Basic .NET code\nfor a customer project. As a result, I know a lot more VB.NET than I\nwould like to, and I&rsquo;ve run into a number of peculiar behaviors, such as\n<a href=\"https:\/\/programmaticallyspeaking.com\/nothing-surprises-me-in-vbnet.html\">this one<\/a>. In this blog post, I will tell the story of when Visual\nStudio tricked me into breaking the build.<\/p>\n<p>This was .NET framework 4 and Visual Studio 2010, so nothing too ancient\nat all.<\/p>\n<p>In short, this is what happened: Within one project, I wrote a class\nthat inherited from a generic class, specifying a class from the\n<code>System.ServiceModel.Activation<\/code> namespace as type argument. I then used\nthe sub class from a different project, adding the first project as\nreference. Building the solution in Visual Studio resulted in a big,\nhappy &ldquo;Build success!&rdquo; I ran the tests, watched them pass and them\ncommitted everything to the Subversion repository. Then I watched in\nhorror as the build failed on the build server:<\/p>\n<blockquote>\n<p>error BC30007: Reference required to assembly\n&lsquo;System.ServiceModel.Activation, &hellip;&rsquo; containing the base class\n&lsquo;System.ServiceModel.Activation&hellip;&rsquo;. Add one to your project.<\/p>\n<\/blockquote>\n<p>Wat?<\/p>\n<p>So essentially, MSBuild failed the build with a compile-time error that\nVisual Studio somehow didn&rsquo;t encounter! How did that happen?<\/p>\n<p>Here&rsquo;s some code that illustrates the problem:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c\">&#39; Class in a &quot;distant&quot; project (C).<\/span>\n<span class=\"k\">Public<\/span><span class=\"w\"> <\/span><span class=\"k\">Class<\/span><span class=\"w\"> <\/span><span class=\"nc\">DistantClass<\/span>\n<span class=\"k\">End<\/span><span class=\"w\"> <\/span><span class=\"k\">Class<\/span>\n\n<span class=\"c\">&#39; Base class in a Visual Studio project (B).<\/span>\n<span class=\"k\">Public<\/span><span class=\"w\"> <\/span><span class=\"k\">Class<\/span><span class=\"w\"> <\/span><span class=\"nc\">BaseClass<\/span><span class=\"p\">(<\/span><span class=\"k\">Of<\/span><span class=\"w\"> <\/span><span class=\"n\">T<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">Public<\/span><span class=\"w\"> <\/span><span class=\"k\">Overrides<\/span><span class=\"w\"> <\/span><span class=\"k\">Function<\/span><span class=\"w\"> <\/span><span class=\"nf\">ToString<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"ow\">As<\/span><span class=\"w\"> <\/span><span class=\"kt\">String<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">Return<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;All your base belongs to us! &quot;<\/span><span class=\"w\"> <\/span><span class=\"o\">&amp;<\/span><span class=\"w\"> <\/span><span class=\"ow\">GetType<\/span><span class=\"p\">(<\/span><span class=\"n\">T<\/span><span class=\"p\">).<\/span><span class=\"n\">Name<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">End<\/span><span class=\"w\"> <\/span><span class=\"k\">Function<\/span>\n<span class=\"k\">End<\/span><span class=\"w\"> <\/span><span class=\"k\">Class<\/span>\n\n<span class=\"c\">&#39; Sub class in the same project as BaseClass (B).<\/span>\n<span class=\"k\">Public<\/span><span class=\"w\"> <\/span><span class=\"k\">Class<\/span><span class=\"w\"> <\/span><span class=\"nc\">SubClass<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">Inherits<\/span><span class=\"w\"> <\/span><span class=\"n\">BaseClass<\/span><span class=\"p\">(<\/span><span class=\"k\">Of<\/span><span class=\"w\"> <\/span><span class=\"n\">DistantClass<\/span><span class=\"p\">)<\/span>\n<span class=\"k\">End<\/span><span class=\"w\"> <\/span><span class=\"k\">Class<\/span>\n\n<span class=\"c\">&#39; Ultimate consumer, in its own Visual Studio project (A).<\/span>\n<span class=\"k\">Public<\/span><span class=\"w\"> <\/span><span class=\"k\">Class<\/span><span class=\"w\"> <\/span><span class=\"nc\">AnyClass<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">Shared<\/span><span class=\"w\"> <\/span><span class=\"k\">Sub<\/span><span class=\"w\"> <\/span><span class=\"nf\">Main<\/span><span class=\"p\">()<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">System<\/span><span class=\"p\">.<\/span><span class=\"n\">Console<\/span><span class=\"p\">.<\/span><span class=\"n\">WriteLine<\/span><span class=\"p\">(<\/span><span class=\"k\">New<\/span><span class=\"w\"> <\/span><span class=\"n\">SubClass<\/span><span class=\"p\">())<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">End<\/span><span class=\"w\"> <\/span><span class=\"k\">Sub<\/span>\n<span class=\"k\">End<\/span><span class=\"w\"> <\/span><span class=\"k\">Class<\/span>\n<\/code><\/pre><\/div>\n\n<p>As indicated by the comments, the classes belong to three different\nprojects, with the following structure:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>+----------+       +-----------+       +------------+\n|     A    |       |     B     |       |      C     |\n| AnyClass | ----&gt; | BaseClass | ----&gt; |DistantClass|\n|          |       | SubClass  |       |            |\n+----------+       +-----------+       +------------+\n<\/code><\/pre><\/div>\n\n<p>If you create this project structure in Visual Studio, your solution\nwill build successfully. Now, open up a console and type (with XX being\nthe solution name, of course):<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>msbuild \/t:Rebuild XX.sln\n<\/code><\/pre><\/div>\n\n<p>BOOM! The build fails with the aforementioned BC30007 error! MSBuild\nwants us to add a reference from A to C:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>+----------+       +-----------+       +------------+\n|     A    |       |     B     |       |      C     |\n| AnyClass | ----&gt; | BaseClass | ----&gt; |DistantClass|\n|          |       | SubClass  |       |            |\n+----------+       +-----------+       +------------+\n     |                                        ^\n     +----------------------------------------+\n<\/code><\/pre><\/div>\n\n<p>The problem has nothing to do with MSBuild. The error message comes from\nthe VB compiler. Try the following command sequence to see it:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>vbc \/t:library \/out:C.dll DistantClass.vbvbc \/t:library \/out:B.dll \/r:C.dll BaseClass.vb SubClass.vbvbc \/t:exe \/out:A.exe \/r:B.dll AnyClass.vb\n<\/code><\/pre><\/div>\n\n<\/p>\n<p>To be honest, I haven&rsquo;t been able to figure out exactly why the\nreference is required, only that Visual Studio and the compiler have\ndifferent dependency resolution strategies. What I have found in\naddition to this is the following:<\/p>\n<ul>\n<li>The C# compiler does NOT need the reference from A to C in a\n    corresponding C# setup. With the exception of VB-specific stuff,\n    the final C# assembly is pretty much identical to the corresponding\n    VB assembly. Apparently, the C# compiler is smarter than the VB\n    compiler.<\/li>\n<li>The presence of and information about <code>DistantClass<\/code> are\n    discoverable using reflection. I&rsquo;m guessing that there is some\n    transitivity involved here.<\/li>\n<li>If you change <code>BaseClass<\/code> into a non-generic class that inherits\n    from <code>DistantClass<\/code>, you will get the C# equivalent of BC30007,\n    CS0012:<\/li>\n<\/ul>\n<blockquote>\n<p>error CS0012: The type &lsquo;DistantClass&rsquo; is defined in an assembly that\nis not referenced. You must add a reference to assembly &lsquo;C, &hellip;&rsquo;.<\/p>\n<\/blockquote>\n<p>Apparently, inheritance requires more information that a constructed\ngeneric type!<\/p>\n<p>In conclusion:<\/p>\n<ol>\n<li>Never, ever trust Visual Studio when it comes to compiling VB.NET\n    code. Always build with MSBuild outside of the IDE.<\/li>\n<li>Don&rsquo;t use VB.NET! Save yourself some time and sanity and use C#!<\/li>\n<\/ol>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"fail"}},{"@attributes":{"term":"vb.net"}},{"@attributes":{"term":"csharp"}},{"@attributes":{"term":"vs2010"}}]},{"title":"Suck it up and be a noob","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/suck-it-up-and-be-a-noob.html","rel":"alternate"}},"published":"2012-09-17T22:36:00+02:00","updated":"2012-09-17T22:36:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2012-09-17:\/suck-it-up-and-be-a-noob.html","summary":"<p>This is a whine post, but I really need to get it out of my system.\nApologies in advance!<\/p>\n<p>I&rsquo;ve battled with <a href=\"http:\/\/angularjs.org\/\">Angular<\/a> for a while now. It&rsquo;s a JavaScript\nframework that allows you to write rich client-side applications in very\nshort time with goodies such as two-way \u2026<\/p>","content":"<p>This is a whine post, but I really need to get it out of my system.\nApologies in advance!<\/p>\n<p>I&rsquo;ve battled with <a href=\"http:\/\/angularjs.org\/\">Angular<\/a> for a while now. It&rsquo;s a JavaScript\nframework that allows you to write rich client-side applications in very\nshort time with goodies such as two-way data binding, route handling and\nview-controller separation.<\/p>\n<blockquote>\n<p>In theory, that is.<\/p>\n<\/blockquote>\n<p>In practice, writing an application using Angular takes a long time and\nis a journey filled with pain, frustration and dead ends. And the main\nreason is this:<\/p>\n<blockquote>\n<p>The documentation sucks!<\/p>\n<\/blockquote>\n<p>There&rsquo;s no nicer way to say it. The documentation is incomplete,\nincorrect and outdated. To further add insult to injury, examples on the\nweb are likely to apply to an older version of Angular and not work with\nthe newest version, since backwards compatibility was broken somewhere\nalong the way.<\/p>\n<p>In defense of the Angular developers, writing documentation is hard and\nboring. I&rsquo;ve worked with API development, and the documentation was\nalways a sore point, and was many times addressed as an afterthought.\nBut that&rsquo;s an explanation, not an excuse! No matter how feature-rich and\npowerful a framework is, bad documentation is a big and ugly problem.\nAnd Angular is not alone - there are countless frameworks out there with\nsub-standard documentation. Microsoft&rsquo;s .NET framework is one of them.<\/p>\n<p>So how do you deal with bad documentation? You do one or both of the\nfollowing:<\/p>\n<ol>\n<li>Become a <em>noob<\/em>! As soon as you run into a problem, however tiny it\n    is, ask on the mailing list! Don&rsquo;t bother consulting the\n    documentation, because it&rsquo;s likely to lead you in the wrong\n    direction anyway.<\/li>\n<li>Be a good open source citizen and contribute what you&rsquo;ve learned the\n    hard way to the documentation, so that others may benefit from it!<\/li>\n<\/ol>\n<p>Generally speaking, noob behavior doesn&rsquo;t come naturally to me. I\nusually spend a long time researching problems I run into before asking,\nbecause I don&rsquo;t want to appear uninformed. But Angular has made me\nre-think this!<\/p>\n<p>I have a number of contributions I want to make to Angular&rsquo;s\ndocumentation. I will post at least some of them on this blog also, in\nthe interest of spreading the knowledge.<\/p>\n<p>Stay tuned!<\/p>\n<p>P.S. On a side note, I&rsquo;ve seen the phrase &ldquo;designed with love&rdquo; used for\na number of frameworks (all web, IIRC). I&rsquo;ve never seen &ldquo;documented with\nlove!&rdquo; ;-)<\/p>","category":[{"@attributes":{"term":"Opinion"}},{"@attributes":{"term":"angularjs"}},{"@attributes":{"term":"pain"}}]},{"title":"One assertion per test, please","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/one-assertion-per-test-please.html","rel":"alternate"}},"published":"2012-07-25T01:25:00+02:00","updated":"2012-07-25T01:25:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2012-07-25:\/one-assertion-per-test-please.html","summary":"<p>When it comes to unit or integration tests, there are of course good\nones and bad ones. There are few things more treacherous than a test\nsuite filled with low-quality tests that don&rsquo;t test what they&rsquo;re\nsupposed to, if anything at all. When the test suite goes green \u2026<\/p>","content":"<p>When it comes to unit or integration tests, there are of course good\nones and bad ones. There are few things more treacherous than a test\nsuite filled with low-quality tests that don&rsquo;t test what they&rsquo;re\nsupposed to, if anything at all. When the test suite goes green, you&rsquo;re\nnot really any wiser.<\/p>\n<p>To determine whether a test is good or bad, you can subject it to a\nnumber of rules. In this post, I will focus on one of the simpler:<\/p>\n<blockquote>\n<p>There should only be one assertion per test!<\/p>\n<\/blockquote>\n<p>I&rsquo;m pretty adamant about this one, and it&rsquo;s one of the first rules I\nbring up whenever I talk about how to write good tests. On the surface,\nthe rule looks pretty simple, but there are actually a couple of\nexistential questions behind it, such as: &ldquo;What is a test?&rdquo; and &ldquo;What is\nan assertion?&rdquo;<\/p>\n<p>I was reminded of the rule when writing some tests using the JavaScript\nunit testing framework <a href=\"http:\/\/qunitjs.com\/\">QUnit<\/a>. I&rsquo;ll come back to why in a moment,\nalong with answers to the existential questions posed above, but let&rsquo;s\nfirst look at the reasoning behind the rule.<\/p>\n<h3>Why only a single assertion?<\/h3>\n<p>The single assertion requirement has to do with clarity and conciseness.\nHere are some good reasons that motivate the rule:<\/p>\n<blockquote>\n<p>A test should only be able to fail for a single reason, namely that the\nthing it tests doesn&rsquo;t behave as expected.<\/p>\n<\/blockquote>\n<p><em>Thing<\/em> in this context refers to a particular aspect of the subject\nunder test. Having multiple assertions means that a test can fail for\nmultiple reasons, which makes it harder to determine the cause of\nfailure. Furthermore, a failure in an early assertion hides subsequent\nassertions, meaning that the failure count doesn&rsquo;t adequately represent\nthe state of the test suite. In other words, things are worse than they\nlook! It&rsquo;s actually quite annoying to uncover new failures as you fix\nold ones.<\/p>\n<blockquote>\n<p>It should be possible to name a test in a precise and informative way,\nso that a failure is as self-descriptive as possible.<\/p>\n<\/blockquote>\n<p>With multiple assertions, a test really tests many things. This is of\ncourse difficult to capture in the name of the test, which typically\nresults in a non-descriptive name, or a name that only describes part of\nwhat the test does. How about &ldquo;TestCRUD&rdquo; or &ldquo;TestGet?&rdquo;<\/p>\n<blockquote>\n<p>Multiple aspects of the outcome of some action should be tested\nseparately, and the tests should be able to succeed or fail independent\nof each other.<\/p>\n<\/blockquote>\n<p>Dependencies between tests are bad (that&rsquo;s another rule), and multiple\nassertions are in fact equivalent to multiple tests locked in a\ndependency chain. Tests that test successive behavior (e.g., one that\ntests that a method returns an empty list rather than <code>null<\/code>, and one\nthat tests that the list is unmodifiable) are of course weakly dependent\non each other, but typically in a way that when some fail, others are in\nan <em>error state<\/em>. But that&rsquo;s ok - disregard the errors and focus only on\nthe failures.<\/p>\n<blockquote>\n<p>A test should be concise and readable.<\/p>\n<\/blockquote>\n<p>Multiple assertions make a test more involved, and that hardly makes it\nconcise. A test with a single assertion is usually easy to read and\ncomprehend, and that&rsquo;s important!<\/p>\n<p>You might be able to come up with more reasons than these, and I&rsquo;d love\nto hear them! I&rsquo;d also be interested in hearing about counter-arguments\nand cases where you think having multiple assertions per test is valid.\nI can think of one or two, but that&rsquo;s a topic for another post. :-)<\/p>\n<h3>Tips for writing single-assertion tests<\/h3>\n<p>When you write tests using the Arrange-Act-Assert or Given-When-Then\nstyles in an ordinary test framework like <a href=\"http:\/\/nunit.org\/\">NUnit<\/a>, and put all parts\nwithin a single test, it&rsquo;s tempting to write multiple assertions rather\nthan having multiple tests that repeat the Arrange-Act\/Given-When parts.\nAdopting a BDDish Context-Specification style makes life much easier. An\nexample:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"na\">[TestFixture]<\/span>\n<span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">WhenSomethingHappens<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"na\">[SetUp]<\/span><span class=\"w\"> <\/span><span class=\"c1\">\/\/ or [TestFixtureSetUp]<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">Context<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Prepare data and do &quot;Something&quot;<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">    <\/span><span class=\"na\">[Test]<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">ThenFoo<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Assert the &quot;Foo&quot; outcome<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">    <\/span><span class=\"na\">[Test]<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">ThenBar<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Assert the &quot;Bar&quot; outcome<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span><span class=\"w\">   <\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>This style has the added bonus of forcing you to separate different\naspects of the subject under test into different test classes. (Having\none test class per subject under test has its merits, but can turn into\na mess rather quickly.)<\/p>\n<h3>The existential questions<\/h3>\n<p>As I wrote initially, the rule leaves some questions unanswered. To\nreally know what the rule means, we have to define what a test is and\nwhat an assertion is.<\/p>\n<p>Based on what I wrote earlier about tests failing independent of each\nother, a <em>test<\/em> must be something that can fail or be in an error state\nby itself, without other tests being affected. Therefore, we can define\ntest to mean &ldquo;isolated test execution unit.&rdquo; In a test framework like\nNUnit, <a href=\"http:\/\/www.junit.org\/\">JUnit<\/a> or <a href=\"http:\/\/testng.org\">TestNG<\/a>, &ldquo;isolated test execution unit&rdquo;\ncorresponds to a test method:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"na\">[Test]<\/span><span class=\"w\"> <\/span><span class=\"c1\">\/\/ NUnit<\/span>\n<span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">TestThatCalculatorCanAddNumbers<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">Assert<\/span><span class=\"p\">.<\/span><span class=\"n\">AreEqual<\/span><span class=\"p\">(<\/span><span class=\"m\">3<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">calculator<\/span><span class=\"p\">.<\/span><span class=\"n\">Add<\/span><span class=\"p\">(<\/span><span class=\"m\">1<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"p\">));<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>It can also be a smaller unit, like for example a lambda statement in\n<a href=\"http:\/\/nspec.org\/\">NSpec<\/a>:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\">\/\/ NSpec<\/span>\n<span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">given_a_calculator<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">it<\/span><span class=\"p\">[<\/span><span class=\"s\">&quot;adding two numbers should result in a correct sum&quot;<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">calculator<\/span><span class=\"p\">.<\/span><span class=\"n\">Add<\/span><span class=\"p\">(<\/span><span class=\"m\">1<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"p\">).<\/span><span class=\"n\">should_be<\/span><span class=\"p\">(<\/span><span class=\"m\">3<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Thus, in NSpec the test isn&rsquo;t the method, but the lambda statement. To\nbe precise, an isolated test execution unit of a test framework is the\nsmallest unit that the test runner of that framework can wrap within a\ntry-catch statement.<\/p>\n<p>What about <em>assertion<\/em> then? The answer is that it depends on the\nassertion framework you&rsquo;re using (which can be the test framework\nitself, or some other framework). I usually think of assertion as a\n<em>publicly facing<\/em> assertion, meaning a method in the API of the\nassertion framework. Under the hood, such an assertion may be composite.\nFor example, an assertion in the <a href=\"https:\/\/github.com\/alexruiz\/fest-assert-2.x\/wiki\">FEST Assert<\/a> framework for Java\ntypically performs some initial sanity assertions, for example that the\nlist whose length should be verified isn&rsquo;t <code>null<\/code>.<\/p>\n<p>I realize that the definition of assertion is a bit murky, but bottom\nline I only want to see a single assertion statement in a test. And yes,\nI do think that <code>Assert.IsTrue(a == b &amp;&amp; c == d &amp;&amp; ...)<\/code> counts as\ncheating! ;-)<\/p>\n<h3>What about QUnit<\/h3>\n<p>As stated, I wrote some QUnit tests to test JavaScript code. To my\nsurprise, one of the examples at the <a href=\"http:\/\/docs.jquery.com\/QUnit\">old QUnit page<\/a> contained\nmultiple assertions within a single test. Uh-oh, a violation of my\nprecious rule! However, as it turns out, an early assertion failure does\n<em>not<\/em> hide later assertions - they run just fine. So this example:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">test<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;multiple assertions&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"kd\">function<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">equal<\/span><span class=\"p\">(<\/span><span class=\"mf\">1<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;2&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;Failed!&quot;<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">equal<\/span><span class=\"p\">(<\/span><span class=\"mf\">1<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;1&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;Passed!&quot;<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">});<\/span>\n<\/code><\/pre><\/div>\n\n<p>&hellip;results in this output:<\/p>\n<p><img alt=\"Multiple assertions in a test in QUnit\" src=\".\/images\/qunit-multi-assert.png\" title=\"Multiple assertions in a test in QUnit\" \/><\/p>\n<p>Based on the report we see that QUnit seems to equate assertion and\ntest, although the terminology is a bit unclear given that the\nassertions are specified in a function passed to the <code>test<\/code> function.\nThis is interesting! If an assertion is a test, then the rule becomes a\ntautology, and as such, it&rsquo;s pretty pointless. Furthermore, assertions\nin QUnit are clearly not exception based, which could mean that\n<em>isolated test execution unit<\/em> has nothing to do with try-catch, but is\nrather something that is entirely dependent on the test framework. I was\non the verge of reconsidering the rule altogether, when in a later test,\nI tested an element-finding method by verifying the ID of the found\nelement, like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">test<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;a rule violation&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"kd\">function<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">equal<\/span><span class=\"p\">(<\/span><span class=\"nx\">findElement<\/span><span class=\"p\">().<\/span><span class=\"nx\">id<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;id1&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;Null reference!&quot;<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">equal<\/span><span class=\"p\">(<\/span><span class=\"mf\">1<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;1&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;Passed!&quot;<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">});<\/span>\n<\/code><\/pre><\/div>\n\n<p>Initially, <code>findElement()<\/code> returned <code>null<\/code> for the case tested, and lo\nand behold! The test runner choked altogether, since there is a\ntry-catch statement wrapping all assertions, making the entire test\nfunction the isolated test execution unit:<\/p>\n<p><img alt=\"Test runner died in QUnit\" src=\".\/images\/qunit-test-died.png\" title=\"Test runner died in QUnit\" \/><\/p>\n<p>Note also that the report says &ldquo;0 tests of 1 passed&rdquo; - the second\nassertion is completely hidden. Sure, we can use the <code>expect(...)<\/code>\nfunction to state how many assertions we make, but that just feels\nclumsy in this particular context.<\/p>\n<h3>Conclusion<\/h3>\n<p>In my eyes, the QUnit adventure confirms that the rule is indeed valid,\nfor all the reasons outlined earlier! QUnit is simply not compatible\nwith my opinions of how to write good tests. On a final note, I ditched\nit for <a href=\"http:\/\/pivotal.github.com\/jasmine\/\">Jasmine<\/a>!<\/p>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"assertion"}},{"@attributes":{"term":"qunit"}},{"@attributes":{"term":"testrules"}},{"@attributes":{"term":"javascript"}}]},{"title":"A Chrome extension for easy ID linking","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/a-chrome-extension-for-easy-id-linking.html","rel":"alternate"}},"published":"2012-07-21T22:44:00+02:00","updated":"2012-07-21T22:44:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2012-07-21:\/a-chrome-extension-for-easy-id-linking.html","summary":"<p>Occasionally I want to link to specific section of a web page.\nPreviously, I would bring up the source of the web page to see if there\nwas a named anchor tag for the section in question, then I would\nmanually add the anchor name as the URL fragment. Recently \u2026<\/p>","content":"<p>Occasionally I want to link to specific section of a web page.\nPreviously, I would bring up the source of the web page to see if there\nwas a named anchor tag for the section in question, then I would\nmanually add the anchor name as the URL fragment. Recently, however, I\nlearned that any element with an ID attribute can act as a link target.\nIt&rsquo;s only been <a href=\"http:\/\/www.w3.org\/TR\/REC-html40\/struct\/global.html#adef-id\">stated<\/a> in the HTML 4 specification like forever. :-)<\/p>\n<p>Anyway, I thought it might be useful to create a web browser extension\nthat lets me automate the link target-finding process a bit. As a bonus,\nI figured I would also learn how to write an extension. Enter\n<a href=\"https:\/\/github.com\/provegard\/LinkToId\" title=\"LinkToId Chrome extension @ GitHub\">LinkToId<\/a>, a Chrome extension (I mostly use Chrome nowadays, which is\nwhy) that:<\/p>\n<ul>\n<li>Lets you discover the closest possible link target, if any. The link\n    target is identified via a tooltip.<\/li>\n<li>Lets you update the fragment of the current URL to point to the link\n    target.<\/li>\n<\/ul>\n<\/p>\n<p>Here is a screenshot that shows the extension in action on a\nStackOverflow page:<\/p>\n<p><img alt=\"Screenshot of the LinkToId tooltip\" src=\".\/images\/LinkToId-screenshot.png\" title=\"Screenshot of the LinkToId tooltip\" \/><\/p>\n<p>Had I left-clicked at this point, the current URL would be updated to\ninclude <em>#answer-4971817<\/em> as the fragment.<\/p>\n<p>To use the extension, you simply press the Ctrl and Alt keys (the\ntrigger keys) simultaneously while pointing to the section you want to\nlink to. If the section has an ID, the tooltip will show. To update the\nURL, left-click while still holding the trigger keys.<\/p>\n<p>Note that the extension is still very primitive, and thus has a number\nof limitations:<\/p>\n<ul>\n<li>The trigger keys (Ctrl + Alt) are hard-coded and cannot be\n    configured.<\/li>\n<li>The DOM tree is searched backwards to find an element with an ID. In\n    practice, this means that the element you find may be very far away.\n    Some option to limit the search would be useful.<\/li>\n<li>Tooltip message is not localizable.<\/li>\n<\/ul>\n<\/p>\n<p>The extension <a href=\"https:\/\/github.com\/provegard\/LinkToId\">source code<\/a> is on GitHub. To install the extension, go\nto the <a href=\"https:\/\/github.com\/provegard\/LinkToId\/downloads\">Downloads<\/a> page and click on one of the download packages\n(it&rsquo;s not in Chrome Web Store yet). If you&rsquo;re using Chrome, you will\nautomatically be prompted to install it.<\/p>\n<p>To run the tests, go to the Chrome Extensions page\n(<em>chrome:\/\/chrome\/extensions<\/em>) and make a note of the LinkToId extension\nID. Next, enter the following URL into the browser:\n<em>chrome-extension:\/\/\\&lt;extension ID&gt;\/test\/index.html<\/em>.<\/p>\n<p>Any comments and feedback are welcome!<\/p>","category":[{"@attributes":{"term":"Tools"}},{"@attributes":{"term":"chrome"}},{"@attributes":{"term":"extension"}},{"@attributes":{"term":"linktoid"}}]},{"title":"Changing the user profile path in Windows 7","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/changing-the-user-profile-path-in-windows-7.html","rel":"alternate"}},"published":"2012-07-12T00:12:00+02:00","updated":"2012-07-12T00:12:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2012-07-12:\/changing-the-user-profile-path-in-windows-7.html","summary":"<p>Nothing programmatic about this post, unfortunately. Instead, a bit of\nrambling about Windows. :-) One of the reasons I don&rsquo;t use Linux on my\ndesktop computer is that it requires too much constant tweaking,\nconfiguring and fixing to get things to work together properly. I tried\nit twice, and I \u2026<\/p>","content":"<p>Nothing programmatic about this post, unfortunately. Instead, a bit of\nrambling about Windows. :-) One of the reasons I don&rsquo;t use Linux on my\ndesktop computer is that it requires too much constant tweaking,\nconfiguring and fixing to get things to work together properly. I tried\nit twice, and I had the same (bad) experience both times. I&rsquo;m mostly\nhappy about Windows 7 - it&rsquo;s a much better OS than previous Windows\nversions. But the other day, when I took on the seemingly easy task of\nmoving one of my user profiles to a different partition (from\nc:\\Users\\SomeUser to d:\\SomeUser), I immediately ran into problems.<\/p>\n<p>The first problem was that the Local Users and Groups snapin isn&rsquo;t\navailable in Windows 7 Home Premium. This annoys me immensely for three\nreasons. One, that the OS really shouldn&rsquo;t be allowed to have &ldquo;Premium&rdquo;\nin its name when it&rsquo;s so crippled. Two, that there doesn&rsquo;t appear to be\nany <em>adequately detailed<\/em> feature chart that I could&rsquo;ve consulted before\npurchasing the OS. Three, that an upgrade to Professional or Ultimate is\nridiculously expensive.<\/p>\n<p>But then I got the idea to try the &ldquo;net&rdquo; command, specifically &ldquo;net\nuser.&rdquo; Based on the command help output, it sure looked promising:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>\/HOMEDIR:pathname        Sets the path for the user&#39;s home directory.\n                         The path must exist.\n\/PROFILEPATH[:path]      Sets a path for the user&#39;s logon profile.\n<\/code><\/pre><\/div>\n\n<p>The second problem was however that neither of these had any effect on\nthe user profile location. A bit of investigation revealed that:<\/p>\n<ul>\n<li><code>net user SomeUser \/profilepath:&lt;path&gt;<\/code> sets a roaming profile for\n    the user SomeUser. I only tested this with a UNC path pointing to my\n    local computer: <code>\\\\%computername%\\d$\\SomeUser<\/code>. Upon logging\n    SomeUser on and off, a directory d:\\SomeUser.V2 was created with a\n    &ldquo;roaming copy&rdquo; of the user&rsquo;s profile (Wikipedia explains the <a href=\"http:\/\/en.wikipedia.org\/wiki\/Roaming_user_profile#Active_Directory\">V2\n    suffix<\/a>). The &ldquo;roaming copy&rdquo; was properly kept in sync for each\n    logon and logoff, as expected.<\/li>\n<li><code>net user SomeUser \/homedir:&lt;path&gt;<\/code> only seems to affect the\n    HOMEDRIVE and HOMEPATH environment variables. I tested setting the\n    path to <code>d:\\SomeUserX<\/code>, and the environment variables happily\n    reflected this. It had no apparent effect though. From what I can\n    find on the web, these variables are &ldquo;good to use in scripts,&rdquo;\n    although USERPROFILE is preferred. By default, they point to\n    USERPROFILE.<\/li>\n<\/ul>\n<p>Now here&rsquo;s some rambling: I usually find that Microsoft&rsquo;s documentation\nis very poor. I&rsquo;ve been working a lot with the .NET framework lately,\nand I&rsquo;ve found time and time again that the documentation helps very\nlittle, if anything at all. The <a href=\"http:\/\/technet.microsoft.com\/en-us\/library\/cc771865(v=ws.10)\" title=\"Net user documentation\">documentation for net user<\/a> is no\nexception. Compared to the command help output, it adds &ldquo;This path\npoints to a registry profile&rdquo; for the \/PROFILEPATH switch. Huh? What\ndoes that even mean?<\/p>\n<p>I finally got the solution by consulting <a href=\"http:\/\/answers.microsoft.com\/en-us\/windows\/forum\/windows_7-security\/how-do-i-set-a-home-directory-outside-cusers-for-a\/aed68262-1bf4-4a4d-93dc-7495193a440f\">Microsoft Answers<\/a> (I&rsquo;m the\nOP):<\/p>\n<ol>\n<li>Create a System Restore Point.<\/li>\n<li>Log on under an admin account.<\/li>\n<li>Move the folder c:\\Users\\SomeUser so that it becomes d:\\SomeUser.<\/li>\n<li>Open the registry editor.<\/li>\n<li>Navigate to HKLM\\SOFTWARE\\Microsoft\\Windows\n    NT\\CurrentVersion\\ProfileList.<\/li>\n<li>Search for &ldquo;ProfileImagePath&rdquo; until you find the one that points at\n    c:\\Users\\SomeUser.<\/li>\n<li>Modify it so that it points at d:\\SomeUser.<\/li>\n<li>Use System Restore in case things go wrong.<\/li>\n<\/ol>\n<p>It&rsquo;s a bit hackish, but it works very well! So if you ever needs to move\na user profile, that&rsquo;s how to do it!<\/p>","category":[{"@attributes":{"term":"Sysadmin"}},{"@attributes":{"term":"profile"}},{"@attributes":{"term":"windows7"}}]},{"title":"Offline repository sync using git bundle","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/offline-repository-sync-using-git-bundle.html","rel":"alternate"}},"published":"2012-06-11T15:03:00+02:00","updated":"2012-06-11T15:03:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2012-06-11:\/offline-repository-sync-using-git-bundle.html","summary":"<p>Keeping git repositories in sync is usually and easily done using <a href=\"http:\/\/www.kernel.org\/pub\/software\/scm\/git\/docs\/v1.7.10.1\/git-pull.html\">git\npull<\/a> and <a href=\"http:\/\/www.kernel.org\/pub\/software\/scm\/git\/docs\/v1.7.10.1\/git-push.html\">git push<\/a>. However, for those rare times when you don&rsquo;t\nhave network connectivity (or limited connectivity) and still need to\ntransfer the contents of a repository to somewhere else, there&rsquo;s <a href=\"http:\/\/www.kernel.org\/pub\/software\/scm\/git\/docs\/v1.7.10.1\/git-bundle.html\">git\nbundle<\/a>.<\/p>\n<p>The bundle \u2026<\/p>","content":"<p>Keeping git repositories in sync is usually and easily done using <a href=\"http:\/\/www.kernel.org\/pub\/software\/scm\/git\/docs\/v1.7.10.1\/git-pull.html\">git\npull<\/a> and <a href=\"http:\/\/www.kernel.org\/pub\/software\/scm\/git\/docs\/v1.7.10.1\/git-push.html\">git push<\/a>. However, for those rare times when you don&rsquo;t\nhave network connectivity (or limited connectivity) and still need to\ntransfer the contents of a repository to somewhere else, there&rsquo;s <a href=\"http:\/\/www.kernel.org\/pub\/software\/scm\/git\/docs\/v1.7.10.1\/git-bundle.html\">git\nbundle<\/a>.<\/p>\n<p>The bundle command creates an archive from one or more objects in a\nrepository. I usually just take the entire master branch. For advanced\ncases, see the man page. For a simple case, do as follows.<\/p>\n<p>In the source repository, use <code>git bundle<\/code> to create the archive:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>bundle<span class=\"w\"> <\/span>create<span class=\"w\"> <\/span>\/path\/to\/file.bundle<span class=\"w\"> <\/span>refs\/heads\/master\nCounting<span class=\"w\"> <\/span>objects:<span class=\"w\"> <\/span><span class=\"m\">935<\/span>,<span class=\"w\"> <\/span><span class=\"k\">done<\/span>.\nDelta<span class=\"w\"> <\/span>compression<span class=\"w\"> <\/span>using<span class=\"w\"> <\/span>up<span class=\"w\"> <\/span>to<span class=\"w\"> <\/span><span class=\"m\">8<\/span><span class=\"w\"> <\/span>threads.\nCompressing<span class=\"w\"> <\/span>objects:<span class=\"w\"> <\/span><span class=\"m\">100<\/span>%<span class=\"w\"> <\/span><span class=\"o\">(<\/span><span class=\"m\">712<\/span>\/712<span class=\"o\">)<\/span>,<span class=\"w\"> <\/span><span class=\"k\">done<\/span>.\nWriting<span class=\"w\"> <\/span>objects:<span class=\"w\"> <\/span><span class=\"m\">100<\/span>%<span class=\"w\"> <\/span><span class=\"o\">(<\/span><span class=\"m\">935<\/span>\/935<span class=\"o\">)<\/span>,<span class=\"w\"> <\/span><span class=\"m\">1<\/span>.72<span class=\"w\"> <\/span>MiB,<span class=\"w\"> <\/span><span class=\"k\">done<\/span>.\nTotal<span class=\"w\"> <\/span><span class=\"m\">935<\/span><span class=\"w\"> <\/span><span class=\"o\">(<\/span>delta<span class=\"w\"> <\/span><span class=\"m\">441<\/span><span class=\"o\">)<\/span>,<span class=\"w\"> <\/span>reused<span class=\"w\"> <\/span><span class=\"m\">585<\/span><span class=\"w\"> <\/span><span class=\"o\">(<\/span>delta<span class=\"w\"> <\/span><span class=\"m\">202<\/span><span class=\"o\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>Note that uncommitted changes won&rsquo;t be included, since they are not\npointed to by the tree reference (<code>master<\/code> in this case). Now transfer\nthe archive to its destination. In the destination repository, do:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>ls-remote<span class=\"w\"> <\/span>\/path\/to\/file.bundle\ne615fea0972f6eccb870cfe67e146a8e21f3ee7d<span class=\"w\">        <\/span>refs\/heads\/master\n<\/code><\/pre><\/div>\n\n<p>The <code>refs\/heads\/master<\/code> reference won&rsquo;t do in the destination\nrepository, as there is such a reference already. Therefore, we need to\nfetch with a mapping:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>fetch<span class=\"w\"> <\/span>\/path\/to\/file.bundle<span class=\"w\"> <\/span>refs\/heads\/master:refs\/remotes\/master\nFrom<span class=\"w\"> <\/span>\/path\/to\/file.bundle\n*<span class=\"w\"> <\/span><span class=\"o\">[<\/span>new<span class=\"w\"> <\/span>branch<span class=\"o\">]<\/span><span class=\"w\">      <\/span>master<span class=\"w\">     <\/span>-&gt;<span class=\"w\"> <\/span>master\n<\/code><\/pre><\/div>\n\n<p>Finally, we can merge into our existing master branch:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>merge<span class=\"w\"> <\/span>refs\/remotes\/master\nUpdating<span class=\"w\"> <\/span>aaf4c61..e615fea\nChecking<span class=\"w\"> <\/span>out<span class=\"w\"> <\/span>files:<span class=\"w\"> <\/span><span class=\"m\">100<\/span>%<span class=\"w\"> <\/span><span class=\"o\">(<\/span><span class=\"m\">442<\/span>\/442<span class=\"o\">)<\/span>,<span class=\"w\"> <\/span><span class=\"k\">done<\/span>.\n...\n<\/code><\/pre><\/div>\n\n<p>That&rsquo;s all there is to it (for the simple case)! Happy bundling!<\/p>\n<p><strong>Update (2012-06-12)<\/strong>: Changed the bundle-creating command to use\n<c>refs\/heads\/master<\/c> instead of just <c>master<\/c> as tree\nreference, as the latter may be ambiguous.<\/p>","category":[{"@attributes":{"term":"Tools"}},{"@attributes":{"term":"bundle"}},{"@attributes":{"term":"git"}}]},{"title":"Regular expression multiline mode - what's a newline?","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/regular-expression-multiline-mode-whats-a-newline.html","rel":"alternate"}},"published":"2012-05-30T11:17:00+02:00","updated":"2012-05-30T11:17:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2012-05-30:\/regular-expression-multiline-mode-whats-a-newline.html","summary":"<p>I stumbled upon an interesting little detail as I was using a regular\nexpression in a unit test case in a C# application. I had a multiline\nstring and was searching for a particular substring in multiline mode.\nThe newlines in the string were Windows newlines, meaning CR followed by \u2026<\/p>","content":"<p>I stumbled upon an interesting little detail as I was using a regular\nexpression in a unit test case in a C# application. I had a multiline\nstring and was searching for a particular substring in multiline mode.\nThe newlines in the string were Windows newlines, meaning CR followed by\nLF. Can you see where this is heading?<\/p>\n<p>To illustrate the situation, consider the following C# program:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">Main<\/span><span class=\"p\">(<\/span><span class=\"kt\">string<\/span><span class=\"p\">[]<\/span><span class=\"w\"> <\/span><span class=\"n\">args<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">const<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span><span class=\"w\"> <\/span><span class=\"n\">input<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;foo\\r\\nbar&quot;<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">    <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">match<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Regex<\/span><span class=\"p\">.<\/span><span class=\"n\">IsMatch<\/span><span class=\"p\">(<\/span><span class=\"n\">input<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;foo$&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">RegexOptions<\/span><span class=\"p\">.<\/span><span class=\"n\">Multiline<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">Console<\/span><span class=\"p\">.<\/span><span class=\"n\">WriteLine<\/span><span class=\"p\">(<\/span><span class=\"n\">match<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>What does it print? Intuitively, it should print &ldquo;True&rdquo;, as multiline\nmode changes the meaning of $ to match at the end of any line, not just\nat the end of input. But if you run the program, you&rsquo;ll find that it\nprints &ldquo;False&rdquo;. Took me a little while to figure out why, but it&rsquo;s\ndocumented <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/yd1hzczs.aspx#Multiline\">here<\/a>. The relevant part:<\/p>\n<blockquote>\n<p>If you specify the RegexOptions.Multiline option, it matches either\nthe newline character (\\n) or the end of the input string. It does\nnot, however, match the carriage return\/line feed character\ncombination. To successfully match them, use the subexpression \\r?$\ninstead of just $.<\/p>\n<\/blockquote>\n<p>So the fix is easy! But I&rsquo;m a bit surprised that $ doesn&rsquo;t match CR+LF,\ngiven that that&rsquo;s the sequence Windows uses for newlines, and the .NET\nframework was developed for the Windows platform&hellip;<\/p>\n<p>For comparison, I tried the same pattern matching in Java:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kd\">static<\/span><span class=\"w\"> <\/span><span class=\"kt\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">main<\/span><span class=\"p\">(<\/span><span class=\"n\">String<\/span><span class=\"o\">[]<\/span><span class=\"w\"> <\/span><span class=\"n\">args<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">String<\/span><span class=\"w\"> <\/span><span class=\"n\">input<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;foo\\r\\nbar&quot;<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">Pattern<\/span><span class=\"w\"> <\/span><span class=\"n\">p<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Pattern<\/span><span class=\"p\">.<\/span><span class=\"na\">compile<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;foo$&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Pattern<\/span><span class=\"p\">.<\/span><span class=\"na\">MULTILINE<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"kt\">boolean<\/span><span class=\"w\"> <\/span><span class=\"n\">match<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">p<\/span><span class=\"p\">.<\/span><span class=\"na\">matcher<\/span><span class=\"p\">(<\/span><span class=\"n\">input<\/span><span class=\"p\">).<\/span><span class=\"na\">lookingAt<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">System<\/span><span class=\"p\">.<\/span><span class=\"na\">out<\/span><span class=\"p\">.<\/span><span class=\"na\">println<\/span><span class=\"p\">(<\/span><span class=\"n\">match<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>This program prints &ldquo;true&rdquo;. In Java, $ matches a range of different\nline terminators. See the <a href=\"http:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/util\/regex\/Pattern.html#lt\">API documentation<\/a> for the complete list.<\/p>\n<p>Morale of the story? Don&rsquo;t make assumptions about the behavior of\nregular expression engines (or about <a href=\"http:\/\/en.wikipedia.org\/wiki\/Regular_expression#Syntax\">regular expression syntax<\/a>, for\nthat matter) - make sure to read the documentation!<\/p>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"newline"}},{"@attributes":{"term":"regular expressions"}},{"@attributes":{"term":"csharp"}},{"@attributes":{"term":"java"}}]},{"title":"Testing asynchronous background workers in .NET","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/testing-asynchronous-background-workers-in-net.html","rel":"alternate"}},"published":"2012-05-08T00:35:00+02:00","updated":"2012-05-08T00:35:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2012-05-08:\/testing-asynchronous-background-workers-in-net.html","summary":"<p>When you build a GUI, all lengthy operations that can be triggered by\nthe user should take place on a background thread so that the GUI\ndoesn&rsquo;t become unresponsive. Why would it? Well, it&rsquo;s because all GUI\noperations take place on a single thread - the GUI thread (the \u2026<\/p>","content":"<p>When you build a GUI, all lengthy operations that can be triggered by\nthe user should take place on a background thread so that the GUI\ndoesn&rsquo;t become unresponsive. Why would it? Well, it&rsquo;s because all GUI\noperations take place on a single thread - the GUI thread (the\nEvent-Dispatch Thread in Java). At the core of the GUI thread is a\nmessage pump that dispatches messages such as mouse and keyboard input\nto various controls. If you perform a lengthy operation on the GUI\nthread in response to a click message, for example, the message pump\nwill &ldquo;stand still&rdquo; until the operation is complete. During this time,\nother messages just sit in the queue, which effectively renders the GUI\ninoperable. Instead, you&rsquo;d spawn off a background thread to do the work,\nand let that thread post back the result to the GUI thread when done.<\/p>\n<p>Using the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/dd460717.aspx\">Task Parallel Library<\/a> in .NET, creating a background\nthread to do some work is very simple:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">private<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">DoWorkInBackground<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">Task<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">string<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">.<\/span><span class=\"n\">Factory<\/span><span class=\"p\">.<\/span><span class=\"n\">StartNew<\/span><span class=\"p\">(<\/span><span class=\"n\">DoWork<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"k\">private<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span><span class=\"w\"> <\/span><span class=\"nf\">DoWork<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ perform some lengthy operation, then return a result<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>But how do we get to the result? The <code>StartNew<\/code> method returns a <code>Task<\/code>\ninstance, and we can query its <code>Result<\/code> property to get the result. The\nproblem is that the calling thread blocks until the result is available,\nand blocking the GUI thread was exactly what we wanted to avoid. So\nlet&rsquo;s try a different approach, utilizing the facts that the GUI thread\nhas its own <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.threading.synchronizationcontext.aspx\">synchronization context<\/a>, that a task can have a\n<a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ee372288.aspx\">continuation task<\/a>, and that we can run such a continuation task with\na specific <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.threading.tasks.taskscheduler.aspx\">task scheduler<\/a>:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">private<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">DoWorkInBackground<\/span><span class=\"p\">(<\/span><span class=\"n\">Action<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">string<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">callback<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">taskScheduler<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">TaskScheduler<\/span><span class=\"p\">.<\/span><span class=\"n\">FromCurrentSynchronizationContext<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">    <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">task<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">Task<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">string<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">(<\/span><span class=\"n\">DoWork<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">task<\/span><span class=\"p\">.<\/span><span class=\"n\">ContinueWith<\/span><span class=\"p\">(<\/span><span class=\"n\">t<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">callback<\/span><span class=\"p\">(<\/span><span class=\"n\">t<\/span><span class=\"p\">.<\/span><span class=\"n\">Result<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"n\">taskScheduler<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">task<\/span><span class=\"p\">.<\/span><span class=\"n\">Start<\/span><span class=\"p\">();<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"k\">private<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span><span class=\"w\"> <\/span><span class=\"nf\">DoWork<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ perform some lengthy operation, then return a result<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>As you can see here, the continuation task runs using a task scheduler\ncreated from the current synchronization context. This works because the\nsynchronization context for the GUI thread (<a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.windows.forms.windowsformssynchronizationcontext.aspx\">this<\/a> or <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.windows.threading.dispatchersynchronizationcontext.aspx\">this<\/a>) posts\nto the message pump a special message that, when dispatched, runs the\ntask code.<\/p>\n<p>What I&rsquo;ve just described is a very common way of doing background work.\nSo common that Microsoft has chosen to simplify it <em>a lot<\/em> with the new\n<a href=\"http:\/\/msdn.microsoft.com\/en-us\/vstudio\/gg316360\">Async API<\/a> (which will be a part of .NET 4.5). With the new <code>async<\/code>\nand <code>await<\/code> keywords, we can just do:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">private<\/span><span class=\"w\"> <\/span><span class=\"k\">async<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">DoWorkInBackground<\/span><span class=\"p\">(<\/span><span class=\"n\">Action<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">string<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">callback<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">task<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Task<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">string<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">.<\/span><span class=\"n\">Factory<\/span><span class=\"p\">.<\/span><span class=\"n\">StartNew<\/span><span class=\"p\">(<\/span><span class=\"n\">DoWork<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">callback<\/span><span class=\"p\">(<\/span><span class=\"k\">await<\/span><span class=\"w\"> <\/span><span class=\"n\">task<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"k\">private<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span><span class=\"w\"> <\/span><span class=\"nf\">DoWork<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ perform some lengthy operation, then return a result<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>This is especially useful if you do multiple asynchronous calls with\nsome GUI operations in-between (e.g., pausing the background work to ask\nfor some user input).<\/p>\n<p>Alright, so how do we test asynchronous code like the one above? Well,\nwe could (and should) break out the &ldquo;work&rdquo; to a separate entity and test\nthat entity synchronously. While that&rsquo;s a good start, perhaps we still\nwant to test the entity that chooses to run code in the background in\nthe first place - most likely an MVC controller class. The answer is\nthat the test code has to wait until the asynchronous code has finished\nrunning. But what should it wait <em>for<\/em>? Under our background worker\nmodel, there&rsquo;s some continuation code that runs on the GUI thread by\nmeans of its message pump. But during a test run, the original thread is\nthe test runner thread, which will be stuck waiting for the background\nworker to complete. Can we run a message pump in the test runner thread?\nWe probably could, but luckily we don&rsquo;t have to! All we need is a\nsimulation of one, using a custom synchronization context! Next, I&rsquo;ll\nshow you how to write one.<\/p>\n<p>Let&rsquo;s start by studying how the custom synchronization context can be\nused. To be able to do TDD, we do need to specify a timeout for the\nwait. While we could put the timeout on the test method itself, I think\nspecifying the timeout when the context is created is slightly more\nreadable.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"na\">[TestMethod]<\/span>\n<span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">TestTheOutcomeOfSomeBackgroundOperation<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">sut<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"p\">...;<\/span>\n<span class=\"w\">    <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">tester<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">AsyncTester<\/span><span class=\"p\">.<\/span><span class=\"n\">WithTimeout<\/span><span class=\"p\">(<\/span><span class=\"m\">200<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">sut<\/span><span class=\"p\">.<\/span><span class=\"n\">SomeAction<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">tester<\/span><span class=\"p\">.<\/span><span class=\"n\">Uninstall<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">Assert<\/span><span class=\"p\">.<\/span><span class=\"n\">AreEqual<\/span><span class=\"p\">(...);<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>The factory method <code>WithTimeout<\/code> creates and automatically installs the\ncontext. After having triggered the background operation, we uninstall\nthe context. It&rsquo;s a bit annoying that uninstallation is manual, and it\nalso opens up for some nasty side-effects if the action fails with an\nexception and the context never gets uninstalled. A <code>using<\/code> block is\nmuch nicer:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"na\">[TestMethod]<\/span>\n<span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">TestTheOutcomeOfSomeBackgroundOperation<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">sut<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"p\">...;<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">using<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">AsyncTester<\/span><span class=\"p\">.<\/span><span class=\"n\">WithTimeout<\/span><span class=\"p\">(<\/span><span class=\"m\">200<\/span><span class=\"p\">))<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">sut<\/span><span class=\"p\">.<\/span><span class=\"n\">SomeAction<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">Assert<\/span><span class=\"p\">.<\/span><span class=\"n\">AreEqual<\/span><span class=\"p\">(...);<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Ok, once we have the usage clear, let&rsquo;s define the class! Starting with\nthe mechanics that allow installation and uninstallation as we&rsquo;ve seen\nabove:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">AsyncTester<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">SynchronizationContext<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">IDisposable<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"n\">AsyncTester<\/span><span class=\"w\"> <\/span><span class=\"nf\">WithTimeout<\/span><span class=\"p\">(<\/span><span class=\"kt\">int<\/span><span class=\"w\"> <\/span><span class=\"n\">timeoutMs<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">sc<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">AsyncTester<\/span><span class=\"p\">(<\/span><span class=\"n\">timeoutMs<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Current<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">SetSynchronizationContext<\/span><span class=\"p\">(<\/span><span class=\"n\">sc<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">sc<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">Uninstall<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">SetSynchronizationContext<\/span><span class=\"p\">(<\/span><span class=\"n\">_prevSyncContext<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">Dispose<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">Uninstall<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>The <code>WithTimeout<\/code> method creates and sets the synchronization context.\nThe <code>Uninstall<\/code> method restores the previous context. The <code>Dispose<\/code>\nmethod is required by the <code>IDisposable<\/code> interface and simply delegates\nthe uninstallation. We need a constructor and some fields to support the\nabove (the timeout comes into play later):<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"w\">    <\/span><span class=\"k\">private<\/span><span class=\"w\"> <\/span><span class=\"k\">readonly<\/span><span class=\"w\"> <\/span><span class=\"kt\">int<\/span><span class=\"w\"> <\/span><span class=\"n\">_timeoutMs<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">private<\/span><span class=\"w\"> <\/span><span class=\"k\">readonly<\/span><span class=\"w\"> <\/span><span class=\"n\">SynchronizationContext<\/span><span class=\"w\"> <\/span><span class=\"n\">_prevSyncContext<\/span><span class=\"p\">;<\/span>\n\n<span class=\"w\">    <\/span><span class=\"k\">private<\/span><span class=\"w\"> <\/span><span class=\"nf\">AsyncTester<\/span><span class=\"p\">(<\/span><span class=\"kt\">int<\/span><span class=\"w\"> <\/span><span class=\"n\">timeoutMs<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">SynchronizationContext<\/span><span class=\"w\"> <\/span><span class=\"n\">prevContext<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">_timeoutMs<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">timeoutMs<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">_prevSyncContext<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">prevContext<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>I&rsquo;ve chosen to make the constructor private for two reasons. First, it\nforces the use of the factory method, which IMHO results in more\nreadable code. Second, I don&rsquo;t want to expose the fact that we keep\ntrack of the previous context.<\/p>\n<p>Next, we need to take care of the actual juice of the synchronization\ncontext - the code that waits for whatever background operation is going\non to complete. Recall that when the background task is finished, there\nis a continuation task to be run on the original thread. That task is\nposted by a task scheduler created from the current synchronization\ncontext. Posted to what? To the synchronization context, of course! So\nlet&rsquo;s override the <code>Post<\/code> method:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"w\">    <\/span><span class=\"k\">private<\/span><span class=\"w\"> <\/span><span class=\"k\">readonly<\/span><span class=\"w\"> <\/span><span class=\"n\">BlockingCollection<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Tuple<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">SendOrPostCallback<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"kt\">object<\/span><span class=\"o\">&gt;&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">_queue<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span>\n<span class=\"w\">        <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">BlockingCollection<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Tuple<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">SendOrPostCallback<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"kt\">object<\/span><span class=\"o\">&gt;&gt;<\/span><span class=\"p\">();<\/span>\n\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">override<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">Post<\/span><span class=\"p\">(<\/span><span class=\"n\">SendOrPostCallback<\/span><span class=\"w\"> <\/span><span class=\"n\">d<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"kt\">object<\/span><span class=\"w\"> <\/span><span class=\"n\">state<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">_queue<\/span><span class=\"p\">.<\/span><span class=\"n\">Add<\/span><span class=\"p\">(<\/span><span class=\"n\">Tuple<\/span><span class=\"p\">.<\/span><span class=\"n\">Create<\/span><span class=\"p\">(<\/span><span class=\"n\">d<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">state<\/span><span class=\"p\">));<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>I&rsquo;ve chose to use a <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/dd267312.aspx\">BlockingCollection<\/a> to queue callbacks that\ncorrespond to continuation tasks, since it is thread safe and the <code>Post<\/code>\nmethod is called from a background thread. Note that no execution\nhappens here. That is where the next piece of the puzzle comes in, the\nmethod that consumes the queue. This is our message pump simulation!<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">ProcessQueue<\/span><span class=\"p\">(<\/span><span class=\"kt\">int<\/span><span class=\"w\"> <\/span><span class=\"n\">timeoutMs<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Use the constructor-specified timeout if not overridden.<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">timeoutMs<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;=<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">timeoutMs<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">_timeoutMs<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">        <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">sw<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Stopwatch<\/span><span class=\"p\">.<\/span><span class=\"n\">StartNew<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">        <\/span><span class=\"kt\">int<\/span><span class=\"w\"> <\/span><span class=\"n\">timeLeft<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">while<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"k\">true<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">timeLeft<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"kt\">int<\/span><span class=\"p\">)(<\/span><span class=\"n\">timeoutMs<\/span><span class=\"w\"> <\/span><span class=\"o\">-<\/span><span class=\"w\"> <\/span><span class=\"n\">sw<\/span><span class=\"p\">.<\/span><span class=\"n\">ElapsedMilliseconds<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">            <\/span><span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">timeLeft<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;=<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">                <\/span><span class=\"k\">break<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"c1\">\/\/ we&#39;re done waiting<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">Tuple<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">SendOrPostCallback<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"kt\">object<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">tuple<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">            <\/span><span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">_queue<\/span><span class=\"p\">.<\/span><span class=\"n\">TryTake<\/span><span class=\"p\">(<\/span><span class=\"k\">out<\/span><span class=\"w\"> <\/span><span class=\"n\">tuple<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">timeLeft<\/span><span class=\"p\">))<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">                <\/span><span class=\"c1\">\/\/ Item1 = the callback, Item2 = the state object.<\/span>\n<span class=\"w\">                <\/span><span class=\"n\">tuple<\/span><span class=\"p\">.<\/span><span class=\"n\">Item1<\/span><span class=\"p\">(<\/span><span class=\"n\">tuple<\/span><span class=\"p\">.<\/span><span class=\"n\">Item2<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">            <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>The method is pretty straight-forward; we use a <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.diagnostics.stopwatch.aspx\">Stopwatch<\/a> instance\nto keep track of elapsed time. For each iteration of the loop (there\nwill be many in the case of multiple background workers) we calculate\nhow long time we can <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/dd287154.aspx\">try to take<\/a> a previously added pair of callback\nand state object. The callback has been created by the task scheduler to\nrun the code in the continuation task.<\/p>\n<p>You may have reacted on the fact that the method is public, and that it\ntakes an optional timeout. I&rsquo;ll come to these in a moment. First,\nthough, we need to call the method from somewhere. Let&rsquo;s modify the\n<code>Uninstall<\/code> method:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">Uninstall<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"k\">this<\/span><span class=\"w\"> <\/span><span class=\"o\">!=<\/span><span class=\"w\"> <\/span><span class=\"n\">Current<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"k\">return<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">ProcessQueue<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">SetSynchronizationContext<\/span><span class=\"p\">(<\/span><span class=\"n\">_prevSyncContext<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>The modification means that when the context is uninstalled, all queued\ncontinuation tasks are run. There is also a small safeguard to prevent\nmultiple uninstallations (which is a real problem since the context\ninstance eventually will be disposed, and <code>Dispose<\/code> calls <code>Uninstall<\/code>).<\/p>\n<p>What about the public <code>ProcessQueue<\/code> method and the local timeout? Well,\nI&rsquo;ve had some cases where the context setup (the <em>given<\/em>) involved\nbackground work as well. In such cases, we can do:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"na\">[TestMethod]<\/span>\n<span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">SomeTest<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ context setup...<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">using<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">tester<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">AsyncTester<\/span><span class=\"p\">.<\/span><span class=\"n\">WithTimeout<\/span><span class=\"p\">(<\/span><span class=\"m\">300<\/span><span class=\"p\">))<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ more context setup, including background work...<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">tester<\/span><span class=\"p\">.<\/span><span class=\"n\">ProcessQueue<\/span><span class=\"p\">(<\/span><span class=\"m\">500<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ call code that uses a background worker...<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ assert result...<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>The local timeout is unrelated to the the overall timeout. Both affect\nthe running time of the test - 800 milliseconds in the test method\nabove.<\/p>\n<p>That&rsquo;s it! I hope that you find the class useful! You can find it in its\nentirety in <a href=\"https:\/\/gist.github.com\/2631064\">this gist<\/a>. Actually, there is one more thing to make it\ncomplete: :-)<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"async"}},{"@attributes":{"term":"background worker"}},{"@attributes":{"term":"test"}},{"@attributes":{"term":".net"}}]},{"title":"Your decisions are likely to suck","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/your-decisions-are-likely-to-suck.html","rel":"alternate"}},"published":"2012-04-25T07:40:00+02:00","updated":"2012-04-25T07:40:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2012-04-25:\/your-decisions-are-likely-to-suck.html","summary":"<p>I apologize in advance for being blunt! And it&rsquo;s not really as bad as\nthe title suggests. But my point is that every decision you make,\nwhether it&rsquo;s about a small piece of isolated code or the architecture as\na whole, may not stand the test of time \u2026<\/p>","content":"<p>I apologize in advance for being blunt! And it&rsquo;s not really as bad as\nthe title suggests. But my point is that every decision you make,\nwhether it&rsquo;s about a small piece of isolated code or the architecture as\na whole, may not stand the test of time. With the luxury of hindsight,\nyou will almost always find at least some problem with a previous\ndecision. And that&rsquo;s completely natural! At the time a decision is made,\nit might be the best one considering the information that is available.\nSome time later, you&rsquo;re in a position where you have hard evidence of\nthe consequences of the decision <em>and<\/em> probably also more information.\nIt&rsquo;s also a fact that the truths (about technology, architectural\npatterns, etc.) of today are not necessarily the truths of tomorrow.<\/p>\n<p>There are two key takeaways here:<\/p>\n<ol>\n<li>It&rsquo;s so easy to study a system (or piece of software; the scale\n    doesn&rsquo;t matter here) made by someone else and criticize the\n    decisions that lead to the current state of the system. You need to\n    understand and appreciate the conditions under which these decisions\n    were made!<\/li>\n<li>When making a decision, keep things simple! The <a href=\"http:\/\/en.wikipedia.org\/wiki\/KISS_principle\" title=\"KISS principle @ Wikipedia\">KISS<\/a> principle\n    wins every time! Don&rsquo;t make premature optimizations. Don&rsquo;t create\n    abstractions from single cases. Don&rsquo;t build a castle when a cabin\n    will do. Make it so that you can modify or complement the decision\n    at a later time without earth-shattering consequences. <em>Be agile<\/em>!<\/li>\n<\/ol>\n<p>As for the first point, a colleague reminded me that if the original\ndecision maker still holds on to previous decisions without realizing\n(or wanting to realize) that they are out-of-date, you don&rsquo;t need to be\nas humble!<\/p>\n<p>I think that keeping a <a href=\"http:\/\/en.wikipedia.org\/wiki\/Design_rationale\" title=\"Design rationale @ Wikipedia\">design rationale<\/a> is sound, but I&rsquo;ve never\ncome around to actually do it. Mostly because I&rsquo;ve wanted to avoid\ncreating yet another document to live with the software (of course, a\ndecision rationale is not &ldquo;living&rdquo; in the same sense as many other\ndocuments; it&rsquo;s a history record). But perhaps a design rationale is\noverkill. Perhaps we should just accept that decisions are imperfect and\nwhenever we&rsquo;re in a position to make a superior decision, we should do\nso without dwelling on the past.<\/p>\n<p>To end on a positive note, and to be fair, of the countless micro\ndecisions you make on a day-to-day basis, a majority will most likely be\ngood ones! To stay healthy and sane, I think you just need to be good at\nrecognizing them!<\/p>","category":[{"@attributes":{"term":"Opinion"}},{"@attributes":{"term":"agile"}},{"@attributes":{"term":"decision making"}},{"@attributes":{"term":"decisions"}}]},{"title":"Abusing XML literals in VB.NET","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/abusing-xml-literals-in-vbnet.html","rel":"alternate"}},"published":"2012-04-25T06:32:00+02:00","updated":"2012-04-25T06:32:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2012-04-25:\/abusing-xml-literals-in-vbnet.html","summary":"<p>One of the things I do like about VB.NET is XML literals. Given that XML\nis so common, it&rsquo;s really a great idea! Here&rsquo;s a tiny example:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">Dim<\/span><span class=\"w\"> <\/span><span class=\"n\">x<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;<\/span><span class=\"n\">p<\/span><span class=\"o\">&gt;<\/span><span class=\"n\">Some<\/span><span class=\"w\"> <\/span><span class=\"n\">test<\/span><span class=\"p\">.<\/span><span class=\"o\">&lt;\/<\/span><span class=\"n\">p<\/span><span class=\"o\">&gt;<\/span>\n<\/code><\/pre><\/div>\n\n<p>I thought I&rsquo;d write about how XML literals can be abused to create \u2026<\/p>","content":"<p>One of the things I do like about VB.NET is XML literals. Given that XML\nis so common, it&rsquo;s really a great idea! Here&rsquo;s a tiny example:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">Dim<\/span><span class=\"w\"> <\/span><span class=\"n\">x<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;<\/span><span class=\"n\">p<\/span><span class=\"o\">&gt;<\/span><span class=\"n\">Some<\/span><span class=\"w\"> <\/span><span class=\"n\">test<\/span><span class=\"p\">.<\/span><span class=\"o\">&lt;\/<\/span><span class=\"n\">p<\/span><span class=\"o\">&gt;<\/span>\n<\/code><\/pre><\/div>\n\n<p>I thought I&rsquo;d write about how XML literals can be abused to create\nmulti-line strings very easily. But then I realized that it doesn&rsquo;t stop\nthere - we can as easily use them as multi-line format strings too!\nConsider the following code that uses <code>String.Format<\/code> to solve the task:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">Private<\/span><span class=\"w\"> <\/span><span class=\"k\">Function<\/span><span class=\"w\"> <\/span><span class=\"nf\">CreateStringUsingStringFormat<\/span><span class=\"p\">(<\/span><span class=\"n\">a<\/span><span class=\"w\"> <\/span><span class=\"ow\">As<\/span><span class=\"w\"> <\/span><span class=\"kt\">String<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">b<\/span><span class=\"w\"> <\/span><span class=\"ow\">As<\/span><span class=\"w\"> <\/span><span class=\"kt\">Integer<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">                                               <\/span><span class=\"n\">c<\/span><span class=\"w\"> <\/span><span class=\"ow\">As<\/span><span class=\"w\"> <\/span><span class=\"kt\">Boolean<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"ow\">As<\/span><span class=\"w\"> <\/span><span class=\"kt\">String<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">Return<\/span><span class=\"w\"> <\/span><span class=\"kt\">String<\/span><span class=\"p\">.<\/span><span class=\"n\">Format<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">        <\/span><span class=\"s\">&quot;This is a multi-line string{0}that runs over multiple lines{0}&quot;<\/span><span class=\"w\"> <\/span><span class=\"o\">+<\/span>\n<span class=\"w\">        <\/span><span class=\"s\">&quot;and incorporates {1} and {2}{0}and finally {3}.&quot;<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">Environment<\/span><span class=\"p\">.<\/span><span class=\"n\">NewLine<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">a<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">b<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">c<\/span><span class=\"p\">)<\/span>\n<span class=\"k\">End<\/span><span class=\"w\"> <\/span><span class=\"k\">Function<\/span>\n<\/code><\/pre><\/div>\n\n<p>This piece of code has at least two problems. One is that the connection\nbetween the format items and the arguments that populate them is quite\nloose (which arguably also is a strength). The other is that we have to\nencode newlines explicitly as format items.<\/p>\n<p>The corresponding solution that uses an XML literal solves both problems\nand is more readable, IMHO:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">Private<\/span><span class=\"w\"> <\/span><span class=\"k\">Function<\/span><span class=\"w\"> <\/span><span class=\"nf\">CreateStringUsingXmlLiteral<\/span><span class=\"p\">(<\/span><span class=\"n\">a<\/span><span class=\"w\"> <\/span><span class=\"ow\">As<\/span><span class=\"w\"> <\/span><span class=\"kt\">String<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">b<\/span><span class=\"w\"> <\/span><span class=\"ow\">As<\/span><span class=\"w\"> <\/span><span class=\"kt\">Integer<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">                                             <\/span><span class=\"n\">c<\/span><span class=\"w\"> <\/span><span class=\"ow\">As<\/span><span class=\"w\"> <\/span><span class=\"kt\">Boolean<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"ow\">As<\/span><span class=\"w\"> <\/span><span class=\"kt\">String<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">Return<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;<\/span><span class=\"n\">p<\/span><span class=\"o\">&gt;<\/span><span class=\"n\">This<\/span><span class=\"w\"> <\/span><span class=\"ow\">is<\/span><span class=\"w\"> <\/span><span class=\"n\">a<\/span><span class=\"w\"> <\/span><span class=\"n\">multi<\/span><span class=\"o\">-<\/span><span class=\"n\">line<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span>\n<span class=\"n\">that<\/span><span class=\"w\"> <\/span><span class=\"n\">runs<\/span><span class=\"w\"> <\/span><span class=\"n\">over<\/span><span class=\"w\"> <\/span><span class=\"n\">multiple<\/span><span class=\"w\"> <\/span><span class=\"n\">lines<\/span>\n<span class=\"ow\">and<\/span><span class=\"w\"> <\/span><span class=\"n\">incorporates<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;<\/span><span class=\"err\">%<\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">a<\/span><span class=\"w\"> <\/span><span class=\"err\">%<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"ow\">and<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;<\/span><span class=\"err\">%<\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">b<\/span><span class=\"w\"> <\/span><span class=\"err\">%<\/span><span class=\"o\">&gt;<\/span>\n<span class=\"ow\">and<\/span><span class=\"w\"> <\/span><span class=\"k\">finally<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;<\/span><span class=\"err\">%<\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">c<\/span><span class=\"w\"> <\/span><span class=\"err\">%<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">.<\/span><span class=\"o\">&lt;\/<\/span><span class=\"n\">p<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">.<\/span><span class=\"n\">Value<\/span>\n<span class=\"k\">End<\/span><span class=\"w\"> <\/span><span class=\"k\">Function<\/span>\n<\/code><\/pre><\/div>\n\n<p>Note how I added &ldquo;<code>.Value<\/code>&rdquo; to the XML literal. This is where the abuse\ncomes in - the XML literal is only used as a means to an end and once\nwe&rsquo;ve reached the goal, we don&rsquo;t care about the XML anymore. It was just\na convenient language feature, like a <a href=\"http:\/\/en.wikipedia.org\/wiki\/Here_document\">here document<\/a>.<\/p>\n<p>I did some microbenchmarking and found that the two techniques are\nequivalent in terms of speed. The XML literal solution is about 3 to 5\npercent slower using the example above. I think that&rsquo;s a small price to\npay for readability, don&rsquo;t you? If speed is important, you should use\n<code>StringBuilder<\/code> or pure string concatenation, as these are roughly twice\nas fast.<\/p>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"vb.net"}},{"@attributes":{"term":"format strings"}},{"@attributes":{"term":"xml literals"}}]},{"title":"Swedish to not-so-Swedish through diacritics removal","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/swedish-to-not-so-swedish-through-diacritics-removal.html","rel":"alternate"}},"published":"2012-04-06T01:43:00+02:00","updated":"2012-04-06T01:43:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2012-04-06:\/swedish-to-not-so-swedish-through-diacritics-removal.html","summary":"<p>According to <a href=\"http:\/\/www.merriam-webster.com\/dictionary\/diacritic\">Merriam-Webster<\/a>, a <em>diacritic<\/em> is:<\/p>\n<blockquote>\n<p>a mark near or through an orthographic or phonetic character or\ncombination of characters indicating a phonetic value different from\nthat given the unmarked or otherwise marked element<\/p>\n<\/blockquote>\n<p>Right! :-) In the Swedish language, there are three common letters with\ndiacritics, namely &aring;, &auml; and \u2026<\/p>","content":"<p>According to <a href=\"http:\/\/www.merriam-webster.com\/dictionary\/diacritic\">Merriam-Webster<\/a>, a <em>diacritic<\/em> is:<\/p>\n<blockquote>\n<p>a mark near or through an orthographic or phonetic character or\ncombination of characters indicating a phonetic value different from\nthat given the unmarked or otherwise marked element<\/p>\n<\/blockquote>\n<p>Right! :-) In the Swedish language, there are three common letters with\ndiacritics, namely &aring;, &auml; and &ouml;. The diacritics here are &#730; (ring above)\nand &#168; (diaeresis). In a particular situation, I wanted to do a one-way\nconversion of a name containing Swedish letters with diacritics into a\nname with only non-diacritical letters. Thus, I wanted to convert &aring; and\n&auml; into a and &ouml; into o.<\/p>\n<p>A naive solution to the problem is obviously to create a small mapping\ntable with entries for the relevant lowercase and uppercase letters. But\nhow fun is that? Wouldn&rsquo;t it be better to have a generic solution that\ndoesn&rsquo;t require us to maintain a mapping table? Well, of course it\nwould! Let me show you how!<\/p>\n<p>The key to solving the problem lies in <a href=\"http:\/\/en.wikipedia.org\/wiki\/Unicode_equivalence\">Unicode equivalence<\/a>, which in\nshort means that two Unicode strings that contain different code points\ncan be equivalent as long as the code point sequences have the same\nmeaning across the strings. Single-code point characters can be\n<em>decomposed<\/em> into multi-code point characters and vice versa - the\nlatter can be <em>composed<\/em> into the former. For example, &aring; can be\ndecomposed into a and &#730;, as we saw before. This is achieved by\nnormalizing a string according to <a href=\"http:\/\/unicode.org\/reports\/tr15\/#Norm_Forms\">Normalization Form D (NFD)<\/a>, which\ndecomposes combined code points into separate code points. Let&rsquo;s see how\nthat is done in a few different languages.<\/p>\n<p>In the examples below, I use the string &ldquo;f&aring;ll f&auml;lla f&ouml;ll&rdquo; (the words\nmean <em>hem<\/em> as in skirt hem, <em>fell<\/em> as in fell a tree and <em>fell<\/em> as in I\nfell down), which I expect to be converted to &ldquo;fall falla foll&rdquo;.<\/p>\n<p>First up, Java:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kd\">static<\/span><span class=\"w\"> <\/span><span class=\"kt\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">main<\/span><span class=\"p\">(<\/span><span class=\"n\">String<\/span><span class=\"o\">[]<\/span><span class=\"w\"> <\/span><span class=\"n\">args<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">String<\/span><span class=\"w\"> <\/span><span class=\"n\">str<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;f\u00e5ll f\u00e4lla f\u00f6ll&quot;<\/span><span class=\"p\">;<\/span>\n\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ import java.text.Normalizer and java.text.Normalizer.Form<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">String<\/span><span class=\"w\"> <\/span><span class=\"n\">nstr<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Normalizer<\/span><span class=\"p\">.<\/span><span class=\"na\">normalize<\/span><span class=\"p\">(<\/span><span class=\"n\">str<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Form<\/span><span class=\"p\">.<\/span><span class=\"na\">NFD<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"kt\">char<\/span><span class=\"o\">[]<\/span><span class=\"w\"> <\/span><span class=\"n\">chars<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">nstr<\/span><span class=\"p\">.<\/span><span class=\"na\">toCharArray<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">    <\/span><span class=\"kt\">int<\/span><span class=\"w\"> <\/span><span class=\"n\">j<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"kt\">char<\/span><span class=\"w\"> <\/span><span class=\"n\">ch<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">chars<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">chars<\/span><span class=\"o\">[<\/span><span class=\"n\">j<\/span><span class=\"o\">]<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">ch<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">j<\/span><span class=\"w\"> <\/span><span class=\"o\">+=<\/span><span class=\"w\"> <\/span><span class=\"n\">IsMark<\/span><span class=\"p\">(<\/span><span class=\"n\">ch<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">?<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">1<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">nstr<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">String<\/span><span class=\"p\">(<\/span><span class=\"n\">chars<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">j<\/span><span class=\"p\">);<\/span>\n\n<span class=\"w\">    <\/span><span class=\"n\">System<\/span><span class=\"p\">.<\/span><span class=\"na\">out<\/span><span class=\"p\">.<\/span><span class=\"na\">println<\/span><span class=\"p\">(<\/span><span class=\"n\">str<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">System<\/span><span class=\"p\">.<\/span><span class=\"na\">out<\/span><span class=\"p\">.<\/span><span class=\"na\">println<\/span><span class=\"p\">(<\/span><span class=\"n\">nstr<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"kd\">private<\/span><span class=\"w\"> <\/span><span class=\"kd\">static<\/span><span class=\"w\"> <\/span><span class=\"kt\">boolean<\/span><span class=\"w\"> <\/span><span class=\"nf\">IsMark<\/span><span class=\"p\">(<\/span><span class=\"kt\">char<\/span><span class=\"w\"> <\/span><span class=\"n\">ch<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"kt\">int<\/span><span class=\"w\"> <\/span><span class=\"n\">gc<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Character<\/span><span class=\"p\">.<\/span><span class=\"na\">getType<\/span><span class=\"p\">(<\/span><span class=\"n\">ch<\/span><span class=\"p\">);<\/span>\n\n<span class=\"w\">    <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">gc<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"n\">Character<\/span><span class=\"p\">.<\/span><span class=\"na\">NON_SPACING_MARK<\/span>\n<span class=\"w\">        <\/span><span class=\"o\">||<\/span><span class=\"w\"> <\/span><span class=\"n\">gc<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"n\">Character<\/span><span class=\"p\">.<\/span><span class=\"na\">ENCLOSING_MARK<\/span>\n<span class=\"w\">        <\/span><span class=\"o\">||<\/span><span class=\"w\"> <\/span><span class=\"n\">gc<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"n\">Character<\/span><span class=\"p\">.<\/span><span class=\"na\">COMBINING_SPACING_MARK<\/span><span class=\"p\">;<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Pretty verbose, unfortunately, but much of the code involves filtering\nout diacritics. The marked lines show the code point decomposition and\ndiacritic identification. Note that the Swedish diacritics fall into the\nNON_SPACING_MARK\/Mn category, but I included all the <a href=\"http:\/\/unicode.org\/reports\/tr44\/#GC_Values_Table\">Mark\ncategories<\/a> for good measure!<\/p>\n<p>Alright, how about C#?<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">Main<\/span><span class=\"p\">(<\/span><span class=\"kt\">string<\/span><span class=\"p\">[]<\/span><span class=\"w\"> <\/span><span class=\"n\">args<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">str<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;f\u00e5ll f\u00e4lla f\u00f6ll&quot;<\/span><span class=\"p\">;<\/span>\n\n<span class=\"w\">    <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">nstr<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">str<\/span><span class=\"p\">.<\/span><span class=\"n\">Normalize<\/span><span class=\"p\">(<\/span><span class=\"n\">NormalizationForm<\/span><span class=\"p\">.<\/span><span class=\"n\">FormD<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">nstr<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span><span class=\"p\">(<\/span><span class=\"n\">nstr<\/span><span class=\"p\">.<\/span><span class=\"n\">Where<\/span><span class=\"p\">(<\/span><span class=\"n\">ch<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"o\">!<\/span><span class=\"n\">IsMark<\/span><span class=\"p\">(<\/span><span class=\"n\">ch<\/span><span class=\"p\">)).<\/span><span class=\"n\">ToArray<\/span><span class=\"p\">());<\/span>\n\n<span class=\"w\">    <\/span><span class=\"n\">Console<\/span><span class=\"p\">.<\/span><span class=\"n\">WriteLine<\/span><span class=\"p\">(<\/span><span class=\"n\">str<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">Console<\/span><span class=\"p\">.<\/span><span class=\"n\">WriteLine<\/span><span class=\"p\">(<\/span><span class=\"n\">nstr<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"k\">private<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"kt\">bool<\/span><span class=\"w\"> <\/span><span class=\"nf\">IsMark<\/span><span class=\"p\">(<\/span><span class=\"kt\">char<\/span><span class=\"w\"> <\/span><span class=\"n\">ch<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">gc<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Char<\/span><span class=\"p\">.<\/span><span class=\"n\">GetUnicodeCategory<\/span><span class=\"p\">(<\/span><span class=\"n\">ch<\/span><span class=\"p\">);<\/span>\n\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ using System.Globalization<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">gc<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"n\">UnicodeCategory<\/span><span class=\"p\">.<\/span><span class=\"n\">NonSpacingMark<\/span><span class=\"w\"> <\/span>\n<span class=\"w\">        <\/span><span class=\"o\">||<\/span><span class=\"w\"> <\/span><span class=\"n\">gc<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"n\">UnicodeCategory<\/span><span class=\"p\">.<\/span><span class=\"n\">EnclosingMark<\/span>\n<span class=\"w\">        <\/span><span class=\"o\">||<\/span><span class=\"w\"> <\/span><span class=\"n\">gc<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"n\">UnicodeCategory<\/span><span class=\"p\">.<\/span><span class=\"n\">SpacingCombiningMark<\/span><span class=\"p\">;<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Diacritics filtering is much more concise thanks to LINQ, but\ndecomposition and diacritic identification are virtually identical to\nhow they&rsquo;re done in Java.<\/p>\n<p>Finally, let&rsquo;s look at Python:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kn\">import<\/span> <span class=\"nn\">unicodedata<\/span>\n\n<span class=\"nb\">str<\/span> <span class=\"o\">=<\/span> <span class=\"sa\">u<\/span><span class=\"s1\">&#39;f\u00e5ll f\u00e4lla f\u00f6ll&#39;<\/span>\n<span class=\"n\">nstr<\/span> <span class=\"o\">=<\/span> <span class=\"n\">unicodedata<\/span><span class=\"o\">.<\/span><span class=\"n\">normalize<\/span><span class=\"p\">(<\/span><span class=\"s1\">&#39;NFD&#39;<\/span><span class=\"p\">,<\/span> <span class=\"nb\">str<\/span><span class=\"p\">)<\/span>\n\n<span class=\"n\">nstr<\/span> <span class=\"o\">=<\/span> <span class=\"s1\">&#39;&#39;<\/span><span class=\"o\">.<\/span><span class=\"n\">join<\/span><span class=\"p\">([<\/span><span class=\"n\">ch<\/span> <span class=\"k\">for<\/span> <span class=\"n\">ch<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">nstr<\/span> <span class=\"k\">if<\/span> <span class=\"ow\">not<\/span> <span class=\"n\">unicodedata<\/span><span class=\"o\">.<\/span><span class=\"n\">category<\/span><span class=\"p\">(<\/span><span class=\"n\">ch<\/span><span class=\"p\">)<\/span><span class=\"o\">.<\/span><span class=\"n\">startswith<\/span><span class=\"p\">(<\/span><span class=\"s1\">&#39;M&#39;<\/span><span class=\"p\">)])<\/span>\n\n<span class=\"nb\">print<\/span> <span class=\"nb\">str<\/span>\n<span class=\"nb\">print<\/span> <span class=\"n\">nstr<\/span>\n<\/code><\/pre><\/div>\n\n<p>Python wins the conciseness competition! Decomposition is similar to how\nit&rsquo;s done in Java and C#, but since we get the category as a string\nrather than a numeric constant, we can filter out all Mark categories in\none go. And with list comprehension on top of that, diacritics filtering\nbecomes very succinct!<\/p>\n<p>Not too bad, regardless of language! For each of the languages, the\ncorresponding framework contains what we need, and it&rsquo;s only a matter of\nputting together the pieces.<\/p>\n<p>I&rsquo;ll finish with a small rant; in 2012, you&rsquo;d expect most web services\nto handle words that include diacritics without a problem, right? Well,\nAmazon thinks that my credit card reads ROVEG&Atilde;RD instead of ROVEG&Aring;RD, and it <em>insists<\/em> that my street address begins\nwith &Atilde;&Acirc;stra rather than &Ouml;stra. Yeah, I realize this is an encoding\nproblem rather than a problem with diacritics per se, but still&hellip;<\/p>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"diacritics"}},{"@attributes":{"term":"Swedish"}},{"@attributes":{"term":"unicode"}}]},{"title":"Mocking __iter__ with a magic mock in Python","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/mocking-__iter__-with-a-magic-mock-in-python.html","rel":"alternate"}},"published":"2012-03-29T00:08:00+02:00","updated":"2012-03-29T00:08:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2012-03-29:\/mocking-__iter__-with-a-magic-mock-in-python.html","summary":"<p>I just ran into a tiny little problem and thought I&rsquo;d share the\nsolution.<\/p>\n<p>I was writing some tests in which I was mocking a dependency using\n<a href=\"http:\/\/www.voidspace.org.uk\/python\/mock\">Mock<\/a>. My test code was roughly equivalent to the following (based on\nan example in the Mock <a href=\"http:\/\/www.voidspace.org.uk\/python\/mock\/magicmock.html\">documentation on magic methods<\/a>):<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"gp\">&gt;&gt;&gt; <\/span><span class=\"n\">sub1 \u2026<\/span><\/code><\/pre><\/div>","content":"<p>I just ran into a tiny little problem and thought I&rsquo;d share the\nsolution.<\/p>\n<p>I was writing some tests in which I was mocking a dependency using\n<a href=\"http:\/\/www.voidspace.org.uk\/python\/mock\">Mock<\/a>. My test code was roughly equivalent to the following (based on\nan example in the Mock <a href=\"http:\/\/www.voidspace.org.uk\/python\/mock\/magicmock.html\">documentation on magic methods<\/a>):<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"gp\">&gt;&gt;&gt; <\/span><span class=\"n\">sub1<\/span> <span class=\"o\">=<\/span> <span class=\"n\">Mock<\/span><span class=\"p\">()<\/span>\n<span class=\"gp\">&gt;&gt;&gt; <\/span><span class=\"n\">sub1<\/span><span class=\"o\">.<\/span><span class=\"n\">value<\/span> <span class=\"o\">=<\/span> <span class=\"mi\">1<\/span>\n<span class=\"gp\">&gt;&gt;&gt; <\/span><span class=\"n\">sub2<\/span> <span class=\"o\">=<\/span> <span class=\"n\">Mock<\/span><span class=\"p\">()<\/span>\n<span class=\"gp\">&gt;&gt;&gt; <\/span><span class=\"n\">sub2<\/span><span class=\"o\">.<\/span><span class=\"n\">value<\/span> <span class=\"o\">=<\/span> <span class=\"mi\">2<\/span>\n<span class=\"gp\">&gt;&gt;&gt; <\/span><span class=\"n\">m<\/span> <span class=\"o\">=<\/span> <span class=\"n\">Mock<\/span><span class=\"p\">()<\/span>\n<span class=\"gp\">&gt;&gt;&gt; <\/span><span class=\"n\">m<\/span><span class=\"o\">.<\/span><span class=\"fm\">__iter__<\/span> <span class=\"o\">=<\/span> <span class=\"n\">Mock<\/span><span class=\"p\">(<\/span><span class=\"n\">return_value<\/span> <span class=\"o\">=<\/span> <span class=\"nb\">iter<\/span><span class=\"p\">([<\/span><span class=\"n\">sub1<\/span><span class=\"p\">,<\/span> <span class=\"n\">sub2<\/span><span class=\"p\">]))<\/span>\n<\/code><\/pre><\/div>\n\n<p>The point here was to mock the <code>__iter__<\/code> method to be able to use the\nmain mock in a list comprehension statement. The odd thing was that my\ntests failed, and I quickly found that of two list comprehension\nstatements, the second would return an empty result:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"gp\">&gt;&gt;&gt; <\/span><span class=\"p\">[<\/span><span class=\"n\">x<\/span><span class=\"o\">.<\/span><span class=\"n\">value<\/span> <span class=\"k\">for<\/span> <span class=\"n\">x<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">m<\/span> <span class=\"k\">if<\/span> <span class=\"n\">x<\/span><span class=\"o\">.<\/span><span class=\"n\">value<\/span> <span class=\"o\">==<\/span> <span class=\"mi\">1<\/span><span class=\"p\">]<\/span>\n<span class=\"go\">[1]<\/span>\n\n<span class=\"gp\">&gt;&gt;&gt; <\/span><span class=\"p\">[<\/span><span class=\"n\">x<\/span><span class=\"o\">.<\/span><span class=\"n\">value<\/span> <span class=\"k\">for<\/span> <span class=\"n\">x<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">m<\/span> <span class=\"k\">if<\/span> <span class=\"n\">x<\/span><span class=\"o\">.<\/span><span class=\"n\">value<\/span> <span class=\"o\">==<\/span> <span class=\"mi\">2<\/span><span class=\"p\">]<\/span>\n<span class=\"go\">[]<\/span>\n<\/code><\/pre><\/div>\n\n<p>An educated guess is that the first iteration consumes all elements and\nleaves the iterator exhausted! As it turns out, this is clearly stated\nin the Python <a href=\"http:\/\/docs.python.org\/glossary.html#term-iterator\">documentation about iterator objects<\/a>:<\/p>\n<blockquote>\n<p>One notable exception is code which attempts multiple iteration\npasses. [&hellip;] Attempting this with an iterator will just return the\nsame exhausted iterator object used in the previous iteration pass,\nmaking it appear like an empty container.<\/p>\n<\/blockquote>\n<p>To solve the problem, I had to use the <a href=\"http:\/\/www.voidspace.org.uk\/python\/mock\/magicmock.html#magic-mock\">MagicMock class<\/a> instead. The\ndocumentation says:<\/p>\n<blockquote>\n<p>In 0.8 the <strong>iter<\/strong> also gained special handling implemented with\na side effect. The return value of MagicMock.<strong>iter<\/strong> can be any\niterable object and isn\u2019t required to be an iterator<\/p>\n<\/blockquote>\n<p>&hellip;and gives an example similar to the following:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">m<\/span> <span class=\"o\">=<\/span> <span class=\"n\">MagicMock<\/span><span class=\"p\">()<\/span>\n<span class=\"n\">m<\/span><span class=\"o\">.<\/span><span class=\"fm\">__iter__<\/span><span class=\"o\">.<\/span><span class=\"n\">return_value<\/span> <span class=\"o\">=<\/span> <span class=\"p\">[<\/span><span class=\"n\">sub1<\/span><span class=\"p\">,<\/span> <span class=\"n\">sub2<\/span><span class=\"p\">]<\/span>\n<\/code><\/pre><\/div>\n\n<p>Putting it to the test:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"gp\">&gt;&gt;&gt; <\/span><span class=\"p\">[<\/span><span class=\"n\">x<\/span><span class=\"o\">.<\/span><span class=\"n\">value<\/span> <span class=\"k\">for<\/span> <span class=\"n\">x<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">m<\/span> <span class=\"k\">if<\/span> <span class=\"n\">x<\/span><span class=\"o\">.<\/span><span class=\"n\">value<\/span> <span class=\"o\">==<\/span> <span class=\"mi\">1<\/span><span class=\"p\">]<\/span>\n<span class=\"go\">[1]<\/span>\n\n<span class=\"gp\">&gt;&gt;&gt; <\/span><span class=\"p\">[<\/span><span class=\"n\">x<\/span><span class=\"o\">.<\/span><span class=\"n\">value<\/span> <span class=\"k\">for<\/span> <span class=\"n\">x<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">m<\/span> <span class=\"k\">if<\/span> <span class=\"n\">x<\/span><span class=\"o\">.<\/span><span class=\"n\">value<\/span> <span class=\"o\">==<\/span> <span class=\"mi\">2<\/span><span class=\"p\">]<\/span>\n<span class=\"go\">[2]<\/span>\n<\/code><\/pre><\/div>\n\n<p>It works! :-) A final note: It&rsquo;s really 0.8 that is required; I tried\nwith 0.8.0beta3 (which I had installed), and it didn&rsquo;t work. An upgrade\nwas needed!<\/p>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"iteration"}},{"@attributes":{"term":"list comprehension"}},{"@attributes":{"term":"magic mock"}},{"@attributes":{"term":"Python"}}]},{"title":"Nothing surprises me in VB.NET","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/nothing-surprises-me-in-vbnet.html","rel":"alternate"}},"published":"2012-03-27T19:11:00+02:00","updated":"2012-03-27T19:11:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2012-03-27:\/nothing-surprises-me-in-vbnet.html","summary":"<p>I currently work in a VB.NET project with a customer, and what amazes me\nis that I over and over again get the feeling that the language is\ndesigned to be easy to work with, but at the same time there are so many\naspects of it that behave \u2026<\/p>","content":"<p>I currently work in a VB.NET project with a customer, and what amazes me\nis that I over and over again get the feeling that the language is\ndesigned to be easy to work with, but at the same time there are so many\naspects of it that behave in a, to me, completely unexpected and\nnon-intuitive way. I&rsquo;ve thought many times that I should write something\nabout these different &ldquo;aha moments&rdquo; where something has baffled me, but\nthat would easily turn into pointless ranting. Not so long ago, however,\nI stumbled across something that I do think is relevant to bring to the\nsurface. So here it comes! :-)<\/p>\n<p>Remember that my perspective here is that of a Java\/C# programmer. If\nyou&rsquo;re a VB.NET programmer by heart, I assume you will spot my incorrect\nassumption pretty quickly.<\/p>\n<p>Some background: In Java and C#, you can use the conditional <code>? :<\/code>\noperator for evaluating short conditional expressions. VB.NET has the\n<code>IIf<\/code> function which behaves similarly, except it eagerly evaluates both\nthe true expression and the false expression (it&rsquo;s a function after\nall), which sometimes (most of the time?) is undesirable. However, <a href=\"http:\/\/en.wikipedia.org\/wiki\/Visual_Basic_.NET#Visual_Basic_2008_.28VB_9.0.29\">VB\n9<\/a> introduced the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/bb513985.aspx\"><code>If<\/code> operator<\/a>, which properly only evaluates the\nexpression that corresponds to the conditional value.<\/p>\n<p>Now, I observed the aforementioned surprising behavior after writing a\nfunction with return type <code>DateTime?<\/code> (i.e., a nullable <code>DateTime<\/code>) in which\nI conditionally returned either a <code>DateTime<\/code> value or <code>Nothing<\/code> using the <code>If<\/code>\noperator. When I tried to save the resulting value in a database in the\n<code>Nothing<\/code> case I got back an exception saying that the date was way out of\nrange! The following code snippet illustrates what I did (except the\nconditional value wasn&rsquo;t a boolean literal, of course):<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">Module<\/span><span class=\"w\"> <\/span><span class=\"nn\">Module1<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">Sub<\/span><span class=\"w\"> <\/span><span class=\"nf\">Main<\/span><span class=\"p\">()<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">Console<\/span><span class=\"p\">.<\/span><span class=\"n\">WriteLine<\/span><span class=\"p\">(<\/span><span class=\"n\">SomeDate<\/span><span class=\"p\">())<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">End<\/span><span class=\"w\"> <\/span><span class=\"k\">Sub<\/span>\n\n<span class=\"w\">    <\/span><span class=\"k\">Function<\/span><span class=\"w\"> <\/span><span class=\"nf\">SomeDate<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"ow\">As<\/span><span class=\"w\"> <\/span><span class=\"n\">DateTime<\/span><span class=\"err\">?<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">Return<\/span><span class=\"w\"> <\/span><span class=\"k\">If<\/span><span class=\"p\">(<\/span><span class=\"k\">False<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">DateTime<\/span><span class=\"p\">.<\/span><span class=\"n\">Now<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"k\">Nothing<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">End<\/span><span class=\"w\"> <\/span><span class=\"k\">Function<\/span>\n<span class=\"k\">End<\/span><span class=\"w\"> <\/span><span class=\"k\">Module<\/span>\n<\/code><\/pre><\/div>\n\n<p>What does the code above print? The answer: 0001-01-01 00:00:00, which\ncorresponds to <code>DateTime.MinValue<\/code>. Huh? Let\u2019s look at the corresponding\ncode in C#:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">internal<\/span><span class=\"w\"> <\/span><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">Program<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">private<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">Main<\/span><span class=\"p\">(<\/span><span class=\"kt\">string<\/span><span class=\"p\">[]<\/span><span class=\"w\"> <\/span><span class=\"n\">args<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">Console<\/span><span class=\"p\">.<\/span><span class=\"n\">WriteLine<\/span><span class=\"p\">(<\/span><span class=\"n\">SomeDate<\/span><span class=\"p\">());<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">    <\/span><span class=\"k\">private<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"n\">DateTime<\/span><span class=\"o\">?<\/span><span class=\"w\"> <\/span><span class=\"n\">SomeDate<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"k\">false<\/span><span class=\"w\"> <\/span><span class=\"o\">?<\/span><span class=\"w\"> <\/span><span class=\"n\">DateTime<\/span><span class=\"p\">.<\/span><span class=\"n\">Now<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">DateTime<\/span><span class=\"o\">?<\/span><span class=\"p\">)<\/span><span class=\"k\">null<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Note that the C# compiler doesn&rsquo;t allow us to just write <code>null<\/code> as the\nfalse expression; an explicit cast to <code>DateTime?<\/code>is required. The reason\nis that it cannot implicitly convert between <code>null<\/code> and <code>DateTime<\/code> (and this\nis a clue to the final answer). The C# code produces an empty output,\njust as expected.<\/p>\n<p>So what happened here? When googling for differences in how C# and\nVB.NET initialize value types, I found <a href=\"http:\/\/stackoverflow.com\/questions\/303502\/c-sharp-vs-vb-net-handling-of-null-structures\">this StackOverflow thread<\/a>,\nwhich lead me to read more about the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/0x9tb07z(v=vs.100).aspx\"><code>Nothing<\/code> keyword<\/a>. I learned that\nfor a non-nullable value type, <code>Nothing<\/code> evaluates to the default value of\nthe type, which happens to be <code>DateTime.MinValue<\/code> for <code>DateTime<\/code>. So that&rsquo;s\nwhat happened! But why? The answer is in the type inference taking place\nfor the <code>If<\/code> operator; the compiler realizes that the resulting type can\nbe non-nullable <code>DateTime<\/code>, since <code>Nothing<\/code> in that context will evaluate to\nthe default <code>DateTime<\/code> value. Next, the result is assigned to a nullable\n<code>DateTime<\/code>, which is perfectly fine. In C#, as noted above and in the\nMSDN link, <code>null<\/code> does not behave as <code>Nothing<\/code> and a compile-time error\nwould occur (which is why the cast is required).<\/p>\n<p>So, the root cause was an incorrect assumption that <code>Nothing<\/code> behaves as\n<code>null<\/code>, and the subsequent use of <code>Nothing<\/code> in the <code>If<\/code> operator.<\/p>\n<p>One solution is to use an explicit cast, which brings us closer to the\nC# version of the code:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">Function<\/span><span class=\"w\"> <\/span><span class=\"nf\">SomeDate<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"ow\">As<\/span><span class=\"w\"> <\/span><span class=\"n\">DateTime<\/span><span class=\"err\">?<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">Return<\/span><span class=\"w\"> <\/span><span class=\"k\">If<\/span><span class=\"p\">(<\/span><span class=\"k\">False<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">DateTime<\/span><span class=\"p\">.<\/span><span class=\"n\">Now<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"k\">DirectCast<\/span><span class=\"p\">(<\/span><span class=\"k\">Nothing<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">DateTime<\/span><span class=\"err\">?<\/span><span class=\"p\">))<\/span>\n<span class=\"k\">End<\/span><span class=\"w\"> <\/span><span class=\"k\">Function<\/span>\n<\/code><\/pre><\/div>\n\n<p>IMHO this is a bit clumsy, and it makes the otherwise elegant\nconditional expression read a lot less clearly. Thus, I ended up not\nusing the <code>If<\/code> operator at all:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">Function<\/span><span class=\"w\"> <\/span><span class=\"nf\">SomeDate<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"ow\">As<\/span><span class=\"w\"> <\/span><span class=\"n\">DateTime<\/span><span class=\"err\">?<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">If<\/span><span class=\"w\"> <\/span><span class=\"k\">False<\/span><span class=\"w\"> <\/span><span class=\"k\">Then<\/span><span class=\"w\"> <\/span><span class=\"k\">Return<\/span><span class=\"w\"> <\/span><span class=\"n\">DateTime<\/span><span class=\"p\">.<\/span><span class=\"n\">Now<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">Return<\/span><span class=\"w\"> <\/span><span class=\"k\">Nothing<\/span>\n<span class=\"k\">End<\/span><span class=\"w\"> <\/span><span class=\"k\">Function<\/span>\n<\/code><\/pre><\/div>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"nothing"}},{"@attributes":{"term":"null"}},{"@attributes":{"term":"vb.net"}}]},{"title":"NSubstitute vs Moq - a quick comparison","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/nsubstitute-vs-moq-a-quick-comparison.html","rel":"alternate"}},"published":"2012-02-27T22:50:00+01:00","updated":"2012-02-27T22:50:00+01:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2012-02-27:\/nsubstitute-vs-moq-a-quick-comparison.html","summary":"<p>When you write unit tests, you occasionally need to mock away\ndependencies of the subject under test (SUT). By far the easiest way to\ndo this is to use a mocking library, which has the added benefit that it\nallows you to verify the behavior of the SUT by inspecting \u2026<\/p>","content":"<p>When you write unit tests, you occasionally need to mock away\ndependencies of the subject under test (SUT). By far the easiest way to\ndo this is to use a mocking library, which has the added benefit that it\nallows you to verify the behavior of the SUT by inspecting its\ninteraction with the mock. I&rsquo;ve used <a href=\"http:\/\/easymock.org\/\">EasyMock<\/a> for Java quite a lot,\nbut one of its drawbacks, one that it shares with many other mocking\nlibraries, is that it uses a record\/replay pattern, which leads to a\ntest case on the following form:<\/p>\n<ol>\n<li>Setup mock response behavior and expectations.<\/li>\n<li>Put the mock object into replay mode.<\/li>\n<li>Do something with the SUT (this should be the meat of the test,\n    really).<\/li>\n<li>Verify that all mock expectations were met, in one go.<\/li>\n<\/ol>\n<p>Even with only a modest number of expectations, a test case on this form\neasily becomes front-heavy, and the SUT interaction may be drowned out.\nAnother big problem is that the form does not lend itself well to a\n<a href=\"http:\/\/www.google.com\/search?q=context+specification+bdd\">context\/specification<\/a> style of testing. Using that style, you have a\nsingle context setup (including SUT interaction) and multiple\nspecifications (tests). Thus, you&rsquo;d want to verify individual mock calls\nfor each specification rather than verifying all expectations at once.<\/p>\n<p>When I first encountered <a href=\"http:\/\/code.google.com\/p\/moq\/\">Moq<\/a>, a mocking library for .NET, I was\npleased to find that it allows me to verify individual mock calls, which\ncompletely eradicates the need of defining expectations. As a result, I\ncan specify mock response behavior in the context setup, and verify how\nthe SUT interacts with the mock in the specifications (tests). There is\nalso no need to separate record and replay modes. Nice!<\/p>\n<p>However, after having used Moq for a while in a VB.NET project, I feel\nthat its syntax is a bit too noisy (perhaps this is partly the fault of\nVB.NET, which in itself is much noisier than C#). And even though its\nuse of lambdas is neat, I&rsquo;m not sure it&rsquo;s best for readability.\nSearching for alternatives, I came across <a href=\"http:\/\/nsubstitute.github.com\/\">NSubstitute<\/a>, and I\nimmediately felt that this was what I was looking for!<\/p>\n<p>NSubstitute has, IMHO, a much cleaner syntax than Moq, and it supports\nthe context\/specification style out of the box. Below is a quick\ncomparison between the two. I&rsquo;ve only tested a few aspects so far, but\nNSubsitute feels a lot better!<\/p>\n<h3>Comparing the two<\/h3>\n<p>Let&rsquo;s say that we have an interface for some sort of quiz engine. It&rsquo;s\npretty simple; when there are numbers available, it raises an event. A\nquiz solver can then read the numbers, sum them and provide the sum to\nthe quiz engine.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">Public<\/span><span class=\"w\"> <\/span><span class=\"k\">Interface<\/span><span class=\"w\"> <\/span><span class=\"n\">IQuiz<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">Event<\/span><span class=\"w\"> <\/span><span class=\"n\">HasNumbers<\/span><span class=\"w\"> <\/span><span class=\"ow\">As<\/span><span class=\"w\"> <\/span><span class=\"n\">Action<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">ReadOnly<\/span><span class=\"w\"> <\/span><span class=\"k\">Property<\/span><span class=\"w\"> <\/span><span class=\"nf\">Numbers<\/span><span class=\"w\"> <\/span><span class=\"ow\">As<\/span><span class=\"w\"> <\/span><span class=\"n\">IEnumerable<\/span><span class=\"p\">(<\/span><span class=\"k\">Of<\/span><span class=\"w\"> <\/span><span class=\"kt\">Integer<\/span><span class=\"p\">)<\/span>\n\n<span class=\"w\">    <\/span><span class=\"k\">Sub<\/span><span class=\"w\"> <\/span><span class=\"nf\">SumIs<\/span><span class=\"p\">(<\/span><span class=\"n\">sum<\/span><span class=\"w\"> <\/span><span class=\"ow\">As<\/span><span class=\"w\"> <\/span><span class=\"kt\">Integer<\/span><span class=\"p\">)<\/span>\n<span class=\"k\">End<\/span><span class=\"w\"> <\/span><span class=\"k\">Interface<\/span>\n<\/code><\/pre><\/div>\n\n<p>To test the summing capability of a quiz solver, let&rsquo;s use a quiz engine\nmock! First, the mock creation:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c\">&#39; Moq<\/span>\n<span class=\"k\">Dim<\/span><span class=\"w\"> <\/span><span class=\"n\">quizMock<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">New<\/span><span class=\"w\"> <\/span><span class=\"n\">Mock<\/span><span class=\"p\">(<\/span><span class=\"k\">Of<\/span><span class=\"w\"> <\/span><span class=\"n\">IQuiz<\/span><span class=\"p\">)()<\/span>\n\n<span class=\"c\">&#39; NSubstitute<\/span>\n<span class=\"k\">Dim<\/span><span class=\"w\"> <\/span><span class=\"n\">quiz<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Substitute<\/span><span class=\"p\">.<\/span><span class=\"n\">For<\/span><span class=\"p\">(<\/span><span class=\"k\">Of<\/span><span class=\"w\"> <\/span><span class=\"n\">IQuiz<\/span><span class=\"p\">)()<\/span>\n<\/code><\/pre><\/div>\n\n<p>Not a huge difference, but I think NSubstitute is a bit more readable!\nWhat&rsquo;s not visible from this, but which becomes obvious later on, is\nthat the type of <code>quizMock<\/code> is <code>Mock(Of IQuiz)<\/code>, whereas the type of\n<code>quiz<\/code> is <code>IQuiz<\/code>. Next, let&rsquo;s define some mock response behavior.\nSpecifically, we want our <code>Numbers<\/code> property to return the numbers 1, 2\nand 3:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c\">&#39; Moq<\/span>\n<span class=\"n\">quizMock<\/span><span class=\"p\">.<\/span><span class=\"n\">SetupGet<\/span><span class=\"p\">(<\/span><span class=\"n\">Function<\/span><span class=\"p\">(<\/span><span class=\"n\">quiz<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"n\">quiz<\/span><span class=\"p\">.<\/span><span class=\"n\">Numbers<\/span><span class=\"p\">).<\/span><span class=\"n\">Returns<\/span><span class=\"p\">({<\/span><span class=\"mi\">1<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mi\">2<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mi\">3<\/span><span class=\"p\">})<\/span>\n\n<span class=\"c\">&#39; NSubstitute<\/span>\n<span class=\"n\">quiz<\/span><span class=\"p\">.<\/span><span class=\"n\">Numbers<\/span><span class=\"p\">.<\/span><span class=\"n\">Returns<\/span><span class=\"p\">({<\/span><span class=\"mi\">1<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mi\">2<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mi\">3<\/span><span class=\"p\">})<\/span>\n<\/code><\/pre><\/div>\n\n<p>Now the difference is much bigger. With Moq, we have to call a special\n<code>SetupGet<\/code> method on the mock, and pass a lambda that represents the\ncall for which we want to specify a behavior (internally, the lambda\nbecomes an <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/bb397951.aspx\" title=\"Expression trees @ MSDN\">expression tree<\/a> that Moq parses). Contrast that with the\nstraight-forward syntax of NSubsitute (where <code>Returns<\/code> is an <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/bb384936.aspx\" title=\"Extension methods for VB.NET @ MSDN\">extension\nmethod<\/a>). A clear win for NSubstitute, I think!<\/p>\n<p>Now it&rsquo;s time to make our SUT (the construction of which I have omitted\nbecause it has nothing to do with the choice of mocking library,\nobviously) do its work, and since it&rsquo;s triggered by an event, we need to\nraise the event on the mock:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c\">&#39; Moq<\/span>\n<span class=\"n\">quizMock<\/span><span class=\"p\">.<\/span><span class=\"n\">Raise<\/span><span class=\"p\">(<\/span><span class=\"n\">Sub<\/span><span class=\"p\">(<\/span><span class=\"n\">quiz<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"k\">AddHandler<\/span><span class=\"w\"> <\/span><span class=\"n\">quiz<\/span><span class=\"p\">.<\/span><span class=\"n\">HasNumbers<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"k\">Nothing<\/span><span class=\"p\">)<\/span>\n\n<span class=\"c\">&#39; NSubstitute<\/span>\n<span class=\"k\">AddHandler<\/span><span class=\"w\"> <\/span><span class=\"n\">quiz<\/span><span class=\"p\">.<\/span><span class=\"n\">HasNumbers<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Raise<\/span><span class=\"p\">.<\/span><span class=\"n\">Event<\/span><span class=\"p\">(<\/span><span class=\"k\">Of<\/span><span class=\"w\"> <\/span><span class=\"n\">Action<\/span><span class=\"p\">)()<\/span>\n<\/code><\/pre><\/div>\n\n<p>Not a big difference, although the <code>Nothing<\/code> argument required to\nrepresent an event handler in the Moq case can be confusing - and even\nmore so if the event is parameterized. The <code>AddHandler<\/code> syntax of VB.NET\nis pretty noisy and there&rsquo;s not much a mocking library can do to\novercome that.<\/p>\n<p>Finally, let&rsquo;s verify that the solver sums the numbers correctly:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c\">&#39; Moq<\/span>\n<span class=\"n\">quizMock<\/span><span class=\"p\">.<\/span><span class=\"n\">Verify<\/span><span class=\"p\">(<\/span><span class=\"n\">Sub<\/span><span class=\"p\">(<\/span><span class=\"n\">quiz<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"n\">quiz<\/span><span class=\"p\">.<\/span><span class=\"n\">SumIs<\/span><span class=\"p\">(<\/span><span class=\"mi\">6<\/span><span class=\"p\">))<\/span>\n\n<span class=\"c\">&#39; NSubstitute<\/span>\n<span class=\"n\">quiz<\/span><span class=\"p\">.<\/span><span class=\"n\">Received<\/span><span class=\"p\">().<\/span><span class=\"n\">SumIs<\/span><span class=\"p\">(<\/span><span class=\"mi\">6<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>Again, I think NSubsitute comes out as winner since its syntax is less\ncumbersome and more &ldquo;on the spot&rdquo;. In this case, the argument matching\nprocess is simple and handled automatically by both mocking libraries.\nWith more complex arguments (lists, for example), we may need to use\nmore sophisticated argument matching, which reads roughly the same in\nboth libraries.<\/p>\n<p>The overall verdict? I really like NSubstitute over Moq due to its more\nreadable syntax!<\/p>\n<h3>A note on event handlers and VB.NET<\/h3>\n<p>In VB.NET, an event can be defined without an event handler type. So for\nexample, the <code>HasNumbers<\/code> event in our <code>IQuiz<\/code> interface could be\ndefined as:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">Public<\/span><span class=\"w\"> <\/span><span class=\"k\">Interface<\/span><span class=\"w\"> <\/span><span class=\"n\">IQuiz<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">Event<\/span><span class=\"w\"> <\/span><span class=\"n\">HasNumbers<\/span><span class=\"p\">()<\/span>\n<span class=\"w\">    <\/span><span class=\"c\">&#39;...<\/span>\n<span class=\"k\">End<\/span><span class=\"w\"> <\/span><span class=\"k\">Interface<\/span>\n<\/code><\/pre><\/div>\n\n<p>NSubstitute doesn&rsquo;t like this, though, because there is no <code>Raise.Event<\/code>\nmethod overload that can be converted to the anonymous event handler\ntype that is created. Therefore, you have to specify the event handler\ntype of the event explicitly, as we did previously.<\/p>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"mock"}},{"@attributes":{"term":"moq"}},{"@attributes":{"term":"nsubstitute"}},{"@attributes":{"term":"test"}}]},{"title":"Using Git locally within a Subversion branch","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/using-git-locally-within-a-subversion-branch.html","rel":"alternate"}},"published":"2012-01-19T23:44:00+01:00","updated":"2012-01-19T23:44:00+01:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2012-01-19:\/using-git-locally-within-a-subversion-branch.html","summary":"<p>I&rsquo;m not a big fan of <a href=\"http:\/\/subversion.apache.org\/\">Subversion<\/a> but I&rsquo;m madly in love with <a href=\"http:\/\/git-scm.com\/\">Git<\/a>!\nSo much that when I have to use Subversion, I create a Git repository\nwithin my locally checked out Subversion branch. This is really easy to\ndo, and only takes four simple steps:<\/p>\n<ol>\n<li>Navigate \u2026<\/li><\/ol>","content":"<p>I&rsquo;m not a big fan of <a href=\"http:\/\/subversion.apache.org\/\">Subversion<\/a> but I&rsquo;m madly in love with <a href=\"http:\/\/git-scm.com\/\">Git<\/a>!\nSo much that when I have to use Subversion, I create a Git repository\nwithin my locally checked out Subversion branch. This is really easy to\ndo, and only takes four simple steps:<\/p>\n<ol>\n<li>Navigate to the directory that contains your Subversion branch copy\n    and use the <a href=\"http:\/\/gitref.org\/creating\/#init\"><code>git init<\/code><\/a> command to create a repository.<\/li>\n<li>Create a .gitignore file and add a filter to ignore .svn directories\n    (plus everything else that should be ignored, of course).<\/li>\n<li>Use <a href=\"http:\/\/gitref.org\/basic\/#add\"><code>git add<\/code><\/a> and <a href=\"http:\/\/gitref.org\/basic\/#commit\"><code>git commit<\/code><\/a> to create an initial commit\n    with the .gitignore file and all code.<\/li>\n<li>Configure Subversion to ignore the .git directory.<\/li>\n<\/ol>\n<p>Now you&rsquo;re ready to work some Git magic! I won&rsquo;t go into details, but\nhere are a few things that I find very useful:<\/p>\n<ul>\n<li>Use the <a href=\"http:\/\/gitref.org\/basic\/#reset\"><code>git reset<\/code><\/a> command to undo local changes. (Yeah, I know\n    you can use Subversion&rsquo;s revert command too.)<\/li>\n<li>Use the <a href=\"http:\/\/book.git-scm.com\/4_stashing.html\"><code>git stash<\/code><\/a> command to temporarily save changes.<\/li>\n<li>Create commits every now and then as &ldquo;check points&rdquo;. This is\n    <strong>definitively not<\/strong> how you should use Git, but in this context it\n    can save a lot of time. Especially if you work with the Visual\n    Studio WinForms designer, which happily gets into an unrecoverable\n    state every now or then! (Just had to get that off my chest!)<\/li>\n<li>Create separate commits for each Subversion update you do. While\n    such a commit is unlikely to be particularly coherent (after all, it\n    can include work from several of your co-workers), you now have a\n    way to pinpoint when bugs were introduced. The <a href=\"http:\/\/book.git-scm.com\/5_finding_issues_-_git_bisect.html\"><code>git bisect<\/code><\/a>\n    command is immensely useful for this purpose, in particular together\n    with a small test runner script.<\/li>\n<li>Use the <a href=\"http:\/\/gitref.org\/branching\/#checkout\"><code>git checkout<\/code><\/a> command to quickly create branches to\n    experiment or try out ideas.<\/li>\n<li>\n<p>Use branching to facilitate &ldquo;offline work&rdquo;. For example, if you\n    worked on a copy of the code somewhere else but accidentally did a\n    Subversion update in the main branch copy, you can:<\/p>\n<ol>\n<li>Stash the changes from the update,<\/li>\n<li>create a new branch,<\/li>\n<li>copy your code into that branch,<\/li>\n<li>create a commit,<\/li>\n<li>switch back to the main branch, and finally<\/li>\n<li>merge from the separate branch using the <a href=\"http:\/\/gitref.org\/branching\/#merge\"><code>git merge<\/code><\/a>\n    command.<\/li>\n<\/ol>\n<\/li>\n<li>\n<p>Use the distributed nature of Git to create a separate offline\n    repository, and then use <a href=\"http:\/\/gitref.org\/remotes\/#push\"><code>git push<\/code><\/a> or <a href=\"http:\/\/gitref.org\/remotes\/#fetch\"><code>git pull<\/code><\/a> to\n    synchronize between the repositories.<\/p>\n<\/li>\n<\/ul>\n<\/p>\n<p>Would you like to add anything to the list?<\/p>","category":[{"@attributes":{"term":"Tools"}},{"@attributes":{"term":"git"}},{"@attributes":{"term":"subversion"}}]},{"title":"LVM recipe: determine which physical volume(s) a logical volume is located on","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/lvm-recipe-determine-which-physical-volumes-a-logical-volume-is-located-on.html","rel":"alternate"}},"published":"2012-01-19T22:44:00+01:00","updated":"2012-01-19T22:44:00+01:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2012-01-19:\/lvm-recipe-determine-which-physical-volumes-a-logical-volume-is-located-on.html","summary":"<p>Run the <code>lvs<\/code> command as follows:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\"># lvs --segments -o +pe_ranges<\/span>\n<\/code><\/pre><\/div>\n\n<p>The output should be something similar to this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>LV      VG   Attr   #Str Type   SSize   PE Ranges\ndata    data -wi-ao    1 linear   1.82t \/dev\/md4:0-476930\ndata    data -wi-ao    1 linear   1.36t \/dev\/md2:0-357701\nhomes   data -wi-a-    1 \u2026<\/code><\/pre><\/div>","content":"<p>Run the <code>lvs<\/code> command as follows:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\"># lvs --segments -o +pe_ranges<\/span>\n<\/code><\/pre><\/div>\n\n<p>The output should be something similar to this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>LV      VG   Attr   #Str Type   SSize   PE Ranges\ndata    data -wi-ao    1 linear   1.82t \/dev\/md4:0-476930\ndata    data -wi-ao    1 linear   1.36t \/dev\/md2:0-357701\nhomes   data -wi-a-    1 linear   4.30g \/dev\/md1:38400-39499\n...\n<\/code><\/pre><\/div>\n\n<p>Note the &ldquo;PE Ranges&rdquo; column - from the table it follows that the logical\nvolume &ldquo;data&rdquo; is located on two physical volumes, \/dev\/md2 and \/dev\/md4.<\/p>","category":[{"@attributes":{"term":"Sysadmin"}},{"@attributes":{"term":"lvm"}},{"@attributes":{"term":"recipe"}}]},{"title":"Node.js experimentation - a GitHub clone script","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/nodejs-experimentation-a-github-clone-script.html","rel":"alternate"}},"published":"2012-01-19T10:32:00+01:00","updated":"2012-01-19T10:32:00+01:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2012-01-19:\/nodejs-experimentation-a-github-clone-script.html","summary":"<p>Recently I wrote my first <a href=\"http:\/\/nodejs.org\/\" title=\"Node.js home page\">Node.js<\/a> program! Yeah, yeah, I know! Late\nto the game and all that! But I thought it was time to catch up with the\nrest of the world. Better late than never, right? (Also, the program\nneeded to parse <a href=\"http:\/\/www.json.org\/\">JSON<\/a> data, so JavaScript felt \u2026<\/p>","content":"<p>Recently I wrote my first <a href=\"http:\/\/nodejs.org\/\" title=\"Node.js home page\">Node.js<\/a> program! Yeah, yeah, I know! Late\nto the game and all that! But I thought it was time to catch up with the\nrest of the world. Better late than never, right? (Also, the program\nneeded to parse <a href=\"http:\/\/www.json.org\/\">JSON<\/a> data, so JavaScript felt like a natural\nchoice.)<\/p>\n<p>What I wrote is a tiny script that clones all non-forked repositories,\nincluding gists, from GitHub. It&rsquo;s nothing advanced at all, and I\ncertainly didn&rsquo;t tap the full potential of the event-driven architecture\nof Node.js. But it was fun to write JavaScript code again, and it was\nfun to write asynchronous code. My colleague <a href=\"http:\/\/aslamkhan.net\/\" title=\"f3yourmind\">Aslam Khan<\/a> says that\nit&rsquo;s a challenge to put your mind into &ldquo;async mode&rdquo;, and I couldn&rsquo;t\nagree more. But once you have done it, endless new possibilities open\nup! :-)<\/p>\n<p>Anyhow, less talk, more code:a<\/p>\n<div class=\"gist\">\n    <script src='https:\/\/gist.github.com\/1597431.js?file=ghclone.js'><\/script>\n    <noscript>\n        <pre><code>\/*\n * A Node.js script that clones all non-forked repos and all gists on GitHub\n * for a user. If the repos\/gists have been cloned already, the script pulls\n * new commits from GitHub instead.\n *\n * Usage:\n *\n *   node ghclone.js -u <user> -p <password> -d <destination dir>\n *\n * Tested with Node.js version 0.6.7.\n *\n * Author: Per Rovegard <per@rovegard.se>\n *\/\n\nvar https = require('https'),\n    exec = require('child_process').exec,\n    path = require('path'),\n    util = require('util'),\n    events = require('events'),\n    emitter = new events.EventEmitter();\n\n\/\/ Configure the emitter to print messages to the console, and to exit if we\n\/\/ run into a severe condition.\nemitter\n  .on('info', console.info)\n  .on('error', console.error)\n  .on('severe', function(err) {\n    console.error(err);\n    process.exit(1);\n  });\n\n\/\/ Used by exec to print the result of executing a subprocess.\nfunction puts(error, stdout, stderr) {\n  if (error) {\n    emitter.emit('error', error);\n  } else {\n    emitter.emit('info', stdout.trim());\n    if (stderr) {\n      emitter.emit('error', stderr.trim());\n    }\n  }\n}\n\n\/\/ Assembles the value of the Authorization header passed in the HTTPS request\n\/\/ to GitHub.\nfunction auth(user, pass) {\n  return 'Basic ' + (new Buffer(user + ':' + pass)).toString('base64'); \n}\n\n\/\/ Performs a git pull in the given git directory.\nfunction git_pull(gitdir) {\n  exec(util.format('git --git-dir=%s\/.git pull', gitdir), puts);\n}\n\n\/\/ Performs a git clone of the given URL into the given directory.\nfunction git_clone(url, dir) {\n  exec(util.format('git clone %s %s', url, dir), puts);\n}\n\n\/\/ Create a worker for do_clone to be used in the call to path.exists.\n\/\/ Required to get the loop variable values correct.\nfunction create_worker(gitdir, clone_url) {\n  return function(exists) {\n    if (exists) {\n      emitter.emit('info', util.format('%s exists, will pull.', gitdir));\n      git_pull(gitdir);\n    } else {\n      emitter.emit('info', util.format('%s does not exist, will clone from %s.', gitdir, clone_url));\n      git_clone(clone_url, gitdir);\n    }\n  }\n}\n\n\/* Performs the actual process of iterating over repositories and gists, and\n * cloning or pulling depending on whether or not the corresponding\n * destination directory already exists. Forked repositories are excluded\n * during iteration, and will thus not be cloned.\n *\n * The first parameter takes the JSON data coming from the server, and the\n * second takes the destination directory into which individual repositories\n * and gists are cloned (i.e., they are cloned into subdirectories of this\n * directory). The directory is assumed to exist at this point.\n *\/\nfunction do_clone(data, destdir) {\n  var json = JSON.parse(data);\n  if (json.message) {\n    emitter.emit('severe', util.format('GitHub responded: %s', json.message));\n  }\n  json.forEach(function(repo) {\n    if (!repo.fork) {\n      var name = repo.name || repo.id;\n      var clone_url = repo.clone_url || repo.git_pull_url;\n      var gitdir = path.join(destdir, name);\n      path.exists(gitdir, create_worker(gitdir, clone_url));\n    }\n  });\n}\n\n\/\/ Main entry point of the program.\nfunction main(username, password, destdir) {\n  var http_options = {\n    host: 'api.github.com',\n    headers: {\n      'Authorization': auth(username, password)\n    }\n  };\n\n  ['\/user\/repos', '\/gists'].forEach(function(path) {\n    http_options.path = path;\n    https.get(http_options, function(res) {\n      var data = '';\n      res.on('data', function(d) {\n        data += d;\n      });\n      res.on('end', function() {\n        do_clone(data, destdir);\n      });\n    }).on('error', function(e) { \n      emitter.emit('error', e);\n    });\n  });\n}\n\n\/* Simple argument parser that looks for arguments that begin with a dash, \n * and requires each such argument to have a non-option associated value.\n * Options and their values are stored in an associative array which is the\n * result of this function.\n *\/\nfunction parse_args(args) {\n  var opts = {};\n  for (var i = 0; i < args.length; i++) {\n    if (args[i][0] == '-') {\n      var value = args[i + 1];\n      if (value && value[0] != '-') {\n        eval(util.format('opts.%s = \"%s\"', args[i].substring(1), value));\n        i++;\n      }\n    }\n  }\n  return opts;\n}\n\nvar opts = parse_args(process.argv.slice(2)),\n    user = opts.u,\n    password = opts.p,\n    destdir = opts.d;\n\n\/\/ Sanity check of arguments.\nif (!(user && password && destdir)) {\n  emitter.emit('severe', util.format('Usage: node %s -u <username> -p <password> -d <destination dir>', process.argv[1]));\n}\n\npath.exists(destdir, function(exists) {\n  if (exists) {\n    \/\/ Run the show!\n    main(user, password, destdir);\n  } else {\n    \/\/ The destination directory must exist!\n    emitter.emit('severe', util.format('Destination directory %s cannot be found.', destdir));\n  }\n});\n\n<\/code><\/pre>\n    <\/noscript>\n<\/div>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"async"}},{"@attributes":{"term":"git"}},{"@attributes":{"term":"node.js"}}]},{"title":"Strongly typed properties in Java vs C#","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/strongly-typed-properties-in-java-vs-c.html","rel":"alternate"}},"published":"2012-01-19T00:48:00+01:00","updated":"2012-01-19T00:48:00+01:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2012-01-19:\/strongly-typed-properties-in-java-vs-c.html","summary":"<p>The background for this post was that I needed to implement strongly\ntyped properties in a C# project. With <em>strongly typed property<\/em>, I\nspecifically mean a strongly typed version of\n<code>public object GetProperty(string propertyName)<\/code>, where the property\nname is a constant (or <em>name<\/em>) of some sort, and the return \u2026<\/p>","content":"<p>The background for this post was that I needed to implement strongly\ntyped properties in a C# project. With <em>strongly typed property<\/em>, I\nspecifically mean a strongly typed version of\n<code>public object GetProperty(string propertyName)<\/code>, where the property\nname is a constant (or <em>name<\/em>) of some sort, and the return type is\nproperty specific, so that no type casting is required at the call site.\nFurthermore, I wanted the properties to be derived from other properties\non-demand, but cached for subsequent access. This turned out to be\nnon-trivial in C#, and I&rsquo;ll explain why in a moment. But first, let me\nshow how I&rsquo;ve done it in Java several times before.<\/p>\n<h3>The Java version<\/h3>\n<p>Thanks to Java&rsquo;s <a href=\"http:\/\/docs.oracle.com\/javase\/1.5.0\/docs\/guide\/language\/generics.html\" title=\"Generics in Java\">generics<\/a>, and precisely because they are\nimplemented with <a href=\"http:\/\/docs.oracle.com\/javase\/tutorial\/java\/generics\/erasure.html\" title=\"Type erasure explained\">type erasure<\/a>, the solution is quite simple. First,\nwe need a generic interface for property classes to implement:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kd\">interface<\/span> <span class=\"nc\">Property<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">T<\/span><span class=\"w\"> <\/span><span class=\"nf\">get<\/span><span class=\"p\">(<\/span><span class=\"n\">PropertyContainer<\/span><span class=\"w\"> <\/span><span class=\"n\">container<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Next, by declaring a property-getting method that takes a generic\n<code>Class<\/code> parameter in our property container class, we can rely on the\ncompiler to infer the return type for us:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kd\">class<\/span> <span class=\"nc\">PropertyContainer<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"n\">T<\/span><span class=\"w\"> <\/span><span class=\"nf\">getProperty<\/span><span class=\"p\">(<\/span><span class=\"n\">Class<\/span><span class=\"o\">&lt;?<\/span><span class=\"w\"> <\/span><span class=\"kd\">extends<\/span><span class=\"w\"> <\/span><span class=\"n\">Property<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">clazz<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ ...<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>If you&rsquo;re unfamiliar with Java generics, the\n<code>Class&lt;? extends Property&lt;T&gt;&gt;<\/code> parameter type might be intimidating, but\nwhat it says is that the method accepts a <code>Class<\/code> instance whose generic\ntype argument is any class that implements the <code>Property<\/code> interface, and\nsince we specify <code>T<\/code> here, the compiler can just look at the type of the\npassed argument to determine what the return type must be. I&rsquo;ve left out\nthe <code>getProperty<\/code> implementation because it&rsquo;s not very relevant for the\ndiscussion, but it comes down to a map lookup using the class as the\nkey. Now, let&rsquo;s implement the following two properties, one of which is\nderived from the other:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kd\">class<\/span> <span class=\"nc\">RootProperty<\/span><span class=\"w\"> <\/span><span class=\"kd\">implements<\/span><span class=\"w\"> <\/span><span class=\"n\">Property<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Integer<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"n\">Integer<\/span><span class=\"w\"> <\/span><span class=\"nf\">get<\/span><span class=\"p\">(<\/span><span class=\"n\">PropertyContainer<\/span><span class=\"w\"> <\/span><span class=\"n\">container<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"mi\">42<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kd\">class<\/span> <span class=\"nc\">DerivedProperty<\/span><span class=\"w\"> <\/span><span class=\"kd\">implements<\/span><span class=\"w\"> <\/span><span class=\"n\">Property<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Double<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"n\">Double<\/span><span class=\"w\"> <\/span><span class=\"nf\">get<\/span><span class=\"p\">(<\/span><span class=\"n\">PropertyContainer<\/span><span class=\"w\"> <\/span><span class=\"n\">container<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">container<\/span><span class=\"p\">.<\/span><span class=\"na\">getProperty<\/span><span class=\"p\">(<\/span><span class=\"n\">RootProperty<\/span><span class=\"p\">.<\/span><span class=\"na\">class<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"w\"> <\/span><span class=\"mf\">3.14<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>&hellip;and you can see a call site already here in the <code>DerivedProperty<\/code>\nproperty. Neat, isn&rsquo;t it? We use the class of the <code>RootProperty<\/code>\nproperty as our &ldquo;constant&rdquo;, and no type cast is needed to be able to\nmultiply the property value with a <code>double<\/code> value, which proves that the\ncompiler has inferred the return type properly!<\/p>\n<p>Moving on to C#, the starting point&hellip;<\/p>\n<h3>The C# version<\/h3>\n<p>Ok, so how to achieve the same thing in C#? Well, it&rsquo;s a bit harder!\nAnd actually, that&rsquo;s because of how C# implements <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/512aeb7t%28v=vs.100%29.aspx\" title=\"Generics in C#\">generics<\/a>, which\nironically is considered to be an improvement compared to Java&rsquo;s version\nsince type information is retained during runtime. Let&rsquo;s see how generic\nclasses compare in the different languages:<\/p>\n<table style=\"border:1px solid black\">\n    <caption>Generic class comparison in Java vs. C#<\/caption>\n    <thead>\n        <tr>\n            <th>Language<\/th>\n            <th>Expression<\/th>\n            <th>Result<\/th>\n        <\/tr>\n    <\/thead>\n    <tbody>\n        <tr>\n            <td>Java<\/td>\n            <td><code>ArrayList&lt;String>.class == ArrayList&lt;Integer>.class<\/code><\/td>\n            <td><b>true<\/b><\/td>\n        <\/tr>\n        <tr>\n            <td>C\\#<\/td>\n            <td><code>typeof(List&lt;string>) == typeof(List&lt;int>)<\/code><\/td>\n            <td><b>false<\/b><\/td>\n        <\/tr>\n    <\/tbody>\n<\/table>\n\n<p>Opposites! In C#, the two types are different specializations of the\ngeneric <code>List<\/code> class. In Java, the two types resolve to the non-generic\n<code>ArrayList<\/code> class at runtime.<\/p>\n<p>Unlike Java&rsquo;s <code>Class<\/code> class, C#&lsquo;s <code>Type<\/code> class doesn&rsquo;t have any generic\nversion. I suppose one reason is that reflection would be pretty painful\nif it did. Thus, there is no way to pass a class to a property-getting\nmethod and have the C# compiler infer the return type. You might be\ntempted to do something similar to the Java version:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">IProperty<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">T<\/span><span class=\"w\"> <\/span><span class=\"nf\">Get<\/span><span class=\"p\">(<\/span><span class=\"n\">PropertyContainer<\/span><span class=\"w\"> <\/span><span class=\"n\">container<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>&hellip;and then expect to be able to declare a property-getting method that\nallows you to make a call like <code>container.GetProperty()<\/code>. But to do so\nturns out to be difficult:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">PropertyContainer<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"o\">???<\/span><span class=\"w\"> <\/span><span class=\"n\">GetProperty<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"k\">where<\/span><span class=\"w\"> <\/span><span class=\"n\">T<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">IProperty<\/span><span class=\"o\">&lt;???&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/...<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Since <code>T<\/code> is the type of the property itself, we need another generic\ntype parameter to get to the return type:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">PropertyContainer<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"n\">U<\/span><span class=\"w\"> <\/span><span class=\"n\">GetProperty<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">U<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"k\">where<\/span><span class=\"w\"> <\/span><span class=\"n\">T<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">IProperty<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">U<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/...<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>But all of a sudden, the call site is not so neat anymore, because both\ntypes must be specified:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">container<\/span><span class=\"p\">.<\/span><span class=\"n\">GetProperty<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">SomeProperty<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">ReturnType<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">();<\/span>\n<\/code><\/pre><\/div>\n\n<p>This bugged me for a while, until I finally realized that the solution\nis to let the property-getting method take a <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ms173171%28v=vs.100%29.aspx\">function delegate<\/a>, and\npass in a <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/bb308966.aspx#csharp3.0overview_topic9\">method group<\/a>! A method group is simply a method name,\nmeaning that there may be multiple overloaded methods in the group. But\nthe compiler will determine which method to use based on the delegate\nsignature. So, let&rsquo;s scrap the <code>IProperty<\/code> interface and declare the\nmethod as follows:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">PropertyContainer<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"n\">T<\/span><span class=\"w\"> <\/span><span class=\"nf\">GetProperty<\/span><span class=\"p\">(<\/span><span class=\"n\">Func<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">PropertyContainer<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">getter<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/...<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>So the method accepts a delegate, or a function, that takes a\n<code>PropertyContainer<\/code> instance as argument and returns a value of some\narbitrary type <code>T<\/code>. This is equivalent to the <code>Get<\/code> method of the\nnow-scrapped <code>IProperty<\/code> interface! (Again, I&rsquo;ve omitted the\nimplementation, but this time it&rsquo;s dictionary lookup with\n<code>getter.Method<\/code> as key.) We can now declare a number of properties as\nmethods:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">Properties<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"kt\">int<\/span><span class=\"w\"> <\/span><span class=\"nf\">RootProperty<\/span><span class=\"p\">(<\/span><span class=\"n\">PropertyContainer<\/span><span class=\"w\"> <\/span><span class=\"n\">container<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"m\">42<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"kt\">double<\/span><span class=\"w\"> <\/span><span class=\"nf\">DerivedProperty<\/span><span class=\"p\">(<\/span><span class=\"n\">PropertyContainer<\/span><span class=\"w\"> <\/span><span class=\"n\">container<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">container<\/span><span class=\"p\">.<\/span><span class=\"n\">GetProperty<\/span><span class=\"p\">(<\/span><span class=\"n\">RootProperty<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"w\"> <\/span><span class=\"m\">3.14<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>If you take a look at the call site in the <code>DerivedProperty<\/code> method, you\ncan see that we use the method group <code>RootProperty<\/code> as our property\nconstant, and there is no need to type cast the property value before\nmultiplying. In other words, the solution is pretty much identical to\nthe Java one but using a completely different mechanism. While we don&rsquo;t\nhave to type something like the &ldquo;.class&rdquo; suffix, we have to include the\nclass name to use a property outside of the <code>Properties<\/code> class:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">SomeMethod<\/span><span class=\"p\">(<\/span><span class=\"n\">PropertyContainer<\/span><span class=\"w\"> <\/span><span class=\"n\">container<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">Console<\/span><span class=\"p\">.<\/span><span class=\"n\">WriteLine<\/span><span class=\"p\">(<\/span><span class=\"n\">container<\/span><span class=\"p\">.<\/span><span class=\"n\">GetProperty<\/span><span class=\"p\">(<\/span><span class=\"n\">Properties<\/span><span class=\"p\">.<\/span><span class=\"n\">DerivedProperty<\/span><span class=\"p\">));<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>While C# doesn&rsquo;t have static imports like Java, it&rsquo;s possible to use an\n<a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/sf0df423(v=vs.100).aspx\">using alias<\/a> to shorten the class name a bit:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">using<\/span><span class=\"w\"> <\/span><span class=\"nn\">P<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">SomePackage<\/span><span class=\"p\">.<\/span><span class=\"n\">Properties<\/span><span class=\"p\">;<\/span>\n<span class=\"p\">...<\/span>\n\n<span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">SomeMethod<\/span><span class=\"p\">(<\/span><span class=\"n\">PropertyContainer<\/span><span class=\"w\"> <\/span><span class=\"n\">container<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">Console<\/span><span class=\"p\">.<\/span><span class=\"n\">WriteLine<\/span><span class=\"p\">(<\/span><span class=\"n\">container<\/span><span class=\"p\">.<\/span><span class=\"n\">GetProperty<\/span><span class=\"p\">(<\/span><span class=\"n\">P<\/span><span class=\"p\">.<\/span><span class=\"n\">DerivedProperty<\/span><span class=\"p\">));<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<h3>Some final words<\/h3>\n<\/p>\n<p>The two solutions are roughly equivalent from a <em>usage<\/em> perspective, in\nthe sense that both require no unnecessary glue code to work. I was very\nhappy when I found the C# method group solution, which IMHO is quite\nelegant! I hope you think so too!<\/p>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"delegate"}},{"@attributes":{"term":"generics"}},{"@attributes":{"term":"method group"}},{"@attributes":{"term":"csharp"}},{"@attributes":{"term":"java"}}]},{"title":"Generic extension method with multiple constraints","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/generic-extension-method-with-multiple-constraints.html","rel":"alternate"}},"published":"2012-01-18T13:47:00+01:00","updated":"2012-01-18T13:47:00+01:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2012-01-18:\/generic-extension-method-with-multiple-constraints.html","summary":"<p>In a .NET project, I was coding an extension method for <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.windows.forms.form.aspx\" title=\"Form class @ MSDN\">forms<\/a>, and\nfor various reasons I needed to call a form method which came from an\ninterface. Instead of coding an ugly type check and subsequent type\ncast, I was happy to discover that I could simply create a \u2026<\/p>","content":"<p>In a .NET project, I was coding an extension method for <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.windows.forms.form.aspx\" title=\"Form class @ MSDN\">forms<\/a>, and\nfor various reasons I needed to call a form method which came from an\ninterface. Instead of coding an ugly type check and subsequent type\ncast, I was happy to discover that I could simply create a generic\n<a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/bb384936.aspx\" title=\"Extension methods @ MSDN\">extension method<\/a> and constrain the generic type parameter to be a\nform <strong>and<\/strong> to implement my interface:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"na\">&lt;Extension()&gt;<\/span>\n<span class=\"k\">Public<\/span><span class=\"w\"> <\/span><span class=\"k\">Sub<\/span><span class=\"w\"> <\/span><span class=\"nf\">DoStuff<\/span><span class=\"p\">(<\/span><span class=\"k\">Of<\/span><span class=\"w\"> <\/span><span class=\"n\">T<\/span><span class=\"w\"> <\/span><span class=\"ow\">As<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"n\">Form<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">ISomeInterface<\/span><span class=\"p\">})(<\/span><span class=\"k\">ByVal<\/span><span class=\"w\"> <\/span><span class=\"n\">form<\/span><span class=\"w\"> <\/span><span class=\"ow\">As<\/span><span class=\"w\"> <\/span><span class=\"n\">T<\/span><span class=\"p\">)<\/span>\n<span class=\"k\">End<\/span><span class=\"w\"> <\/span><span class=\"k\">Sub<\/span>\n<\/code><\/pre><\/div>\n\n<p>No type casting means less code and less evil! Hooray!<\/p>\n<p>(If you wonder about the odd-looking code, it&rsquo;s because it&rsquo;s VB&hellip; ;-))<\/p>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"constraints"}},{"@attributes":{"term":"extension methods"}},{"@attributes":{"term":"generics"}}]},{"title":"Playing with Java annotation processing","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/playing-with-java-annotation-processing.html","rel":"alternate"}},"published":"2012-01-06T17:16:00+01:00","updated":"2012-01-06T17:16:00+01:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2012-01-06:\/playing-with-java-annotation-processing.html","summary":"<p>I found <a href=\"http:\/\/projectlombok.org\/\">Project Lombok<\/a> via a Tweet, and was intrigued when I saw\nthat a single annotation could trigger automatic code generation\ntransparently during compilation of a source file. How do they do that?<\/p>\n<p>Some digging lead me to discover Java&rsquo;s annotation processing API, and\nhow one can use \u2026<\/p>","content":"<p>I found <a href=\"http:\/\/projectlombok.org\/\">Project Lombok<\/a> via a Tweet, and was intrigued when I saw\nthat a single annotation could trigger automatic code generation\ntransparently during compilation of a source file. How do they do that?<\/p>\n<p>Some digging lead me to discover Java&rsquo;s annotation processing API, and\nhow one can use SPI (Service Provider Interfaces) to transparently\ninvoke an annotation processor during compilation. Here&rsquo;s how to do it:<\/p>\n<p>First, we create a simple annotation type (package declaration and\nimports omitted for brevity):<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nd\">@Retention<\/span><span class=\"p\">(<\/span><span class=\"n\">RetentionPolicy<\/span><span class=\"p\">.<\/span><span class=\"na\">SOURCE<\/span><span class=\"p\">)<\/span>\n<span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"nd\">@interface<\/span><span class=\"w\"> <\/span><span class=\"n\">PrintMe<\/span><span class=\"w\"> <\/span><span class=\"p\">{}<\/span>\n<\/code><\/pre><\/div>\n\n<p>With the <code>@Retention<\/code> annotation, we specify that we don&rsquo;t need the\nannotations of this type beyond compilation time, so the compiler can\ndiscard them.<\/p>\n<p>Next, we create an annotation processor that prints elements that are\nannotated using the <code>@PrintMe<\/code> annotation. We can inherit from the\n<code>AbstractProcessor<\/code> class. Using the <code>@SupportedAnnotationTypes<\/code>\nannotation, we specify which annotations we handle:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nd\">@SupportedAnnotationTypes<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">  <\/span><span class=\"p\">{<\/span><span class=\"s\">&quot;com.programmaticallyspeaking.aptdemo.PrintMe&quot;<\/span><span class=\"p\">}<\/span>\n<span class=\"p\">)<\/span>\n<span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kd\">class<\/span> <span class=\"nc\">AnnotationProcessor<\/span><span class=\"w\"> <\/span><span class=\"kd\">extends<\/span><span class=\"w\"> <\/span><span class=\"n\">AbstractProcessor<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<\/code><\/pre><\/div>\n\n<p>The main method to implement is <code>process<\/code>:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"w\">  <\/span><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kt\">boolean<\/span><span class=\"w\"> <\/span><span class=\"nf\">process<\/span><span class=\"p\">(<\/span><span class=\"n\">Set<\/span><span class=\"o\">&lt;?<\/span><span class=\"w\"> <\/span><span class=\"kd\">extends<\/span><span class=\"w\"> <\/span><span class=\"n\">TypeElement<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">annotations<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">                         <\/span><span class=\"n\">RoundEnvironment<\/span><span class=\"w\"> <\/span><span class=\"n\">env<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<\/code><\/pre><\/div>\n\n<p>We get hold of the current <code>Messager<\/code> instance to be able to print\nmessages:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"w\">    <\/span><span class=\"n\">Messager<\/span><span class=\"w\"> <\/span><span class=\"n\">messager<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">processingEnv<\/span><span class=\"p\">.<\/span><span class=\"na\">getMessager<\/span><span class=\"p\">();<\/span>\n<\/code><\/pre><\/div>\n\n<p>Then we iterate over the annotations (there is only one, so the code is\na bit more generic than it needs to be) and the elements that are\nannotated by them:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"w\">    <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">TypeElement<\/span><span class=\"w\"> <\/span><span class=\"n\">te<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">annotations<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">      <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">Element<\/span><span class=\"w\"> <\/span><span class=\"n\">e<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">env<\/span><span class=\"p\">.<\/span><span class=\"na\">getElementsAnnotatedWith<\/span><span class=\"p\">(<\/span><span class=\"n\">te<\/span><span class=\"p\">))<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<\/code><\/pre><\/div>\n\n<p>At this point, we can do a lot of interesting stuff, but for now let&rsquo;s\njust print each annotated element:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"w\">        <\/span><span class=\"n\">messager<\/span><span class=\"p\">.<\/span><span class=\"na\">printMessage<\/span><span class=\"p\">(<\/span><span class=\"n\">Diagnostic<\/span><span class=\"p\">.<\/span><span class=\"na\">Kind<\/span><span class=\"p\">.<\/span><span class=\"na\">NOTE<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">                              <\/span><span class=\"s\">&quot;Printing: &quot;<\/span><span class=\"w\"> <\/span><span class=\"o\">+<\/span><span class=\"w\"> <\/span><span class=\"n\">e<\/span><span class=\"p\">.<\/span><span class=\"na\">toString<\/span><span class=\"p\">());<\/span>\n<\/code><\/pre><\/div>\n\n<p>Finally, we wrap up and return <code>true<\/code> to claim the handled annotations\nso that no other annotation processor can use them:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"w\">      <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"kc\">true<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">  <\/span><span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>To avoid a warning about source version when the annotation processor is\nrun, we specify that we handle the latest source version that the\ncurrent execution environment supports:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"w\">  <\/span><span class=\"nd\">@Override<\/span>\n<span class=\"w\">  <\/span><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"n\">SourceVersion<\/span><span class=\"w\"> <\/span><span class=\"nf\">getSupportedSourceVersion<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">SourceVersion<\/span><span class=\"p\">.<\/span><span class=\"na\">latestSupported<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">  <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>And that&rsquo;s it for the annotation processor. Next, we need to specify\nwhere the annotation processor resides using SPI. We do this by creating\na file called <em>javax.annotation.processing.Processor<\/em> in the\n<em>META-INF\/services<\/em> directory. The contents of the file should be:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>com.programmaticallyspeaking.aptdemo.AnnotationProcessor\n<\/code><\/pre><\/div>\n\n<p>Also, Maven&rsquo;s compiler plugin needs some configuration. First to\nincrease the source and target levels and second to disable annotation\nprocessing (as the plugin gets mighty confused by our SPI file):<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nt\">&lt;plugin&gt;<\/span>\n<span class=\"w\">  <\/span><span class=\"nt\">&lt;artifactId&gt;<\/span>maven-compiler-plugin<span class=\"nt\">&lt;\/artifactId&gt;<\/span>\n<span class=\"w\">  <\/span><span class=\"nt\">&lt;version&gt;<\/span>2.3.2<span class=\"nt\">&lt;\/version&gt;<\/span>\n<span class=\"w\">  <\/span><span class=\"nt\">&lt;configuration&gt;<\/span>\n<span class=\"w\">    <\/span><span class=\"nt\">&lt;source&gt;<\/span>1.6<span class=\"nt\">&lt;\/source&gt;<\/span>\n<span class=\"w\">    <\/span><span class=\"nt\">&lt;target&gt;<\/span>1.6<span class=\"nt\">&lt;\/target&gt;<\/span>\n<span class=\"w\">    <\/span><span class=\"cm\">&lt;!-- Disable annotation processing for ourselves. --&gt;<\/span>\n<span class=\"w\">    <\/span><span class=\"nt\">&lt;compilerArgument&gt;<\/span>-proc:none<span class=\"nt\">&lt;\/compilerArgument&gt;<\/span>\n<span class=\"w\">  <\/span><span class=\"nt\">&lt;\/configuration&gt;<\/span>\n<span class=\"nt\">&lt;\/plugin&gt;<\/span>\n<\/code><\/pre><\/div>\n\n<p>The projects in its entirety can be fetched from <a href=\"https:\/\/github.com\/provegard\/aptdemo\" title=\"aptdemo @ GitHub\">GitHub<\/a>.<\/p>\n<p>Building the project should result in a file <em>aptdemo-1.0-SNAPSHOT.jar<\/em>.\nSay that we have the following test source file:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kn\">import<\/span><span class=\"w\"> <\/span><span class=\"nn\">com.programmaticallyspeaking.aptdemo.PrintMe<\/span><span class=\"p\">;<\/span>\n\n<span class=\"nd\">@PrintMe<\/span>\n<span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kd\">class<\/span> <span class=\"nc\">Test<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">  <\/span><span class=\"nd\">@PrintMe<\/span>\n<span class=\"w\">  <\/span><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kd\">static<\/span><span class=\"w\"> <\/span><span class=\"kt\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">a1<\/span><span class=\"p\">(<\/span><span class=\"kt\">int<\/span><span class=\"w\"> <\/span><span class=\"n\">x<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">  <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">  <\/span><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kd\">static<\/span><span class=\"w\"> <\/span><span class=\"kt\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">a2<\/span><span class=\"p\">(<\/span><span class=\"n\">String<\/span><span class=\"o\">[]<\/span><span class=\"w\"> <\/span><span class=\"n\">arr<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">  <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Compiling it with the aptdemo JAR on the classpath should result in:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>javac<span class=\"w\"> <\/span>-cp<span class=\"w\"> <\/span>target\/apt-demo-1.0-SNAPSHOT.jar<span class=\"w\"> <\/span>Test.java\nNote:<span class=\"w\"> <\/span>Printing:<span class=\"w\"> <\/span>Test\nNote:<span class=\"w\"> <\/span>Printing:<span class=\"w\"> <\/span>a1<span class=\"o\">(<\/span>int<span class=\"o\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>Note that no compilation flags for annotation processing are needed.\nIt&rsquo;s completely transparent! Note also that the <code>a2<\/code> method, which is\nnot annotated, is not printed during compilation.<\/p>\n<p>That&rsquo;s all for now! Happy annotation processing! :-)<\/p>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"annotations"}},{"@attributes":{"term":"apt"}},{"@attributes":{"term":"Java"}},{"@attributes":{"term":"spi"}}]},{"title":"Adventures in updating hard drive firmware","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/adventures-in-updating-hard-drive-firmware.html","rel":"alternate"}},"published":"2012-01-06T12:14:00+01:00","updated":"2012-01-06T12:14:00+01:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2012-01-06:\/adventures-in-updating-hard-drive-firmware.html","summary":"<p>I decided to update the firmware of two of my hard drives. The drives in\nquestion are both Seagate Barracuda 7200.11, model ST3500320AS, and\nsmartctl gave me the following warning:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>==&gt; WARNING: There are known problems with these drives,\nsee the following Seagate web pages:\n\nhttp:\/\/seagate.custkb.com\/seagate \u2026<\/code><\/pre><\/div>","content":"<p>I decided to update the firmware of two of my hard drives. The drives in\nquestion are both Seagate Barracuda 7200.11, model ST3500320AS, and\nsmartctl gave me the following warning:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>==&gt; WARNING: There are known problems with these drives,\nsee the following Seagate web pages:\n\nhttp:\/\/seagate.custkb.com\/seagate\/crm\/selfservice\/search.jsp?DocId=207931\nhttp:\/\/seagate.custkb.com\/seagate\/crm\/selfservice\/search.jsp?DocId=207951\nhttp:\/\/seagate.custkb.com\/seagate\/crm\/selfservice\/search.jsp?DocId=207957\n<\/code><\/pre><\/div>\n\n<p>For one of the drives (with firmware SD15, the other had SD04), the\nwarning included &ldquo;AND THIS FIRMWARE VERSION IS AFFECTED&rdquo;!<\/p>\n<p>Updating the firmware of anything is non-trivial on a non-Windows\nsystem, but luckily Seagate provides <a href=\"http:\/\/seagate.custkb.com\/seagate\/crm\/selfservice\/search.jsp?DocId=207951\">bootable ISO images<\/a> for such\nsystems. Problem with my server is that it doesn&rsquo;t have a DVD drive,\nthough.<\/p>\n<p>Extracting the files from the ISO image wasn&rsquo;t helpful. There are two\nfiles. One is README.TXT, which refers to a non-existent flash.bat file,\nand the other is DriveDetect.exe, a Windows application for detecting\nhard drives. But booting the image in a virtual machine reveals that\nthere is indeed a flash utility lurking in there!<\/p>\n<p>So how to boot the ISO on a server without a DVD drive? Enter my trusty\nbootable USB stick, which was created using <a href=\"http:\/\/www.pendrivelinux.com\">MultiBootISOs USB\nCreator<\/a>. The USB stick uses Grub to boot various ISOs. Inspecting\nmenu.lst revealed that different ISOs are launched using slightly\ndifferent boot entries. My first attempt was to use the variant below,\nand it was successful!<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>title Seagate Firmware Update\n    find --set-root \/MooseDT-SD1A-2D-8-16-32MB.ISO\n    map --mem \/MooseDT-SD1A-2D-8-16-32MB.ISO (hd32)\n    map --hookroot (hd32)\n    chainloader (hd32)\n<\/code><\/pre><\/div>\n\n<p>After booting, I was greeted with the following screen:<\/p>\n<p><img alt=\"Seagate flash utility screenshot\" src=\".\/images\/seagate_flash.jpg\" title=\"Screenshot from Seagate's firmware flash utility\" \/><\/p>\n<p>Here, I pressed <strong>S<\/strong> to scan for devices, to ensure that both hard\ndrives were detected correctly. They were! I then pressed <strong>A<\/strong> to\nupdate the firmware. My plan was to update the firmware for only one of\nthe drives first and then boot the system to verify that the update\ndidn&rsquo;t brick the drive. Why? Well, the drives are part of a RAID5 array,\nso I could afford losing one of them but not both. But the flash utility\ndidn&rsquo;t give me a choice - it happily went about to update both drives!\nSo all I could do was to hold my breath and hope that everything worked\nout (my mind jumped back to the time I bricked an Asus P5B motherboard\nduring a BIOS update and I had to re-flash it using <a href=\"http:\/\/bios-repair.co.uk\/SPI-ISP\/spiflash.html\">SPI<\/a>).<\/p>\n<p>After a power cycle, the server booted without problem, and both drives\nwere working perfectly fine with the new SD1A firmware!<\/p>","category":[{"@attributes":{"term":"Sysadmin"}},{"@attributes":{"term":"boot"}},{"@attributes":{"term":"firmware"}},{"@attributes":{"term":"iso"}},{"@attributes":{"term":"linux"}}]},{"title":"Generator combined with with\/using statement - Python vs C#","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/generator-combined-with-withusing-statement-python-vs-c.html","rel":"alternate"}},"published":"2011-12-30T02:07:00+01:00","updated":"2011-12-30T02:07:00+01:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2011-12-30:\/generator-combined-with-withusing-statement-python-vs-c.html","summary":"<p>The other day, I tried to return a generator expression from within a\n<code>with<\/code> statement in Python, like so:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"ch\">#!\/usr\/bin\/python<\/span>\n\n<span class=\"k\">def<\/span> <span class=\"nf\">readlines<\/span><span class=\"p\">(<\/span><span class=\"n\">fn<\/span><span class=\"p\">):<\/span>\n    <span class=\"k\">with<\/span> <span class=\"nb\">open<\/span><span class=\"p\">(<\/span><span class=\"n\">fn<\/span><span class=\"p\">)<\/span> <span class=\"k\">as<\/span> <span class=\"n\">fd<\/span><span class=\"p\">:<\/span> <span class=\"c1\"># &lt;-- the with statement<\/span>\n        <span class=\"k\">return<\/span> <span class=\"p\">(<\/span><span class=\"n\">line<\/span> <span class=\"k\">for<\/span> <span class=\"n\">line<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">fd<\/span><span class=\"p\">)<\/span> <span class=\"c1\"># &lt;-- the generator expression<\/span>\n\n<span class=\"k\">if<\/span> <span class=\"vm\">__name__<\/span> <span class=\"o\">==<\/span> <span class=\"s2\">&quot;__main__&quot;<\/span><span class=\"p\">:<\/span>\n    <span class=\"k\">for<\/span> <span class=\"n\">line<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">readlines<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;\/proc \u2026<\/span><\/code><\/pre><\/div>","content":"<p>The other day, I tried to return a generator expression from within a\n<code>with<\/code> statement in Python, like so:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"ch\">#!\/usr\/bin\/python<\/span>\n\n<span class=\"k\">def<\/span> <span class=\"nf\">readlines<\/span><span class=\"p\">(<\/span><span class=\"n\">fn<\/span><span class=\"p\">):<\/span>\n    <span class=\"k\">with<\/span> <span class=\"nb\">open<\/span><span class=\"p\">(<\/span><span class=\"n\">fn<\/span><span class=\"p\">)<\/span> <span class=\"k\">as<\/span> <span class=\"n\">fd<\/span><span class=\"p\">:<\/span> <span class=\"c1\"># &lt;-- the with statement<\/span>\n        <span class=\"k\">return<\/span> <span class=\"p\">(<\/span><span class=\"n\">line<\/span> <span class=\"k\">for<\/span> <span class=\"n\">line<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">fd<\/span><span class=\"p\">)<\/span> <span class=\"c1\"># &lt;-- the generator expression<\/span>\n\n<span class=\"k\">if<\/span> <span class=\"vm\">__name__<\/span> <span class=\"o\">==<\/span> <span class=\"s2\">&quot;__main__&quot;<\/span><span class=\"p\">:<\/span>\n    <span class=\"k\">for<\/span> <span class=\"n\">line<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">readlines<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;\/proc\/partitions&quot;<\/span><span class=\"p\">):<\/span>\n        <span class=\"nb\">print<\/span> <span class=\"n\">line<\/span><span class=\"o\">.<\/span><span class=\"n\">strip<\/span><span class=\"p\">()<\/span>\n<\/code><\/pre><\/div>\n\n<p>Running the script above results in a nasty error:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>.\/genwith.py\nTraceback<span class=\"w\"> <\/span><span class=\"o\">(<\/span>most<span class=\"w\"> <\/span>recent<span class=\"w\"> <\/span>call<span class=\"w\"> <\/span>last<span class=\"o\">)<\/span>:\n<span class=\"w\">  <\/span>File<span class=\"w\"> <\/span><span class=\"s2\">&quot;.\/genwith.py&quot;<\/span>,<span class=\"w\"> <\/span>line<span class=\"w\"> <\/span><span class=\"m\">8<\/span>,<span class=\"w\"> <\/span><span class=\"k\">in<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span>line<span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span>readlines<span class=\"o\">(<\/span><span class=\"s2\">&quot;\/proc\/partitions&quot;<\/span><span class=\"o\">)<\/span>:\n<span class=\"w\">  <\/span>File<span class=\"w\"> <\/span><span class=\"s2\">&quot;.\/genwith.py&quot;<\/span>,<span class=\"w\"> <\/span>line<span class=\"w\"> <\/span><span class=\"m\">5<\/span>,<span class=\"w\"> <\/span><span class=\"k\">in<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"o\">(<\/span>line<span class=\"w\"> <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span>line<span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span>fd<span class=\"o\">)<\/span>\nValueError:<span class=\"w\"> <\/span>I\/O<span class=\"w\"> <\/span>operation<span class=\"w\"> <\/span>on<span class=\"w\"> <\/span>closed<span class=\"w\"> <\/span>file\n<\/code><\/pre><\/div>\n\n<p>I wanted to see how the same combination of mechanisms works in C#\n(which has <code>using<\/code> instead of <code>with<\/code>):<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">using<\/span><span class=\"w\"> <\/span><span class=\"nn\">System<\/span><span class=\"p\">;<\/span>\n<span class=\"k\">using<\/span><span class=\"w\"> <\/span><span class=\"nn\">System.IO<\/span><span class=\"p\">;<\/span>\n<span class=\"k\">using<\/span><span class=\"w\"> <\/span><span class=\"nn\">System.Collections.Generic<\/span><span class=\"p\">;<\/span>\n\n<span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">Program<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">private<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"n\">IEnumerable<\/span><span class=\"w\"> <\/span><span class=\"nf\">ReadLines<\/span><span class=\"p\">(<\/span><span class=\"kt\">string<\/span><span class=\"w\"> <\/span><span class=\"n\">fn<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">using<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">reader<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">StreamReader<\/span><span class=\"p\">(<\/span><span class=\"n\">fn<\/span><span class=\"p\">))<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"c1\">\/\/ &lt;-- the using statement<\/span>\n<span class=\"w\">            <\/span><span class=\"kt\">string<\/span><span class=\"w\"> <\/span><span class=\"n\">line<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">            <\/span><span class=\"k\">while<\/span><span class=\"w\"> <\/span><span class=\"p\">((<\/span><span class=\"n\">line<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">reader<\/span><span class=\"p\">.<\/span><span class=\"n\">ReadLine<\/span><span class=\"p\">())<\/span><span class=\"w\"> <\/span><span class=\"o\">!=<\/span><span class=\"w\"> <\/span><span class=\"k\">null<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">                <\/span><span class=\"k\">yield<\/span><span class=\"w\"> <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">line<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"c1\">\/\/ &lt;-- makes ReadLines a generator method<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">public<\/span><span class=\"w\"> <\/span><span class=\"k\">static<\/span><span class=\"w\"> <\/span><span class=\"k\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">Main<\/span><span class=\"p\">(<\/span><span class=\"kt\">string<\/span><span class=\"p\">[]<\/span><span class=\"w\"> <\/span><span class=\"n\">args<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">foreach<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"kt\">var<\/span><span class=\"w\"> <\/span><span class=\"n\">line<\/span><span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"n\">ReadLines<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;\/proc\/partitions&quot;<\/span><span class=\"p\">))<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">Console<\/span><span class=\"p\">.<\/span><span class=\"n\">WriteLine<\/span><span class=\"p\">(<\/span><span class=\"n\">line<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>And this actually works very well:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>dmcs<span class=\"w\"> <\/span>genuse.cs\n$<span class=\"w\"> <\/span>.\/genuse.exe\nmajor<span class=\"w\"> <\/span>minor<span class=\"w\">  <\/span><span class=\"c1\">#blocks  name<\/span>\n\n<span class=\"w\">   <\/span><span class=\"m\">8<\/span><span class=\"w\">        <\/span><span class=\"m\">0<\/span><span class=\"w\">   <\/span><span class=\"m\">20971520<\/span><span class=\"w\"> <\/span>sda...\n<\/code><\/pre><\/div>\n\n<p>But to be fair, the C# code doesn&rsquo;t use a generator expression - it\nuses the <code>yield<\/code> statement which converts the entire <code>ReadLines<\/code> method\ninto a generator. So it&rsquo;s not an adequate comparison at all! Let&rsquo;s go\nback to Python and use <code>yield<\/code> there as well:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"ch\">#!\/usr\/bin\/python<\/span>\n\n<span class=\"k\">def<\/span> <span class=\"nf\">readlines<\/span><span class=\"p\">(<\/span><span class=\"n\">fn<\/span><span class=\"p\">):<\/span>\n    <span class=\"k\">with<\/span> <span class=\"nb\">open<\/span><span class=\"p\">(<\/span><span class=\"n\">fn<\/span><span class=\"p\">)<\/span> <span class=\"k\">as<\/span> <span class=\"n\">fd<\/span><span class=\"p\">:<\/span> <span class=\"c1\"># &lt;-- the with statement<\/span>\n        <span class=\"k\">for<\/span> <span class=\"n\">line<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">fd<\/span><span class=\"p\">:<\/span>\n            <span class=\"k\">yield<\/span> <span class=\"n\">line<\/span> <span class=\"c1\"># &lt;-- makes readlines a generator function<\/span>\n\n<span class=\"k\">if<\/span> <span class=\"vm\">__name__<\/span> <span class=\"o\">==<\/span> <span class=\"s2\">&quot;__main__&quot;<\/span><span class=\"p\">:<\/span>\n    <span class=\"k\">for<\/span> <span class=\"n\">line<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">readlines<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;\/proc\/partitions&quot;<\/span><span class=\"p\">):<\/span>\n        <span class=\"nb\">print<\/span> <span class=\"n\">line<\/span><span class=\"o\">.<\/span><span class=\"n\">strip<\/span><span class=\"p\">()<\/span>\n<\/code><\/pre><\/div>\n\n<p>&hellip;and now the result is much better:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>.\/genwith.py\nmajor<span class=\"w\"> <\/span>minor<span class=\"w\">  <\/span><span class=\"c1\">#blocks  name<\/span>\n\n<span class=\"w\">   <\/span><span class=\"m\">8<\/span><span class=\"w\">        <\/span><span class=\"m\">0<\/span><span class=\"w\">   <\/span><span class=\"m\">20971520<\/span><span class=\"w\"> <\/span>sda...\n<\/code><\/pre><\/div>\n\n<p>Lesson learned: Use generator expressions with caution and use <code>yield<\/code>\nwhen a context manager (which is what the <code>with<\/code> statement uses) is\ninvolved.<\/p>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"c#"}},{"@attributes":{"term":"generator"}},{"@attributes":{"term":"Python"}}]},{"title":"Certificate error when upgrading to Oneric","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/certificate-error-when-upgrading-to-oneric.html","rel":"alternate"}},"published":"2011-12-30T01:33:00+01:00","updated":"2011-12-30T01:33:00+01:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2011-12-30:\/certificate-error-when-upgrading-to-oneric.html","summary":"<p>Just updated one of my Ubuntu servers to Oneric, and I noticed some\nerror messages during the installation:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>error adding \/etc\/ssl\/certs\/brasil.gov.br.pem\nerror adding \/etc\/ssl\/certs\/cacert.org.pem\nerror adding \/etc\/ssl\/certs\/ca.pem\n...\n<\/code><\/pre><\/div>\n\n<p>I found a solution in this <a href=\"http:\/\/ubuntuforums.org\/showpost.php?p=11383381&amp;postcount=18\">forum post \u2026<\/a><\/p>","content":"<p>Just updated one of my Ubuntu servers to Oneric, and I noticed some\nerror messages during the installation:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>error adding \/etc\/ssl\/certs\/brasil.gov.br.pem\nerror adding \/etc\/ssl\/certs\/cacert.org.pem\nerror adding \/etc\/ssl\/certs\/ca.pem\n...\n<\/code><\/pre><\/div>\n\n<p>I found a solution in this <a href=\"http:\/\/ubuntuforums.org\/showpost.php?p=11383381&amp;postcount=18\">forum post<\/a>:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>sudo<span class=\"w\"> <\/span>dpkg-reconfigure<span class=\"w\"> <\/span>ca-certificates\n<\/code><\/pre><\/div>\n\n<p>&hellip;and select all certificates in the dialog.<\/p>\n<p>(To be honest, I don&rsquo;t know if the error actually caused any problem for\nme, but it&rsquo;s nice to have preempted any problems now that I have the\nerror messages fresh in mind.)<\/p>","category":[{"@attributes":{"term":"Sysadmin"}},{"@attributes":{"term":"oneric"}},{"@attributes":{"term":"ubuntu"}}]},{"title":"Getting network interfaces in Python","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/getting-network-interfaces-in-python.html","rel":"alternate"}},"published":"2011-12-30T00:50:00+01:00","updated":"2011-12-30T00:50:00+01:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2011-12-30:\/getting-network-interfaces-in-python.html","summary":"<p>Here&rsquo;s a small Python script\/module I put together to list all network\ninterfaces on the current server (tested on Linux only!) in a format\nthat easily lets me convert between name, index and address of an\ninterface.<\/p>\n<p>The code is based on <a href=\"http:\/\/code.google.com\/p\/pydlnadms\/source\/browse\/getifaddrs.py\">getifaddrs.py<\/a> from <a href=\"http:\/\/code.google.com\/p\/pydlnadms\/\">pydlnadms<\/a>, but I \u2026<\/p>","content":"<p>Here&rsquo;s a small Python script\/module I put together to list all network\ninterfaces on the current server (tested on Linux only!) in a format\nthat easily lets me convert between name, index and address of an\ninterface.<\/p>\n<p>The code is based on <a href=\"http:\/\/code.google.com\/p\/pydlnadms\/source\/browse\/getifaddrs.py\">getifaddrs.py<\/a> from <a href=\"http:\/\/code.google.com\/p\/pydlnadms\/\">pydlnadms<\/a>, but I have\nrefactored it a tiny bit and removed stuff I didn&rsquo;t need.<\/p>\n<div class=\"gist\">\n    <script src='https:\/\/gist.github.com\/1536682.js?file=getnifs.py'><\/script>\n    <noscript>\n        <pre><code>#!\/usr\/bin\/python\n\n# Based on getifaddrs.py from pydlnadms [http:\/\/code.google.com\/p\/pydlnadms\/].\n# Only tested on Linux!\n\nfrom socket import AF_INET, AF_INET6, inet_ntop\nfrom ctypes import (\n    Structure, Union, POINTER,\n    pointer, get_errno, cast,\n    c_ushort, c_byte, c_void_p, c_char_p, c_uint, c_int, c_uint16, c_uint32\n)\nimport ctypes.util\nimport ctypes\n\nclass struct_sockaddr(Structure):\n    _fields_ = [\n        ('sa_family', c_ushort),\n        ('sa_data', c_byte * 14),]\n\nclass struct_sockaddr_in(Structure):\n    _fields_ = [\n        ('sin_family', c_ushort),\n        ('sin_port', c_uint16),\n        ('sin_addr', c_byte * 4)]\n\nclass struct_sockaddr_in6(Structure):\n    _fields_ = [\n        ('sin6_family', c_ushort),\n        ('sin6_port', c_uint16),\n        ('sin6_flowinfo', c_uint32),\n        ('sin6_addr', c_byte * 16),\n        ('sin6_scope_id', c_uint32)]\n\nclass union_ifa_ifu(Union):\n    _fields_ = [\n        ('ifu_broadaddr', POINTER(struct_sockaddr)),\n        ('ifu_dstaddr', POINTER(struct_sockaddr)),]\n\nclass struct_ifaddrs(Structure):\n    pass\nstruct_ifaddrs._fields_ = [\n    ('ifa_next', POINTER(struct_ifaddrs)),\n    ('ifa_name', c_char_p),\n    ('ifa_flags', c_uint),\n    ('ifa_addr', POINTER(struct_sockaddr)),\n    ('ifa_netmask', POINTER(struct_sockaddr)),\n    ('ifa_ifu', union_ifa_ifu),\n    ('ifa_data', c_void_p),]\n\nlibc = ctypes.CDLL(ctypes.util.find_library('c'))\n\ndef ifap_iter(ifap):\n    ifa = ifap.contents\n    while True:\n        yield ifa\n        if not ifa.ifa_next:\n            break\n        ifa = ifa.ifa_next.contents\n\ndef getfamaddr(sa):\n    family = sa.sa_family\n    addr = None\n    if family == AF_INET:\n        sa = cast(pointer(sa), POINTER(struct_sockaddr_in)).contents\n        addr = inet_ntop(family, sa.sin_addr)\n    elif family == AF_INET6:\n        sa = cast(pointer(sa), POINTER(struct_sockaddr_in6)).contents\n        addr = inet_ntop(family, sa.sin6_addr)\n    return family, addr\n\nclass NetworkInterface(object):\n    def __init__(self, name):\n        self.name = name\n        self.index = libc.if_nametoindex(name)\n        self.addresses = {}\n\n    def __str__(self):\n        return \"%s [index=%d, IPv4=%s, IPv6=%s]\" % (\n            self.name, self.index,\n            self.addresses.get(AF_INET),\n            self.addresses.get(AF_INET6))\n\ndef get_network_interfaces():\n    ifap = POINTER(struct_ifaddrs)()\n    result = libc.getifaddrs(pointer(ifap))\n    if result != 0:\n        raise OSError(get_errno())\n    del result\n    try:\n        retval = {}\n        for ifa in ifap_iter(ifap):\n            name = ifa.ifa_name\n            i = retval.get(name)\n            if not i:\n                i = retval[name] = NetworkInterface(name)\n            family, addr = getfamaddr(ifa.ifa_addr.contents)\n            if addr:\n                i.addresses[family] = addr\n        return retval.values()\n    finally:\n        libc.freeifaddrs(ifap)\n\nif __name__ == '__main__':\n    print [str(ni) for ni in get_network_interfaces()]\n<\/code><\/pre>\n    <\/noscript>\n<\/div>\n<p>With this module, I can write things like:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"gp\">&gt;&gt;&gt; <\/span><span class=\"kn\">import<\/span> <span class=\"nn\">socket<\/span>\n<span class=\"gp\">&gt;&gt;&gt; <\/span><span class=\"kn\">import<\/span> <span class=\"nn\">getnifs<\/span>\n<span class=\"gp\">&gt;&gt;&gt; <\/span><span class=\"n\">nifs<\/span> <span class=\"o\">=<\/span> <span class=\"n\">getnifs<\/span><span class=\"o\">.<\/span><span class=\"n\">get_network_interfaces<\/span><span class=\"p\">()<\/span>\n<span class=\"gp\">&gt;&gt;&gt; <\/span><span class=\"p\">[<\/span><span class=\"n\">ni<\/span><span class=\"o\">.<\/span><span class=\"n\">index<\/span> <span class=\"k\">for<\/span> <span class=\"n\">ni<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">nifs<\/span> <span class=\"k\">if<\/span> <span class=\"n\">ni<\/span><span class=\"o\">.<\/span><span class=\"n\">name<\/span> <span class=\"o\">==<\/span> <span class=\"s1\">&#39;eth0&#39;<\/span><span class=\"p\">][<\/span><span class=\"mi\">2<\/span><span class=\"p\">]<\/span>\n<span class=\"gp\">&gt;&gt;&gt; <\/span><span class=\"p\">[<\/span><span class=\"n\">ni<\/span><span class=\"o\">.<\/span><span class=\"n\">name<\/span> <span class=\"k\">for<\/span> <span class=\"n\">ni<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">nifs<\/span> <span class=\"k\">if<\/span> <span class=\"n\">ni<\/span><span class=\"o\">.<\/span><span class=\"n\">index<\/span> <span class=\"o\">==<\/span> <span class=\"mi\">1<\/span><span class=\"p\">][<\/span><span class=\"s1\">&#39;lo&#39;<\/span><span class=\"p\">]<\/span>\n<span class=\"gp\">&gt;&gt;&gt; <\/span><span class=\"p\">[<\/span><span class=\"n\">ni<\/span><span class=\"o\">.<\/span><span class=\"n\">name<\/span> <span class=\"k\">for<\/span> <span class=\"n\">ni<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">nifs<\/span> <span class=\"k\">if<\/span> <span class=\"s1\">&#39;127.0.0.1&#39;<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">ni<\/span><span class=\"o\">.<\/span><span class=\"n\">addresses<\/span><span class=\"o\">.<\/span><span class=\"n\">values<\/span><span class=\"p\">()][<\/span><span class=\"s1\">&#39;lo&#39;<\/span><span class=\"p\">]<\/span>\n<\/code><\/pre><\/div>\n\n<p>&hellip;which is exactly what I was looking for!<\/p>","category":[{"@attributes":{"term":"Sysadmin"}},{"@attributes":{"term":"linux"}},{"@attributes":{"term":"network interfaces"}},{"@attributes":{"term":"Python"}}]},{"title":"New features in diskgraph","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/new-features-in-diskgraph.html","rel":"alternate"}},"published":"2011-12-29T19:34:00+01:00","updated":"2011-12-29T19:34:00+01:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2011-12-29:\/new-features-in-diskgraph.html","summary":"<p>I added some new features to <a href=\"https:\/\/programmaticallyspeaking.com\/presenting-diskgraph.html\">diskgraph<\/a>, and bumped the version to\n<a href=\"https:\/\/github.com\/provegard\/diskgraph\/tree\/diskgraph-1.1\" title=\"diskgraph 1.1 @ GitHub\">1.1<\/a>. New things:<\/p>\n<ul>\n<li>Graph nodes now have colors depending on their type.<\/li>\n<li>Nodes that represent free space are included in the graph. Only free\n    space &gt;= 5 MB is shown, though.<\/li>\n<li>Mounted file systems are shown in the \u2026<\/li><\/ul>","content":"<p>I added some new features to <a href=\"https:\/\/programmaticallyspeaking.com\/presenting-diskgraph.html\">diskgraph<\/a>, and bumped the version to\n<a href=\"https:\/\/github.com\/provegard\/diskgraph\/tree\/diskgraph-1.1\" title=\"diskgraph 1.1 @ GitHub\">1.1<\/a>. New things:<\/p>\n<ul>\n<li>Graph nodes now have colors depending on their type.<\/li>\n<li>Nodes that represent free space are included in the graph. Only free\n    space &gt;= 5 MB is shown, though.<\/li>\n<li>Mounted file systems are shown in the graph.<\/li>\n<\/ul>\n<p>Here&rsquo;s part of the generated PNG for my server:<\/p>\n<p><img alt=\"Part of PNG image generated by diskgraph 1.1.\" src=\".\/images\/diskgraph11-part.png\" title=\"diskgraph11-part\" \/><\/p>","category":[{"@attributes":{"term":"Tools"}},{"@attributes":{"term":"diskgraph"}},{"@attributes":{"term":"linux"}}]},{"title":"Presenting diskgraph","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/presenting-diskgraph.html","rel":"alternate"}},"published":"2011-12-28T02:33:00+01:00","updated":"2011-12-28T02:33:00+01:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2011-12-28:\/presenting-diskgraph.html","summary":"<p>My server case is full of disks, and many of them are pretty small, like\n250 GB. I would like to upgrade the boot disk from a USB stick to a\nproper SSD disk, but that requires me to replace a number of the smaller\ndisks with something bigger. To \u2026<\/p>","content":"<p>My server case is full of disks, and many of them are pretty small, like\n250 GB. I would like to upgrade the boot disk from a USB stick to a\nproper SSD disk, but that requires me to replace a number of the smaller\ndisks with something bigger. To be able to do that, I need to know what\npurpose each of the disks serve. While this is pretty easy to do by\nchecking <em>\/proc\/mdstat<\/em> and running various LVM commands, it would be\nnicer if I could get a graph that shows what all disks are for.<\/p>\n<p>Enter <a href=\"https:\/\/github.com\/provegard\/diskgraph\" title=\"Diskgraph @ github\">diskgraph<\/a>!<\/p>\n<p>When run, diskgraph produces a PNG file that contains a graph of disks,\npartitions, RAID arrays and LVM entities (physical volumes, volume\ngroups and logical volumes). Part of the graph for my server looks like\nthis:<\/p>\n<p><img alt=\"image\" src=\".\/images\/diskgraph-part.png\" title=\"diskgraph-part\" \/><\/p>\n<p>The graph is created using <a href=\"http:\/\/code.google.com\/p\/pydot\/\">pydot<\/a>. I will probably add some features\nin the near future:<\/p>\n<ul>\n<li>Graph colors to distinguish entities of different type.<\/li>\n<li>Nodes that show free space in, for example, LVM volume groups.<\/li>\n<\/ul>\n<p>Let me know what you think!<\/p>","category":[{"@attributes":{"term":"Tools"}},{"@attributes":{"term":"diskgraph"}},{"@attributes":{"term":"linux"}}]},{"title":"Mocking iteration over file in Python","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/mocking-iteration-over-file-in-python.html","rel":"alternate"}},"published":"2011-12-24T00:00:00+01:00","updated":"2011-12-24T00:00:00+01:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2011-12-24:\/mocking-iteration-over-file-in-python.html","summary":"<p>Let&rsquo;s say that I want to mock reading from a file using file&rsquo;s iterator\ncapability, i.e. (simplified version):<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">def<\/span> <span class=\"nf\">readfile<\/span><span class=\"p\">(<\/span><span class=\"n\">f<\/span><span class=\"p\">):<\/span>\n    <span class=\"n\">using<\/span> <span class=\"nb\">open<\/span><span class=\"p\">(<\/span><span class=\"n\">f<\/span><span class=\"p\">)<\/span> <span class=\"k\">as<\/span> <span class=\"n\">fd<\/span><span class=\"p\">:<\/span>\n        <span class=\"k\">for<\/span> <span class=\"n\">line<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">fd<\/span><span class=\"p\">:<\/span>\n            <span class=\"k\">yield<\/span> <span class=\"n\">line<\/span>\n<\/code><\/pre><\/div>\n\n<p>I could mock the <code>readfile<\/code> function, but then my mock would have to\nreplicate the \u2026<\/p>","content":"<p>Let&rsquo;s say that I want to mock reading from a file using file&rsquo;s iterator\ncapability, i.e. (simplified version):<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">def<\/span> <span class=\"nf\">readfile<\/span><span class=\"p\">(<\/span><span class=\"n\">f<\/span><span class=\"p\">):<\/span>\n    <span class=\"n\">using<\/span> <span class=\"nb\">open<\/span><span class=\"p\">(<\/span><span class=\"n\">f<\/span><span class=\"p\">)<\/span> <span class=\"k\">as<\/span> <span class=\"n\">fd<\/span><span class=\"p\">:<\/span>\n        <span class=\"k\">for<\/span> <span class=\"n\">line<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">fd<\/span><span class=\"p\">:<\/span>\n            <span class=\"k\">yield<\/span> <span class=\"n\">line<\/span>\n<\/code><\/pre><\/div>\n\n<p>I could mock the <code>readfile<\/code> function, but then my mock would have to\nreplicate the functionality of <code>readfile<\/code>, which as noted is somewhat\nmore complicated than the version above. Luckily, <a href=\"http:\/\/www.voidspace.org.uk\/python\/mock\/index.html\">mock<\/a> allows us to\n<a href=\"http:\/\/www.voidspace.org.uk\/python\/mock\/examples.html#mocking-open\">mock the open function<\/a> directly! The example in the documentation is\na little short on details, though. Here&rsquo;s how to setup the mock for the\niterator case:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">open_name<\/span> <span class=\"o\">=<\/span> <span class=\"s2\">&quot;some_module.open&quot;<\/span>\n<span class=\"k\">with<\/span> <span class=\"n\">patch<\/span><span class=\"p\">(<\/span><span class=\"n\">open_name<\/span><span class=\"p\">,<\/span> <span class=\"n\">create<\/span><span class=\"o\">=<\/span><span class=\"kc\">True<\/span><span class=\"p\">)<\/span> <span class=\"k\">as<\/span> <span class=\"n\">open_mock<\/span><span class=\"p\">:<\/span>\n    <span class=\"n\">open_mock<\/span><span class=\"o\">.<\/span><span class=\"n\">return_value<\/span> <span class=\"o\">=<\/span> <span class=\"n\">MagicMock<\/span><span class=\"p\">(<\/span><span class=\"n\">spec<\/span><span class=\"o\">=<\/span><span class=\"n\">file<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">handle<\/span> <span class=\"o\">=<\/span> <span class=\"n\">open_mock<\/span><span class=\"o\">.<\/span><span class=\"n\">return_value<\/span><span class=\"o\">.<\/span><span class=\"fm\">__enter__<\/span><span class=\"o\">.<\/span><span class=\"n\">return_value<\/span>\n    <span class=\"n\">handle<\/span><span class=\"o\">.<\/span><span class=\"fm\">__iter__<\/span><span class=\"o\">.<\/span><span class=\"n\">return_value<\/span> <span class=\"o\">=<\/span> <span class=\"nb\">iter<\/span><span class=\"p\">(<\/span><span class=\"n\">splitkeepsep<\/span><span class=\"p\">(<\/span><span class=\"n\">file_contents<\/span><span class=\"p\">,<\/span> <span class=\"s2\">&quot;<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">&quot;<\/span><span class=\"p\">))<\/span>\n<\/code><\/pre><\/div>\n\n<p>The <code>file_contents<\/code> variable should contain the text of the file that&rsquo;s\nbeing mocked away, and the <code>splitkeepsep<\/code> function looks like this (see\nalso <a href=\"https:\/\/programmaticallyspeaking.com\/split-on-separator-but-keep-the-separator-in-python.html\">this post<\/a>):<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">def<\/span> <span class=\"nf\">splitkeepsep<\/span><span class=\"p\">(<\/span><span class=\"n\">s<\/span><span class=\"p\">,<\/span> <span class=\"n\">sep<\/span><span class=\"p\">):<\/span>\n    <span class=\"k\">return<\/span> <span class=\"n\">reduce<\/span><span class=\"p\">(<\/span><span class=\"k\">lambda<\/span> <span class=\"n\">acc<\/span><span class=\"p\">,<\/span> <span class=\"n\">i<\/span><span class=\"p\">:<\/span> <span class=\"n\">acc<\/span><span class=\"p\">[:<\/span><span class=\"o\">-<\/span><span class=\"mi\">1<\/span><span class=\"p\">]<\/span> <span class=\"o\">+<\/span> <span class=\"p\">[<\/span><span class=\"n\">acc<\/span><span class=\"p\">[<\/span><span class=\"o\">-<\/span><span class=\"mi\">1<\/span><span class=\"p\">]<\/span> <span class=\"o\">+<\/span> <span class=\"n\">i<\/span><span class=\"p\">]<\/span> <span class=\"k\">if<\/span> <span class=\"n\">i<\/span> <span class=\"o\">==<\/span> <span class=\"n\">sep<\/span> <span class=\"k\">else<\/span> <span class=\"n\">acc<\/span> <span class=\"o\">+<\/span> <span class=\"p\">[<\/span><span class=\"n\">i<\/span><span class=\"p\">],<\/span> <span class=\"n\">re<\/span><span class=\"o\">.<\/span><span class=\"n\">split<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;(<\/span><span class=\"si\">%s<\/span><span class=\"s2\">)&quot;<\/span> <span class=\"o\">%<\/span> <span class=\"n\">re<\/span><span class=\"o\">.<\/span><span class=\"n\">escape<\/span><span class=\"p\">(<\/span><span class=\"n\">sep<\/span><span class=\"p\">),<\/span> <span class=\"n\">s<\/span><span class=\"p\">),<\/span> <span class=\"p\">[])<\/span>\n<\/code><\/pre><\/div>\n\n<p>That&rsquo;s all there is to it! Happy mocking!<\/p>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"file"}},{"@attributes":{"term":"mock"}},{"@attributes":{"term":"test"}},{"@attributes":{"term":"Python"}}]},{"title":"Split on separator but keep the separator, in Python","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/split-on-separator-but-keep-the-separator-in-python.html","rel":"alternate"}},"published":"2011-12-23T23:41:00+01:00","updated":"2011-12-23T23:41:00+01:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2011-12-23:\/split-on-separator-but-keep-the-separator-in-python.html","summary":"<p>I have a function that reads from a file using file&rsquo;s iterator\ncapability, i.e. (simplified version, in reality there&rsquo;s going on more\nwithin the generator):<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">def<\/span> <span class=\"nf\">readfile<\/span><span class=\"p\">(<\/span><span class=\"n\">f<\/span><span class=\"p\">):<\/span>\n    <span class=\"n\">using<\/span> <span class=\"nb\">open<\/span><span class=\"p\">(<\/span><span class=\"n\">f<\/span><span class=\"p\">)<\/span> <span class=\"k\">as<\/span> <span class=\"n\">fd<\/span><span class=\"p\">:<\/span>\n        <span class=\"k\">for<\/span> <span class=\"n\">line<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">fd<\/span><span class=\"p\">:<\/span>\n            <span class=\"k\">yield<\/span> <span class=\"n\">line<\/span>\n<\/code><\/pre><\/div>\n\n<p>If the file contains something like <code>a\\nb \u2026<\/code><\/p>","content":"<p>I have a function that reads from a file using file&rsquo;s iterator\ncapability, i.e. (simplified version, in reality there&rsquo;s going on more\nwithin the generator):<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">def<\/span> <span class=\"nf\">readfile<\/span><span class=\"p\">(<\/span><span class=\"n\">f<\/span><span class=\"p\">):<\/span>\n    <span class=\"n\">using<\/span> <span class=\"nb\">open<\/span><span class=\"p\">(<\/span><span class=\"n\">f<\/span><span class=\"p\">)<\/span> <span class=\"k\">as<\/span> <span class=\"n\">fd<\/span><span class=\"p\">:<\/span>\n        <span class=\"k\">for<\/span> <span class=\"n\">line<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">fd<\/span><span class=\"p\">:<\/span>\n            <span class=\"k\">yield<\/span> <span class=\"n\">line<\/span>\n<\/code><\/pre><\/div>\n\n<p>If the file contains something like <code>a\\nb\\nc\\n<\/code>, I will get back <em>four<\/em>\nlines, three of which include the newline and one which is the empty\nstring. In mocking this function, I want the mock to behave in the same\nway, of course. Thus, I need a way to split some text on newlines, but\nkeep the newlines.<\/p>\n<p>Splitting using the <a href=\"http:\/\/docs.python.org\/library\/stdtypes.html#str.split\" title=\"Documentation on str.split\"><code>split<\/code><\/a> function of a string does not keep the\nseparator but does give the empty string part in the end:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"gp\">&gt;&gt;&gt; <\/span><span class=\"s2\">&quot;a<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">b<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">c<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">&quot;<\/span><span class=\"o\">.<\/span><span class=\"n\">split<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"go\">[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;&#39;]<\/span>\n<\/code><\/pre><\/div>\n\n<p>Another split function that can be used on strings is <a href=\"http:\/\/docs.python.org\/library\/stdtypes.html#str.splitlines\" title=\"Documentation on str.splitlines\"><code>splitlines<\/code><\/a>,\nbut it <em>only splits on newlines<\/em> and discards the empty string part in\nthe end:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"gp\">&gt;&gt;&gt; <\/span><span class=\"s2\">&quot;a<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">b<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">c<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">&quot;<\/span><span class=\"o\">.<\/span><span class=\"n\">splitlines<\/span><span class=\"p\">(<\/span><span class=\"kc\">True<\/span><span class=\"p\">)<\/span>\n<span class=\"go\">[&#39;a\\n&#39;, &#39;b\\n&#39;, &#39;c\\n&#39;]<\/span>\n<\/code><\/pre><\/div>\n\n<p>I can use a trick at this point, and append the separator &ldquo;manually&rdquo;,\nbut unfortunately the result is not exactly as I want it, as the fourth\npart is no longer the empty string:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"gp\">&gt;&gt;&gt; <\/span><span class=\"p\">[<\/span><span class=\"n\">x<\/span> <span class=\"o\">+<\/span> <span class=\"s2\">&quot;<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">&quot;<\/span> <span class=\"k\">for<\/span> <span class=\"n\">x<\/span> <span class=\"ow\">in<\/span> <span class=\"s2\">&quot;a<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">b<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">c<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">&quot;<\/span><span class=\"o\">.<\/span><span class=\"n\">split<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">&quot;<\/span><span class=\"p\">)]<\/span>\n<span class=\"go\">[&#39;a\\n&#39;, &#39;b\\n&#39;, &#39;c\\n&#39;, &#39;\\n&#39;]<\/span>\n<\/code><\/pre><\/div>\n\n<p>Similarly, if I append an empty string to the result of using\n<code>splitlines<\/code>, I would need to distinguish between the cases when the\nstring to split ends in a newline and when it doesn&rsquo;t.<\/p>\n<p>Splitting using the <a href=\"http:\/\/docs.python.org\/library\/re.html#re.split\" title=\"Documentation for re.split\"><code>split<\/code><\/a> function in the re module yields the\nexact same result as in the first case:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"gp\">&gt;&gt;&gt; <\/span><span class=\"n\">re<\/span><span class=\"o\">.<\/span><span class=\"n\">split<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">&quot;<\/span><span class=\"p\">,<\/span> <span class=\"s2\">&quot;a<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">b<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">c<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"go\">[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;&#39;]<\/span>\n<\/code><\/pre><\/div>\n\n<p>But that function uses a regular expression pattern as separator, not a\nsimple string! And in the documentation, it is spelled out that using a\ncapturing group retains the separator pattern. Let&rsquo;s try that:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"gp\">&gt;&gt;&gt; <\/span><span class=\"n\">re<\/span><span class=\"o\">.<\/span><span class=\"n\">split<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;(<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">)&quot;<\/span><span class=\"p\">,<\/span> <span class=\"s2\">&quot;a<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">b<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">c<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"go\">[&#39;a&#39;, &#39;\\n&#39;, &#39;b&#39;, &#39;\\n&#39;, &#39;c&#39;, &#39;\\n&#39;, &#39;&#39;]<\/span>\n<\/code><\/pre><\/div>\n\n<p>Much better, except for the fact that each newline is detached from its\ncorresponding line of text. But to work around that, I can apply the\n<a href=\"http:\/\/docs.python.org\/library\/functions.html#reduce\" title=\"Documentation on (builtin).reduce\"><code>reduce<\/code><\/a> function:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"gp\">&gt;&gt;&gt; <\/span><span class=\"n\">reduce<\/span><span class=\"p\">(<\/span><span class=\"k\">lambda<\/span> <span class=\"n\">acc<\/span><span class=\"p\">,<\/span> <span class=\"n\">elem<\/span><span class=\"p\">:<\/span> <span class=\"n\">acc<\/span><span class=\"p\">[:<\/span><span class=\"o\">-<\/span><span class=\"mi\">1<\/span><span class=\"p\">]<\/span> <span class=\"o\">+<\/span> <span class=\"p\">[<\/span><span class=\"n\">acc<\/span><span class=\"p\">[<\/span><span class=\"o\">-<\/span><span class=\"mi\">1<\/span><span class=\"p\">]<\/span> <span class=\"o\">+<\/span> <span class=\"n\">elem<\/span><span class=\"p\">]<\/span> <span class=\"k\">if<\/span> <span class=\"n\">elem<\/span> <span class=\"o\">==<\/span> <span class=\"s2\">&quot;<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">&quot;<\/span> <span class=\"k\">else<\/span> <span class=\"n\">acc<\/span> <span class=\"o\">+<\/span> <span class=\"p\">[<\/span><span class=\"n\">elem<\/span><span class=\"p\">],<\/span> <span class=\"n\">re<\/span><span class=\"o\">.<\/span><span class=\"n\">split<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;(<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">)&quot;<\/span><span class=\"p\">,<\/span> <span class=\"s2\">&quot;a<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">b<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">c<\/span><span class=\"se\">\\n<\/span><span class=\"s2\">&quot;<\/span><span class=\"p\">),<\/span> <span class=\"p\">[])<\/span>\n<span class=\"go\">[&#39;a\\n&#39;, &#39;b\\n&#39;, &#39;c\\n&#39;, &#39;&#39;]<\/span>\n<\/code><\/pre><\/div>\n\n<p>Voil\u00e0! The desired end result! While the code might seem intimidating,\nit&rsquo;s actually quite straightforward. The <code>reduce<\/code> function applies a\nfunction to the original list (the one resulting from the split) in\norder to reduce it to a single value, which in my case also is a list.\nThe function I use here consists of two parts. If the current element is\na separator, the function appends it to the last element of the current\naccumulator list: <code>acc[:-1] + [acc[-1] + elem] if elem == \"\\n\"<\/code>.\nOtherwise, it just appends the element to the accumulator list:\n<code>else acc + [elem]<\/code>.<\/p>\n<p>In a generic version of the one-liner above, the separator must be\nescaped so that no part of it is mistaken for a regular expression\nspecial character:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">def<\/span> <span class=\"nf\">splitkeepsep<\/span><span class=\"p\">(<\/span><span class=\"n\">s<\/span><span class=\"p\">,<\/span> <span class=\"n\">sep<\/span><span class=\"p\">):<\/span>\n    <span class=\"k\">return<\/span> <span class=\"n\">reduce<\/span><span class=\"p\">(<\/span><span class=\"k\">lambda<\/span> <span class=\"n\">acc<\/span><span class=\"p\">,<\/span> <span class=\"n\">elem<\/span><span class=\"p\">:<\/span> <span class=\"n\">acc<\/span><span class=\"p\">[:<\/span><span class=\"o\">-<\/span><span class=\"mi\">1<\/span><span class=\"p\">]<\/span> <span class=\"o\">+<\/span> <span class=\"p\">[<\/span><span class=\"n\">acc<\/span><span class=\"p\">[<\/span><span class=\"o\">-<\/span><span class=\"mi\">1<\/span><span class=\"p\">]<\/span> <span class=\"o\">+<\/span> <span class=\"n\">elem<\/span><span class=\"p\">]<\/span> <span class=\"k\">if<\/span> <span class=\"n\">elem<\/span> <span class=\"o\">==<\/span> <span class=\"n\">sep<\/span> <span class=\"k\">else<\/span> <span class=\"n\">acc<\/span> <span class=\"o\">+<\/span> <span class=\"p\">[<\/span><span class=\"n\">elem<\/span><span class=\"p\">],<\/span> <span class=\"n\">re<\/span><span class=\"o\">.<\/span><span class=\"n\">split<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;(<\/span><span class=\"si\">%s<\/span><span class=\"s2\">)&quot;<\/span> <span class=\"o\">%<\/span> <span class=\"n\">re<\/span><span class=\"o\">.<\/span><span class=\"n\">escape<\/span><span class=\"p\">(<\/span><span class=\"n\">sep<\/span><span class=\"p\">),<\/span> <span class=\"n\">s<\/span><span class=\"p\">),<\/span> <span class=\"p\">[])<\/span>\n<\/code><\/pre><\/div>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"reduce"}},{"@attributes":{"term":"split"}},{"@attributes":{"term":"string"}},{"@attributes":{"term":"Python"}}]},{"title":"Function return value caching in F#","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/function-return-value-caching-in-f.html","rel":"alternate"}},"published":"2011-12-20T00:40:00+01:00","updated":"2011-12-20T00:40:00+01:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2011-12-20:\/function-return-value-caching-in-f.html","summary":"<p>In my <a href=\"http:\/\/www.testness.org\">TestNess<\/a> project I have decided to try to rewrite certain\nparts in F# to see if the code can benefit from functional programming.\nIt is also a learning thing as I&rsquo;m definitively not well versed in\nfunctional programming - yet :-). One of the specific problems I try to \u2026<\/p>","content":"<p>In my <a href=\"http:\/\/www.testness.org\">TestNess<\/a> project I have decided to try to rewrite certain\nparts in F# to see if the code can benefit from functional programming.\nIt is also a learning thing as I&rsquo;m definitively not well versed in\nfunctional programming - yet :-). One of the specific problems I try to\naddress is to create sub structures given a root structure. The root\nstructure is typically a method, and a sub structure can be a call graph\nfor that method. Creating a call graph is non-trivial, so preferably I\nwant to do this only once for each method, and I therefore need to cache\nthe graph.<\/p>\n<p>This is in itself not a problem at all, but my colleague <a href=\"http:\/\/jimmynilsson.com\/blog\/\">Jimmy<\/a> told\nme he was pretty sure that functional languages have some sort of\nbuild-in caching in general. This lead me to investigate a bit, and I\nended up on <a href=\"http:\/\/en.wikibooks.org\/wiki\/F_Sharp_Programming\/Caching\">this page<\/a>.<\/p>\n<p>To test return value caching, I created a tiny Visual Studio 2010\nproject which can be <a href=\"https:\/\/github.com\/provegard\/FSharpCaching\">fetched<\/a> from GitHub.<\/p>\n<p>To begin with, I need a type from which I can create instances (this\ntype corresponds to the aforementioned call graph):<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">type<\/span><span class=\"w\"> <\/span><span class=\"nc\">AType<\/span><span class=\"o\">(<\/span><span class=\"n\">i<\/span><span class=\"o\">:<\/span><span class=\"n\">int<\/span><span class=\"o\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">class<\/span><span class=\"w\"> <\/span><span class=\"k\">end<\/span>\n<\/code><\/pre><\/div>\n\n<p>(You gotta love the conciseness!) Next, a function that creates an\ninstance of the type given some input:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span><span class=\"w\"> <\/span><span class=\"nv\">produceWithArg<\/span><span class=\"w\"> <\/span><span class=\"n\">i<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">AType<\/span><span class=\"o\">(<\/span><span class=\"n\">i<\/span><span class=\"o\">)<\/span>\n<span class=\"k\">let<\/span><span class=\"w\"> <\/span><span class=\"nv\">produce<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">produceWithArg<\/span>\n<\/code><\/pre><\/div>\n\n<p>For the sake of unit testing this, I&rsquo;ll create an &ldquo;alias&rdquo; function\ncalled <code>produce<\/code>. I&rsquo;ve created two really simple unit tests, one that\nverifies that the function produces the same value if given the same\ninput repeatedly, and one that verifies that the return values are not\nthe same for different inputs. Here they are in all their glory (I chose\nNUnit simply because I had it on my machine):<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">[&lt;<\/span><span class=\"n\">TestFixture<\/span><span class=\"o\">&gt;]<\/span>\n<span class=\"k\">type<\/span><span class=\"w\"> <\/span><span class=\"nc\">cachingFixture<\/span><span class=\"bp\">()<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">class<\/span>\n\n<span class=\"w\">    <\/span><span class=\"o\">[&lt;<\/span><span class=\"n\">Test<\/span><span class=\"o\">&gt;]<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">member<\/span><span class=\"w\"> <\/span><span class=\"n\">self<\/span><span class=\"p\">.<\/span><span class=\"nf\">cacheWithSameInputTest<\/span><span class=\"bp\">()<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span>\n<span class=\"w\">        <\/span><span class=\"nn\">Assert<\/span><span class=\"p\">.<\/span><span class=\"n\">AreSame<\/span><span class=\"w\"> <\/span><span class=\"o\">(<\/span><span class=\"n\">produce<\/span><span class=\"w\"> <\/span><span class=\"mi\">1<\/span><span class=\"o\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">produce<\/span><span class=\"w\"> <\/span><span class=\"mi\">1<\/span><span class=\"o\">)<\/span>\n\n<span class=\"w\">    <\/span><span class=\"o\">[&lt;<\/span><span class=\"n\">Test<\/span><span class=\"o\">&gt;]<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">member<\/span><span class=\"w\"> <\/span><span class=\"n\">self<\/span><span class=\"p\">.<\/span><span class=\"nf\">dontCacheWithDifferentInputsTest<\/span><span class=\"bp\">()<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span>\n<span class=\"w\">        <\/span><span class=\"nn\">Assert<\/span><span class=\"p\">.<\/span><span class=\"n\">AreNotSame<\/span><span class=\"w\"> <\/span><span class=\"o\">(<\/span><span class=\"n\">produce<\/span><span class=\"w\"> <\/span><span class=\"mi\">1<\/span><span class=\"o\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">produce<\/span><span class=\"w\"> <\/span><span class=\"mi\">2<\/span><span class=\"o\">)<\/span>\n\n<span class=\"k\">end<\/span>\n<\/code><\/pre><\/div>\n\n<p>With the <code>produce<\/code> function as defined above, the first test fails while\nthe second passes. This is quite expected, as the function obviously\ncreates a new instance each time it is called.<\/p>\n<p>The first attempt at a caching solution, then, is to remove the\nargument. According to the link mentioned previously: &ldquo;When F# comes\nacross a function with no parameters, F# will only evaluate the\nfunction once and reuse its value everytime the function is accessed.&rdquo;\nLet&rsquo;s try it:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span><span class=\"w\"> <\/span><span class=\"nv\">produceNoArg<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">fun<\/span><span class=\"w\"> <\/span><span class=\"n\">i<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">AType<\/span><span class=\"o\">(<\/span><span class=\"n\">i<\/span><span class=\"o\">)<\/span>\n<span class=\"k\">let<\/span><span class=\"w\"> <\/span><span class=\"nv\">produce<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">produceNoArg<\/span>\n<\/code><\/pre><\/div>\n\n<p>Unfortunately, the test result is the same as before. The reason? Well,\nwhat&rsquo;s being cached in this case is indeed the return value, which\nhappens to be the (anonymous) function! But if the returned function is\ncalled twice, it will of course create two instances of the type! <em>It&rsquo;s<\/em>\nreturn value cannot be cached since it takes a parameter.<\/p>\n<p><strong>Lesson learned<\/strong>: This type of caching is only interesting if the\n<em>evaluation<\/em> of the function is expensive but the <em>execution<\/em> is\ntrivial. My situation is directly orthogonal to this!<\/p>\n<p>The next attempt is to use lazy evaluation. Using the <code>lazy<\/code> keyword, we\ncan create a <code>Lazy&lt;AType&gt;<\/code> instance that caches its value:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span><span class=\"w\"> <\/span><span class=\"nv\">produceLazy<\/span><span class=\"w\"> <\/span><span class=\"n\">i<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">lazy<\/span><span class=\"o\">(<\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">AType<\/span><span class=\"o\">(<\/span><span class=\"n\">i<\/span><span class=\"o\">))<\/span>\n<span class=\"k\">let<\/span><span class=\"w\"> <\/span><span class=\"nv\">produce<\/span><span class=\"w\"> <\/span><span class=\"n\">i<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"o\">(<\/span><span class=\"n\">produceLazy<\/span><span class=\"w\"> <\/span><span class=\"n\">i<\/span><span class=\"o\">).<\/span><span class=\"n\">Force<\/span><span class=\"bp\">()<\/span>\n<\/code><\/pre><\/div>\n\n<p>Note that this is not as transparent as before; we need to call the\n<code>Force()<\/code> method to retrieve the value. And sadly, our tests are still\nin the same state - the first fails and second passes. What happened is\nthat two <code>Lazy&lt;AType&gt;<\/code> were created, and they won&rsquo;t cache values between\neach other for obvious reasons.<\/p>\n<p>Would it be better to combine a parameter-less function with lazy\nevaluation? No, because at some point we must introduce a function that\ntakes a parameter, and then everything is lost.<\/p>\n<p>So the third attempt is to use memoization, which in this context means\nexplicit return value caching. But we can do a bit better than having to\nbe explicit in every function that needs caching. I use the <code>memoize<\/code>\nfunction copied from the link above like so:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">let<\/span><span class=\"w\"> <\/span><span class=\"nv\">produceMem<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">memoize<\/span><span class=\"o\">(<\/span><span class=\"k\">fun<\/span><span class=\"w\"> <\/span><span class=\"n\">i<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">AType<\/span><span class=\"o\">(<\/span><span class=\"n\">i<\/span><span class=\"o\">))<\/span>\n<span class=\"k\">let<\/span><span class=\"w\"> <\/span><span class=\"nv\">produce<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">produceMem<\/span>\n<\/code><\/pre><\/div>\n\n<p>And finally both tests pass!<\/p>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"caching"}},{"@attributes":{"term":"f#"}},{"@attributes":{"term":"return value"}}]},{"title":"A Maven POM for building JSR335 code","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/a-maven-pom-for-building-jsr335-code.html","rel":"alternate"}},"published":"2011-12-19T23:48:00+01:00","updated":"2011-12-19T23:48:00+01:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2011-12-19:\/a-maven-pom-for-building-jsr335-code.html","summary":"<p>While playing around with lambdas and defender methods developed within\nthe scope of <a href=\"http:\/\/openjdk.java.net\/projects\/lambda\/\">Project Lambda<\/a>, I thought I&rsquo;d create a Maven POM file\nto facilitate compiling, testing and weaving (the process of making\ndefender methods work in the JVM) of the code I write. The entire\nproject can be \u2026<\/p>","content":"<p>While playing around with lambdas and defender methods developed within\nthe scope of <a href=\"http:\/\/openjdk.java.net\/projects\/lambda\/\">Project Lambda<\/a>, I thought I&rsquo;d create a Maven POM file\nto facilitate compiling, testing and weaving (the process of making\ndefender methods work in the JVM) of the code I write. The entire\nproject can be <a href=\"https:\/\/github.com\/provegard\/jsr335-maven\/\">fetched<\/a> from GitHub.<\/p>\n<p>Since a POM file can be quite intimidating, I&rsquo;ll go through it step by\nstep. First some basic stuff, defining the identity of the project:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nt\">&lt;project<\/span><span class=\"w\"> <\/span><span class=\"na\">xmlns=<\/span><span class=\"s\">&quot;http:\/\/maven.apache.org\/POM\/4.0.0&quot;<\/span><span class=\"w\"> <\/span>\n<span class=\"w\">         <\/span><span class=\"na\">xmlns:xsi=<\/span><span class=\"s\">&quot;http:\/\/www.w3.org\/2001\/XMLSchema-instance&quot;<\/span><span class=\"w\"> <\/span>\n<span class=\"w\">         <\/span><span class=\"na\">xsi:schemaLocation=<\/span><span class=\"s\">&quot;http:\/\/maven.apache.org\/POM\/4.0.0 http:\/\/maven.apache.org\/maven-v4_0_0.xsd&quot;<\/span><span class=\"nt\">&gt;<\/span>\n<span class=\"w\">  <\/span><span class=\"nt\">&lt;modelVersion&gt;<\/span>4.0.0<span class=\"nt\">&lt;\/modelVersion&gt;<\/span>\n\n<span class=\"w\">  <\/span><span class=\"nt\">&lt;groupId&gt;<\/span>com.programmaticallyspeaking.jsr335<span class=\"nt\">&lt;\/groupId&gt;<\/span>\n<span class=\"w\">  <\/span><span class=\"nt\">&lt;artifactId&gt;<\/span>jsr335-maven<span class=\"nt\">&lt;\/artifactId&gt;<\/span>\n<span class=\"w\">  <\/span><span class=\"nt\">&lt;version&gt;<\/span>1.0<span class=\"nt\">&lt;\/version&gt;<\/span>\n<span class=\"w\">  <\/span><span class=\"nt\">&lt;packaging&gt;<\/span>jar<span class=\"nt\">&lt;\/packaging&gt;<\/span>\n<\/code><\/pre><\/div>\n\n<p>My tests use <a href=\"http:\/\/testng.org\">TestNG<\/a>, so I&rsquo;ll need that as a test dependency:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"w\">  <\/span><span class=\"nt\">&lt;dependencies&gt;<\/span>\n<span class=\"w\">    <\/span><span class=\"nt\">&lt;dependency&gt;<\/span>\n<span class=\"w\">      <\/span><span class=\"nt\">&lt;groupId&gt;<\/span>org.testng<span class=\"nt\">&lt;\/groupId&gt;<\/span>\n<span class=\"w\">      <\/span><span class=\"nt\">&lt;artifactId&gt;<\/span>testng<span class=\"nt\">&lt;\/artifactId&gt;<\/span>\n<span class=\"w\">      <\/span><span class=\"nt\">&lt;version&gt;<\/span>6.3.1<span class=\"nt\">&lt;\/version&gt;<\/span>\n<span class=\"w\">      <\/span><span class=\"nt\">&lt;scope&gt;<\/span>test<span class=\"nt\">&lt;\/scope&gt;<\/span>\n<span class=\"w\">    <\/span><span class=\"nt\">&lt;\/dependency&gt;<\/span>\n<span class=\"w\">  <\/span><span class=\"nt\">&lt;\/dependencies&gt;<\/span>\n<\/code><\/pre><\/div>\n\n<p>Now for the interesting parts. First, we need to configure the compiler\nplugin to use the<a href=\"\/?p=375\">appropriate JDK<\/a>. For that, it relies on the\n<code>JDK8_HOME<\/code> environment variable being set (the error we get if the\nvariable is unset is quite ugly, but it&rsquo;s not important right now; check\nout the <a href=\"http:\/\/maven.apache.org\/plugins\/maven-enforcer-plugin\/\">enforcer plugin<\/a> if you want to handle it nicer). Since we\nhave a custom JDK, we must fork the compilation; otherwise we&rsquo;d just use\nthe regular JDK (the one Maven uses by default). Finally, we must\nspecify source and target versions, since they both default to 1.5:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"w\">  <\/span><span class=\"nt\">&lt;build&gt;<\/span>\n<span class=\"w\">    <\/span><span class=\"nt\">&lt;plugins&gt;<\/span>\n<span class=\"w\">      <\/span><span class=\"nt\">&lt;plugin&gt;<\/span>\n<span class=\"w\">        <\/span><span class=\"nt\">&lt;artifactId&gt;<\/span>maven-compiler-plugin<span class=\"nt\">&lt;\/artifactId&gt;<\/span>\n<span class=\"w\">        <\/span><span class=\"nt\">&lt;version&gt;<\/span>2.3.2<span class=\"nt\">&lt;\/version&gt;<\/span>\n<span class=\"w\">        <\/span><span class=\"nt\">&lt;configuration&gt;<\/span>\n<span class=\"w\">          <\/span><span class=\"cm\">&lt;!-- Must use the 1.8\/lambda compiler. --&gt;<\/span>\n<span class=\"w\">          <\/span><span class=\"nt\">&lt;fork&gt;<\/span>true<span class=\"nt\">&lt;\/fork&gt;<\/span>\n<span class=\"w\">          <\/span><span class=\"nt\">&lt;executable&gt;<\/span>${env.JDK8_HOME}\/bin\/javac<span class=\"nt\">&lt;\/executable&gt;<\/span>\n<span class=\"w\">          <\/span><span class=\"cm\">&lt;!-- Testing 1.8 features, 1.8 source requires 1.8 target. --&gt;<\/span>\n<span class=\"w\">          <\/span><span class=\"nt\">&lt;source&gt;<\/span>1.8<span class=\"nt\">&lt;\/source&gt;<\/span>\n<span class=\"w\">          <\/span><span class=\"nt\">&lt;target&gt;<\/span>1.8<span class=\"nt\">&lt;\/target&gt;<\/span>\n<span class=\"w\">        <\/span><span class=\"nt\">&lt;\/configuration&gt;<\/span>\n<span class=\"w\">      <\/span><span class=\"nt\">&lt;\/plugin&gt;<\/span>\n<\/code><\/pre><\/div>\n\n<p>The surefire plugin runs unit tests, and for that we need to fork using\nthe special JDK as well. The configuration is easier than for the\ncompiler plugin, and forking is on by default:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"w\">      <\/span><span class=\"nt\">&lt;plugin&gt;<\/span>\n<span class=\"w\">        <\/span><span class=\"nt\">&lt;artifactId&gt;<\/span>maven-surefire-plugin<span class=\"nt\">&lt;\/artifactId&gt;<\/span>\n<span class=\"w\">        <\/span><span class=\"nt\">&lt;version&gt;<\/span>2.11<span class=\"nt\">&lt;\/version&gt;<\/span>\n<span class=\"w\">        <\/span><span class=\"nt\">&lt;configuration&gt;<\/span>\n<span class=\"w\">          <\/span><span class=\"cm\">&lt;!-- Use the 1.8\/lambda JVM when forking. --&gt;<\/span>\n<span class=\"w\">          <\/span><span class=\"nt\">&lt;jvm&gt;<\/span>${env.JDK8_HOME}\/bin\/java<span class=\"nt\">&lt;\/jvm&gt;<\/span>\n<span class=\"w\">        <\/span><span class=\"nt\">&lt;\/configuration&gt;<\/span>\n<span class=\"w\">      <\/span><span class=\"nt\">&lt;\/plugin&gt;<\/span>\n<\/code><\/pre><\/div>\n\n<p>Finally we must weave in defender method support in the class files\nsince the JVM doesn&rsquo;t yet support defender methods. This is impossible\nto do declaratively, so we must resort to the antrun plugin. For this\npart, the <code>DPROTO_HOME<\/code> environment variable must be set as well. In the\nAnt task, we weave class files into a temporary directory, from which we\nthen copy the files back to the proper <em>classes<\/em> directory before\ndeleting the temporary one:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"w\">      <\/span><span class=\"nt\">&lt;plugin&gt;<\/span>\n<span class=\"w\">        <\/span><span class=\"nt\">&lt;artifactId&gt;<\/span>maven-antrun-plugin<span class=\"nt\">&lt;\/artifactId&gt;<\/span>\n<span class=\"w\">        <\/span><span class=\"nt\">&lt;version&gt;<\/span>1.7<span class=\"nt\">&lt;\/version&gt;<\/span>\n<span class=\"w\">        <\/span><span class=\"nt\">&lt;executions&gt;<\/span>\n<span class=\"w\">          <\/span><span class=\"nt\">&lt;execution&gt;<\/span>\n<span class=\"w\">            <\/span><span class=\"cm\">&lt;!-- Phase suitable for doing bytecode magic. --&gt;<\/span>\n<span class=\"w\">            <\/span><span class=\"nt\">&lt;phase&gt;<\/span>process-classes<span class=\"nt\">&lt;\/phase&gt;<\/span>\n<span class=\"w\">            <\/span><span class=\"nt\">&lt;goals&gt;<\/span>\n<span class=\"w\">              <\/span><span class=\"nt\">&lt;goal&gt;<\/span>run<span class=\"nt\">&lt;\/goal&gt;<\/span>\n<span class=\"w\">            <\/span><span class=\"nt\">&lt;\/goals&gt;<\/span>\n<span class=\"w\">          <\/span><span class=\"nt\">&lt;\/execution&gt;<\/span>\n<span class=\"w\">        <\/span><span class=\"nt\">&lt;\/executions&gt;<\/span>\n<span class=\"w\">        <\/span><span class=\"nt\">&lt;configuration&gt;<\/span>\n<span class=\"w\">          <\/span><span class=\"nt\">&lt;target&gt;<\/span>\n<span class=\"w\">            <\/span><span class=\"nt\">&lt;property<\/span><span class=\"w\"> <\/span><span class=\"na\">name=<\/span><span class=\"s\">&quot;woven.dir&quot;<\/span><span class=\"w\"> <\/span><span class=\"na\">value=<\/span><span class=\"s\">&quot;${project.build.directory}\/woven&quot;<\/span><span class=\"w\"> <\/span><span class=\"nt\">\/&gt;<\/span>\n<span class=\"w\">            <\/span><span class=\"cm\">&lt;!-- Run static weaver on classes, can use standard JVM. --&gt;<\/span>\n<span class=\"w\">            <\/span><span class=\"nt\">&lt;java<\/span>\n<span class=\"w\">              <\/span><span class=\"na\">classpath=<\/span><span class=\"s\">&quot;${env.DPROTO_HOME}\/distrib\/jsr335-agent.jar:${env.DPROTO_HOME}\/lib\/asm-4.0.jar&quot;<\/span>\n<span class=\"w\">              <\/span><span class=\"na\">classname=<\/span><span class=\"s\">&quot;jsr335.agent.Main&quot;<\/span>\n<span class=\"w\">              <\/span><span class=\"nt\">&gt;<\/span>\n<span class=\"w\">              <\/span><span class=\"nt\">&lt;arg<\/span><span class=\"w\"> <\/span><span class=\"na\">value=<\/span><span class=\"s\">&quot;-d&quot;<\/span><span class=\"w\"> <\/span><span class=\"nt\">\/&gt;<\/span>\n<span class=\"w\">              <\/span><span class=\"nt\">&lt;arg<\/span><span class=\"w\"> <\/span><span class=\"na\">value=<\/span><span class=\"s\">&quot;${woven.dir}&quot;<\/span><span class=\"w\"> <\/span><span class=\"nt\">\/&gt;<\/span>\n<span class=\"w\">              <\/span><span class=\"nt\">&lt;arg<\/span><span class=\"w\"> <\/span><span class=\"na\">value=<\/span><span class=\"s\">&quot;--jdk&quot;<\/span><span class=\"w\"> <\/span><span class=\"nt\">\/&gt;<\/span>\n<span class=\"w\">              <\/span><span class=\"nt\">&lt;arg<\/span><span class=\"w\"> <\/span><span class=\"na\">value=<\/span><span class=\"s\">&quot;${env.JDK8_HOME}&quot;<\/span><span class=\"w\"> <\/span><span class=\"nt\">\/&gt;<\/span>\n<span class=\"w\">              <\/span><span class=\"nt\">&lt;arg<\/span><span class=\"w\"> <\/span><span class=\"na\">value=<\/span><span class=\"s\">&quot;${project.build.outputDirectory}&quot;<\/span><span class=\"w\"> <\/span><span class=\"nt\">\/&gt;<\/span>\n<span class=\"w\">            <\/span><span class=\"nt\">&lt;\/java&gt;<\/span>\n\n<span class=\"w\">            <\/span><span class=\"cm\">&lt;!-- Copy woven classes back to class dir. --&gt;<\/span>\n<span class=\"w\">            <\/span><span class=\"nt\">&lt;copy<\/span><span class=\"w\"> <\/span><span class=\"na\">todir=<\/span><span class=\"s\">&quot;${project.build.outputDirectory}&quot;<\/span><span class=\"nt\">&gt;<\/span>\n<span class=\"w\">              <\/span><span class=\"nt\">&lt;fileset<\/span><span class=\"w\"> <\/span><span class=\"na\">dir=<\/span><span class=\"s\">&quot;${woven.dir}&quot;<\/span><span class=\"w\"> <\/span><span class=\"nt\">\/&gt;<\/span>\n<span class=\"w\">            <\/span><span class=\"nt\">&lt;\/copy&gt;<\/span>\n\n<span class=\"w\">            <\/span><span class=\"nt\">&lt;delete<\/span><span class=\"w\"> <\/span><span class=\"na\">dir=<\/span><span class=\"s\">&quot;${woven.dir}&quot;<\/span><span class=\"w\"> <\/span><span class=\"nt\">\/&gt;<\/span>\n<span class=\"w\">          <\/span><span class=\"nt\">&lt;\/target&gt;<\/span>\n<span class=\"w\">        <\/span><span class=\"nt\">&lt;\/configuration&gt;<\/span>\n<span class=\"w\">      <\/span><span class=\"nt\">&lt;\/plugin&gt;<\/span>\n<span class=\"w\">    <\/span><span class=\"nt\">&lt;\/plugins&gt;<\/span>\n<span class=\"w\">  <\/span><span class=\"nt\">&lt;\/build&gt;<\/span>\n<span class=\"nt\">&lt;\/project&gt;<\/span>\n<\/code><\/pre><\/div>\n\n<p><strong>Note<\/strong>: We could add an execution that binds to the\n<em>process-test-classes<\/em> phase, but it seems as if weaving must be done\nall in one go as opposed to in two separate steps. This means that if\nyou have a class within the tests that implements an interface with\ndefender methods, things won&rsquo;t work out very well for you.<\/p>\n<p>And that&rsquo;s all there is to it!<\/p>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"closures"}},{"@attributes":{"term":"defender methods"}},{"@attributes":{"term":"java8"}},{"@attributes":{"term":"maven"}}]},{"title":"Some notes on building Project Lambda to test closures and defender methods in Java","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/some-notes-on-building-project-lambda-to-test-closures-and-defender-methods-in-java.html","rel":"alternate"}},"published":"2011-12-15T00:32:00+01:00","updated":"2011-12-15T00:32:00+01:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2011-12-15:\/some-notes-on-building-project-lambda-to-test-closures-and-defender-methods-in-java.html","summary":"<p>Check out <a href=\"http:\/\/openjdk.java.net\/projects\/lambda\/\">Project Lambda<\/a> if you don&rsquo;t already know what I&rsquo;m talking\nabout! It adds lambda functions and interface extension methods to Java.\nLambda functions allows for very compact and concise code as well as\nfunctional programming aspects. Interface extension methods gives you\nthe ability to add to \u2026<\/p>","content":"<p>Check out <a href=\"http:\/\/openjdk.java.net\/projects\/lambda\/\">Project Lambda<\/a> if you don&rsquo;t already know what I&rsquo;m talking\nabout! It adds lambda functions and interface extension methods to Java.\nLambda functions allows for very compact and concise code as well as\nfunctional programming aspects. Interface extension methods gives you\nthe ability to add to interfaces without breaking implementing classes\n(and can also be seen as a poor man&rsquo;s <a href=\"http:\/\/en.wikipedia.org\/wiki\/Multiple_inheritance\">multiple inheritance<\/a>, which in\nturn opens up for <a href=\"http:\/\/en.wikipedia.org\/wiki\/Mixins\">mixins<\/a>).<\/p>\n<p>These things already exist in the .NET world and are very powerful, so I\nwanted to try them out in Java. As of this writing, though, the binary\nsnapshot available <a href=\"http:\/\/jdk8.java.net\/lambda\/\">here<\/a> does not support defender methods. You have\nto build everything from source.<\/p>\n<p>Anyway, below are some notes on the build process. The full readme can\nbe found <a href=\"http:\/\/hg.openjdk.java.net\/jdk8\/jdk8\/raw-file\/tip\/README-builds.html\">here<\/a>.<\/p>\n<p><strong>Update 2011-12-15<\/strong>: I created a <a href=\"https:\/\/gist.github.com\/1480571\">script<\/a> that performs the steps\nbelow minus installing prerequisites.<\/p>\n<h3>Operating System<\/h3>\n<p>Just to set the context:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>uname<span class=\"w\"> <\/span>-a\nLinux<span class=\"w\"> <\/span>devel<span class=\"w\"> <\/span><span class=\"m\">2<\/span>.6.38-8-server<span class=\"w\"> <\/span><span class=\"c1\">#42-Ubuntu SMP Mon Apr 11 03:49:04 UTC 2011 x86_64 x86_64 x86_64 GNU\/Linux<\/span>\n$<span class=\"w\"> <\/span>cat<span class=\"w\"> <\/span>\/etc\/lsb-release\n<span class=\"nv\">DISTRIB_ID<\/span><span class=\"o\">=<\/span>Ubuntu\n<span class=\"nv\">DISTRIB_RELEASE<\/span><span class=\"o\">=<\/span><span class=\"m\">11<\/span>.04\n<span class=\"nv\">DISTRIB_CODENAME<\/span><span class=\"o\">=<\/span>natty\n<span class=\"nv\">DISTRIB_DESCRIPTION<\/span><span class=\"o\">=<\/span><span class=\"s2\">&quot;Ubuntu 11.04&quot;<\/span>\n<\/code><\/pre><\/div>\n\n<p>I couldn&rsquo;t get the build to work on another machine running Oneric,\nthough. The linker wouldn&rsquo;t link against <em>libasound<\/em> for some reason.<\/p>\n<h3>Install prerequisites<\/h3>\n<p>Some of these are listed in the readme linked above. YMMV since you\nprobably already have some of the packages. Here are the ones I had to\ninstall:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">zip<\/span><span class=\"w\"> <\/span><span class=\"nx\">unzip<\/span><span class=\"w\"> <\/span><span class=\"nx\">libasound2<\/span><span class=\"o\">-<\/span><span class=\"nx\">dev<\/span><span class=\"w\"> <\/span><span class=\"nx\">libcups2<\/span><span class=\"o\">-<\/span><span class=\"nx\">dev<\/span><span class=\"w\"> <\/span><span class=\"nx\">libfreetype6<\/span><span class=\"o\">-<\/span><span class=\"nx\">dev<\/span><span class=\"w\"> <\/span><span class=\"nx\">gawk<\/span><span class=\"w\"> <\/span><span class=\"nx\">libxext<\/span><span class=\"o\">-<\/span><span class=\"nx\">dev<\/span><span class=\"w\"> <\/span><span class=\"nx\">libxrender<\/span><span class=\"o\">-<\/span><span class=\"nx\">dev<\/span><span class=\"w\"> <\/span><span class=\"nx\">libxtst<\/span><span class=\"o\">-<\/span><span class=\"nx\">dev<\/span>\n<\/code><\/pre><\/div>\n\n<p>Mercurial, Java and Ant are essential. :-) You need at least JDK 1.7.0\nto build things, and I found it quite painful to install Java 1.7 using\nUbuntu&rsquo;s own package system. I think the problem was that I installed\nJava before Ant, and Ant dragged in Java 6 which changed all the\n<em>alternatives<\/em> symlinks. In the end, I downloaded the JDK from\n<a href=\"http:\/\/www.oracle.com\/technetwork\/java\/javase\/downloads\/java-se-jdk-7-download-432154.html\">Oracle<\/a>, unpacked it to <em>\/opt\/jdk1.7.0<\/em> and updated my <code>PATH<\/code>\nenvironment variable to include <em>\/opt\/jdk1.7.0\/bin<\/em> before anything\nelse.<\/p>\n<h3>Download defender-prototype<\/h3>\n<p>Defender-prototype implements the weaving necessary for defender methods\nto work in the JVM. The build script for Project Lambda expects\ndefender-prototype to exist alongside Lambda&rsquo;s own directory.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>hg<span class=\"w\"> <\/span>clone<span class=\"w\"> <\/span>http:\/\/hg.openjdk.java.net\/lambda\/defender-prototype\n<\/code><\/pre><\/div>\n\n<h3>Download defender-prototype required libraries<\/h3>\n<p>These are not included in the repository, so manual download is needed.\nFeel free to select a different mirror for ASM from <a href=\"http:\/\/forge.ow2.org\/project\/download.php?group_id=23&amp;file_id=17183\">here<\/a> (if there\nis one, that is).<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span><span class=\"nb\">cd<\/span><span class=\"w\"> <\/span>defender-prototype\n$<span class=\"w\"> <\/span>mkdir<span class=\"w\"> <\/span>lib<span class=\"w\"> <\/span><span class=\"o\">&amp;&amp;<\/span><span class=\"w\"> <\/span><span class=\"nb\">cd<\/span><span class=\"w\"> <\/span>lib\n$<span class=\"w\"> <\/span>wget<span class=\"w\"> <\/span>http:\/\/testng.org\/testng-6.2.zip\n$<span class=\"w\"> <\/span>unzip<span class=\"w\"> <\/span>-e<span class=\"w\"> <\/span>-j<span class=\"w\"> <\/span>testng-6.2.zip<span class=\"w\"> <\/span>testng-6.2\/testng-6.2.jar\n$<span class=\"w\"> <\/span>wget<span class=\"w\"> <\/span>http:\/\/download.forge.objectweb.org\/asm\/asm-4.0-bin.zip\n$<span class=\"w\"> <\/span>unzip<span class=\"w\"> <\/span>-e<span class=\"w\"> <\/span>-j<span class=\"w\"> <\/span>asm-4.0-bin.zip<span class=\"w\"> <\/span>asm-4.0\/lib\/asm-4.0.jar\n$<span class=\"w\"> <\/span>rm<span class=\"w\"> <\/span>asm-4.0-bin.zip<span class=\"w\"> <\/span>testng-6.2.zip\n$<span class=\"w\"> <\/span><span class=\"nb\">cd<\/span><span class=\"w\"> <\/span>..\n<\/code><\/pre><\/div>\n\n<h3>Build defender-prototype<\/h3>\n<p>Very simple:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>ant\n<\/code><\/pre><\/div>\n\n<h3>Download the Project Lambda source code<\/h3>\n<p>Two-step process:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>hg<span class=\"w\"> <\/span>clone<span class=\"w\"> <\/span>http:\/\/hg.openjdk.java.net\/lambda\/lambda\n$<span class=\"w\"> <\/span><span class=\"nb\">cd<\/span><span class=\"w\"> <\/span>lambda\n$<span class=\"w\"> <\/span>sh<span class=\"w\"> <\/span>get_source.sh\n<\/code><\/pre><\/div>\n\n<h3>Setup the environment<\/h3>\n<p><code>JAVA_HOME<\/code> must be unset, while <code>ALT_BOOTDIR<\/code> should point to the JDK\ndirectory. Here&rsquo;s how to find the real JDK directory in case you&rsquo;re\nusing a Ubuntu package:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>readlink<span class=\"w\"> <\/span>-f<span class=\"w\"> <\/span><span class=\"k\">$(<\/span>dirname<span class=\"w\"> <\/span><span class=\"k\">$(<\/span>readlink<span class=\"w\"> <\/span>-f<span class=\"w\"> <\/span><span class=\"k\">$(<\/span>which<span class=\"w\"> <\/span>javac<span class=\"k\">)))<\/span>\/..\n\/opt\/jdk1.7.0\n<\/code><\/pre><\/div>\n\n<p>We also want the build scripts to download required dependencies for us,\nso <code>ALLOW_DOWNLOADS<\/code> should be set to <code>true<\/code>. And the build script\nrequires <code>LANG<\/code> to be set to <code>C<\/code>. Thus:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span><span class=\"nb\">unset<\/span><span class=\"w\"> <\/span>JAVA_HOME\n$<span class=\"w\"> <\/span><span class=\"nb\">export<\/span><span class=\"w\"> <\/span><span class=\"nv\">ALT_BOOTDIR<\/span><span class=\"o\">=<\/span>\/opt\/jdk1.7.0\n$<span class=\"w\"> <\/span><span class=\"nb\">export<\/span><span class=\"w\"> <\/span><span class=\"nv\">ALLOW_DOWNLOADS<\/span><span class=\"o\">=<\/span><span class=\"nb\">true<\/span>\n$<span class=\"w\"> <\/span><span class=\"nb\">export<\/span><span class=\"w\"> <\/span><span class=\"nv\">LANG<\/span><span class=\"o\">=<\/span>C\n<\/code><\/pre><\/div>\n\n<h3>Perform partial sanity check<\/h3>\n<p>Partial, because it unfortunately doesn&rsquo;t check all prerequisites. The\nsanity check is run when you build (below), but it might be useful to\nrun it separately:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>make<span class=\"w\"> <\/span>sanity\n<\/code><\/pre><\/div>\n\n<h3>Build and install<\/h3>\n<p>Very simple also, but takes some time&hellip; Check back periodically for\nmissing prerequisites!<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>make<span class=\"w\"> <\/span>all\n<\/code><\/pre><\/div>\n\n<p>Installation is a question of copying the shiny new JDK somewhere. For\nexample:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>sudo<span class=\"w\"> <\/span>cp<span class=\"w\"> <\/span>-a<span class=\"w\"> <\/span>build\/linux-amd64\/j2sdk-image<span class=\"w\"> <\/span>\/opt\/jdk8lambda\n<\/code><\/pre><\/div>\n\n<p>(If you&rsquo;re on a different architecture, change <em>linux-amd64<\/em> as needed.)<\/p>\n<h3>Test it!<\/h3>\n<p>Let&rsquo;s test both closures and defender methods at the same time:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\">\/\/ TestLambda.java<\/span>\n<span class=\"kn\">import<\/span><span class=\"w\"> <\/span><span class=\"nn\">java.util.concurrent.Callable<\/span><span class=\"p\">;<\/span>\n\n<span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kd\">class<\/span> <span class=\"nc\">TestLambda<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kd\">static<\/span><span class=\"w\"> <\/span><span class=\"n\">String<\/span><span class=\"w\"> <\/span><span class=\"nf\">sayHi<\/span><span class=\"p\">(<\/span><span class=\"n\">A<\/span><span class=\"w\"> <\/span><span class=\"n\">a<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">                <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;Hello from &quot;<\/span><span class=\"w\"> <\/span><span class=\"o\">+<\/span><span class=\"w\"> <\/span><span class=\"n\">a<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">        <\/span><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kd\">static<\/span><span class=\"w\"> <\/span><span class=\"kd\">interface<\/span> <span class=\"nc\">A<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">                <\/span><span class=\"n\">String<\/span><span class=\"w\"> <\/span><span class=\"nf\">sayHi<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"k\">default<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">sayHi<\/span><span class=\"p\">(<\/span><span class=\"k\">this<\/span><span class=\"p\">);<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">        <\/span><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kd\">static<\/span><span class=\"w\"> <\/span><span class=\"kd\">class<\/span> <span class=\"nc\">AImpl<\/span><span class=\"w\"> <\/span><span class=\"kd\">implements<\/span><span class=\"w\"> <\/span><span class=\"n\">A<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">        <\/span><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kd\">static<\/span><span class=\"w\"> <\/span><span class=\"kt\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">main<\/span><span class=\"p\">(<\/span><span class=\"n\">String<\/span><span class=\"o\">[]<\/span><span class=\"w\"> <\/span><span class=\"n\">args<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"kd\">throws<\/span><span class=\"w\"> <\/span><span class=\"n\">Exception<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">                <\/span><span class=\"n\">Callable<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">String<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">c<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">AImpl<\/span><span class=\"p\">().<\/span><span class=\"na\">sayHi<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">                <\/span><span class=\"n\">System<\/span><span class=\"p\">.<\/span><span class=\"na\">out<\/span><span class=\"p\">.<\/span><span class=\"na\">println<\/span><span class=\"p\">(<\/span><span class=\"n\">c<\/span><span class=\"p\">.<\/span><span class=\"na\">call<\/span><span class=\"p\">());<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Note that the <code>AImpl<\/code> class is empty! Also note the lambda operator\n<code>-&gt;<\/code>, which is similar to the one in C#, <code>=&gt;<\/code> (and identical to the one\nin F# :-)).<\/p>\n<p>Since Project Lambda doesn&rsquo;t introduce functional interfaces, we have to\nuse existing interfaces. In the example above, I chose to use\n<code>Callable&lt;String&gt;<\/code> as something that takes no arguments and returns a\n<code>String<\/code> value. A consequence of this choice is that I have to let the\nmain method throw all exceptions.<\/p>\n<p>Compile and run:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>\/opt\/jdk8lambda\/bin\/javac<span class=\"w\"> <\/span>TestLambda.java\n$<span class=\"w\"> <\/span>\/opt\/jdk8lambda\/bin\/java<span class=\"w\"> <\/span>TestLambda\nHello<span class=\"w\"> <\/span>from<span class=\"w\"> <\/span>TestLambda<span class=\"nv\">$AImpl<\/span>@46bd530\n<\/code><\/pre><\/div>\n\n<p>Very nice indeed! :-)<\/p>\n<p><strong>Update 2011-12-16<\/strong>: As pointed out to me <a href=\"http:\/\/mail.openjdk.java.net\/pipermail\/lambda-dev\/2011-December\/004404.html\">on the lambda-dev mailing\nlist<\/a>, defender methods are not supported by the JVM just yet, so that\nthe case above works anyway is a &ldquo;lucky accident&rdquo;. Therefore the class\nfiles should be statically woven before running:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>\/opt\/jdk8lambda\/bin\/javac<span class=\"w\"> <\/span>TestLambda.java\n$<span class=\"w\"> <\/span>\/opt\/jdk8lambda\/bin\/java<span class=\"w\"> <\/span>-cp<span class=\"w\"> <\/span>..\/defender-prototype\/distrib\/jsr335-agent.jar:..\/defender-prototype\/lib\/asm-4.0.jar<span class=\"w\"> <\/span>jsr335.agent.Main<span class=\"w\"> <\/span>-d<span class=\"w\"> <\/span>woven<span class=\"w\"> <\/span>--jdk<span class=\"w\"> <\/span>\/opt\/jdk8lambda<span class=\"w\"> <\/span>TestLambda*.class\n$<span class=\"w\"> <\/span><span class=\"nb\">cd<\/span><span class=\"w\"> <\/span>woven\n$<span class=\"w\"> <\/span>\/opt\/jdk8lambda\/bin\/java<span class=\"w\"> <\/span>TestLambda\nHello<span class=\"w\"> <\/span>from<span class=\"w\"> <\/span>TestLambda<span class=\"nv\">$AImpl<\/span>@46bd530\n<\/code><\/pre><\/div>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"closures"}},{"@attributes":{"term":"defender methods"}},{"@attributes":{"term":"jdk8"}}]},{"title":"Forcing a .NET application to use a 4.0 CLR","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/forcing-a-net-application-to-use-a-40-clr.html","rel":"alternate"}},"published":"2011-12-14T08:26:00+01:00","updated":"2011-12-14T08:26:00+01:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2011-12-14:\/forcing-a-net-application-to-use-a-40-clr.html","summary":"<p>I was in a situation where I had an application built with .NET 3.5, but\nthe application needed to launch a sub system build with .NET 4.0. This\ndidn&rsquo;t work, obviously, as the 3.5 CLR refused to load the 4.0\nassemblies. My first idea was \u2026<\/p>","content":"<p>I was in a situation where I had an application built with .NET 3.5, but\nthe application needed to launch a sub system build with .NET 4.0. This\ndidn&rsquo;t work, obviously, as the 3.5 CLR refused to load the 4.0\nassemblies. My first idea was to create some sort of COM bridge, which\nturned out to <a href=\"http:\/\/code.msdn.microsoft.com\/windowsdesktop\/Using-a-NET-4-Based-DLL-bb141db3\">exist already<\/a>. <em>Luckily<\/em>, I couldn&rsquo;t get the bridge to\nwork when the launching assembly was a Windows Forms Application. I say\nluckily, as I then encountered a much, much simpler solution.<\/p>\n<p>The key is <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ee518876.aspx\">In-Process Side-by-Side Execution<\/a>, which means that\nseveral CLR versions can be hosted within the same process. Thus, all I\nhad to do was to add the <code>supportedRuntime<\/code> element to the <code>app.config<\/code>\nfile of the main application:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nt\">&lt;configuration&gt;<\/span>\n<span class=\"w\">   <\/span><span class=\"nt\">&lt;startup&gt;<\/span>\n<span class=\"w\">      <\/span><span class=\"nt\">&lt;supportedRuntime<\/span><span class=\"w\"> <\/span><span class=\"na\">version=<\/span><span class=\"s\">&quot;v4.0&quot;<\/span><span class=\"nt\">\/&gt;<\/span>\n<span class=\"w\">   <\/span><span class=\"nt\">&lt;\/startup&gt;<\/span>\n<span class=\"nt\">&lt;\/configuration&gt;<\/span>\n<\/code><\/pre><\/div>\n\n<p>Without that element, the application would use the CLR for which it was\nbuilt, which was 3.5. With the element, it uses the 4.0 CLR and happily\nloads the sub system assemblies built with .NET 4.0.<\/p>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"clr"}},{"@attributes":{"term":"dotnet"}}]},{"title":"A convoluted way to list controllers per block device in Linux","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/a-convoluted-way-to-list-controllers-per-block-device-in-linux.html","rel":"alternate"}},"published":"2011-12-08T21:49:00+01:00","updated":"2011-12-08T21:49:00+01:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2011-12-08:\/a-convoluted-way-to-list-controllers-per-block-device-in-linux.html","summary":"<p>One of my SATA drives has failed and needs to be replaced. I have tried\nto find out if I can hot swap it instead of having to turn off the\ncomputer (which isn&rsquo;t a big deal, but it&rsquo;s nice if I don&rsquo;t have to), and\nthe \u2026<\/p>","content":"<p>One of my SATA drives has failed and needs to be replaced. I have tried\nto find out if I can hot swap it instead of having to turn off the\ncomputer (which isn&rsquo;t a big deal, but it&rsquo;s nice if I don&rsquo;t have to), and\nthe answer seems to be that while Linux should handle hot swapping just\nfine, the outcome really depends on the SATA controller.<\/p>\n<p>So there should be a simple command that lists the controller for any\ngiven block device, right? Perhaps there is, or perhaps there is some\nsimple few-step process to do it. But my Google-fu must be weak right\nnow, because I cannot find any <em>easy<\/em> or <em>simple<\/em> way to achieve what I\nwant.<\/p>\n<p>So I came up with the following quite convoluted way to do it:<\/p>\n<div class=\"gist\">\n    <script src='https:\/\/gist.github.com\/1448415.js?file=lsblkctrl.sh'><\/script>\n    <noscript>\n        <pre><code>#!\/bin\/bash\n\n# Lists Linux block devices and for each one the controller\n# it is connected to.\n\nset -o pipefail\n\nfor i in \/sys\/block\/sd*; do\n    # Find the path that contains the PCI ID of the controller.\n    link=$(readlink $i)\n    # Assume that the PCI ID of the controller is the path part\n    # right before the \/host... part.\n    parts=($(echo $link | sed -e 's,\/host.*,,' | tr \"\/\" \"\\n\"))\n    # The PCI ID of the controller should now be the last item\n    # in the array.\n    pciid=${parts[-1]}\n    # Get the device description from the PCI ID.\n    ctrl=$(lspci -s $pciid 2>\/dev\/null | sed -e 's\/.*: \/\/')\n    # Print the result if lspci suceeeded (it doesn't for a block\n    # device connected to USB).\n    test $? -eq 0 && echo $i: $ctrl\ndone\n<\/code><\/pre>\n    <\/noscript>\n<\/div>\n<p>I have tested it successfully on my main Ubuntu server (the one that has\nthe failed disk) and one of my virtual Ubuntu servers. On another\nvirtual Ubuntu server <code>\/sys\/block<\/code> isn&rsquo;t available, and <code>bash<\/code> is old\nenough to not recognize -1 as a valid array subscript. YMMV!<\/p>","category":[{"@attributes":{"term":"Sysadmin"}},{"@attributes":{"term":"bash"}},{"@attributes":{"term":"controller"}},{"@attributes":{"term":"device"}}]},{"title":"Serializing non-qualified attributes with ElementTree","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/serializing-non-qualified-attributes-with-elementtree.html","rel":"alternate"}},"published":"2011-11-21T23:41:00+01:00","updated":"2011-11-21T23:41:00+01:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2011-11-21:\/serializing-non-qualified-attributes-with-elementtree.html","summary":"<p>The other day, I had a piece of Python code that deserialized an XML\ntext containing a UPnP service description to an <a href=\"http:\/\/docs.python.org\/library\/xml.etree.elementtree.html\" title=\"ElementTree API\">ElementTree<\/a>\ninstance using <code>ElementTree.parse<\/code>, then at a later stage serialized it\nback to XML using <code>ElementTree.write<\/code>.<\/p>\n<p>Now, the service description happened to contain non-qualified\nattributes (like \u2026<\/p>","content":"<p>The other day, I had a piece of Python code that deserialized an XML\ntext containing a UPnP service description to an <a href=\"http:\/\/docs.python.org\/library\/xml.etree.elementtree.html\" title=\"ElementTree API\">ElementTree<\/a>\ninstance using <code>ElementTree.parse<\/code>, then at a later stage serialized it\nback to XML using <code>ElementTree.write<\/code>.<\/p>\n<p>Now, the service description happened to contain non-qualified\nattributes (like this: <code>&lt;stateVariable sendEvents=\"no\"&gt;<\/code>), which caused\nthe serialization to raise an error with the message &ldquo;<strong>cannot use\nnon-qualified names with default_namespace option<\/strong>.&rdquo; Googling around a\nbit didn&rsquo;t help much, since not many seem to have had this problem, or\nthere is no good solution to be found. (A few days later, this <a href=\"http:\/\/xkcd.com\/979\/\">XKCD\nstrip<\/a> was published. Spot on!)<\/p>\n<p>So, inspired by example code at <a href=\"http:\/\/effbot.org\/zone\/element-namespaces.htm\">effbot.org<\/a>, I wrote the following\nworkaround that simple updates each non-qualified attribute with the\nnamespace of its parent element during parsing. This is most\ndefinitively not a <em>proper<\/em> solution, but it works in my case. Perhaps\nit&rsquo;ll help somebody else too!<\/p>\n<div class=\"gist\">\n    <script src='https:\/\/gist.github.com\/1381912.js?file=et_patch.py'><\/script>\n    <noscript>\n        <pre><code>#!\/usr\/bin\/python\n\nfrom xml.etree import ElementTree as ET\nfrom cStringIO import StringIO\n\ndef parse_attrns(file):\n    \"\"\"Parse file to ElementTree instance. Patch non-prefixed attributes\n    with the namespace of the element they belong to.\n    \"\"\"\n    events = (\"start\", )\n    root = None\n    for event, elem in ET.iterparse(file, events):\n        if event == \"start\":\n            if root is None:\n                root = elem\n            if elem.tag.find(\"}\") < 0:\n                continue\n            # inherit the uri from the element\n            uri, _ = elem.tag[1:].rsplit(\"}\", 1)\n            for k, v in elem.attrib.items():\n                if k[:1] != \"{\":\n                    # replace the old attribute with a namespace-prefixed one\n                    del elem.attrib[k]\n                    k = \"{%s}%s\" % (uri, k)\n                    elem.attrib[k] = v\n    return ET.ElementTree(root)\n\nclass fileobj(object):\n    def __init__(self, l):\n        self.write = l.append\n\ndef roundtrip(xml, dns=None):\n    \"\"\"Deserialize XML using ElementTree, then serialize it again.\n\n    >>> roundtrip('<a xmlns=\"foo\"><b id=\"1\" \/><\/a>', dns='foo')\n    '<a xmlns=\"foo\"><b id=\"1\" \/><\/a>'\n\n    >>> roundtrip('<a><b id=\"1\" \/><\/a>', dns='foo')\n    Traceback (most recent call last):\n        ...\n    ValueError: cannot use non-qualified names with default_namespace option\n\n    >>> roundtrip('<a><b id=\"1\" \/><\/a>')\n    '<a><b id=\"1\" \/><\/a>'\n\n    \"\"\"\n    #e = ET.parse(StringIO(xml))\n    e = parse_attrns(StringIO(xml))\n    data = []\n    e.write(fileobj(data), default_namespace=dns)\n    return \"\".join(data)\n\nif __name__ == \"__main__\":\n    import doctest\n    doctest.testmod()\n<\/code><\/pre>\n    <\/noscript>\n<\/div>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"elementtree"}},{"@attributes":{"term":"hack"}},{"@attributes":{"term":"python"}}]},{"title":"OpenCover in Jenkins","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/opencover-in-jenkins.html","rel":"alternate"}},"published":"2011-10-24T13:49:00+02:00","updated":"2011-10-24T13:49:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2011-10-24:\/opencover-in-jenkins.html","summary":"<p>I just updated my <a href=\"http:\/\/ci.finkod.se\/job\/TestNess\/\">Jenkins job<\/a> for <a href=\"http:\/\/www.testness.org\">TestNess<\/a> to use <a href=\"https:\/\/github.com\/sawilde\/opencover\">OpenCover<\/a>\nto measure code coverage.<\/p>\n<p>Previously, I used <a href=\"https:\/\/github.com\/sawilde\/partcover.net4\">PartCover<\/a>. The setup of PartCover was quite\npainful. The first error came when I tried to build the source code from\na directory path that contained a space. Then, I ran into \u2026<\/p>","content":"<p>I just updated my <a href=\"http:\/\/ci.finkod.se\/job\/TestNess\/\">Jenkins job<\/a> for <a href=\"http:\/\/www.testness.org\">TestNess<\/a> to use <a href=\"https:\/\/github.com\/sawilde\/opencover\">OpenCover<\/a>\nto measure code coverage.<\/p>\n<p>Previously, I used <a href=\"https:\/\/github.com\/sawilde\/partcover.net4\">PartCover<\/a>. The setup of PartCover was quite\npainful. The first error came when I tried to build the source code from\na directory path that contained a space. Then, I ran into some 32\/64 bit\nissues when I tested PartCover on my laptop. Finally, I found that the\n<code>--register<\/code> flag didn&rsquo;t work since my Jenkins slave service runs under\nthe SYSTEM account.<\/p>\n<p>OpenCover, on the other hand, was clearly less painful to setup. The\nonly problem was the following error message:<\/p>\n<p><code>No results - no assemblies that matched the supplied filter were instrumented (missing PDBs?)<\/code><\/p>\n<p>(Yeah, the lack of results was actually quite a big problem&hellip; :-))<\/p>\n<p>Using <a href=\"http:\/\/dependencywalker.com\/\">Dependency Walker<\/a>, I found out that DLL registration (of\nOpenCover.Profiler.dll) failed because some DLLs were missing from the\nsystem. It turns out I needed to download and install <a href=\"http:\/\/www.microsoft.com\/download\/en\/details.aspx?id=5555\">Microsoft Visual\nC++ 2010 Redistributable Package (x86)<\/a>.<\/p>\n<p>Once OpenCover has done its job, I use <a href=\"http:\/\/www.palmmedia.de\/Net\/ReportGenerator\">ReportGenerator<\/a> to create an\nHTML report which is subsequently published by the HTML Publisher\nplugin.<\/p>","category":[{"@attributes":{"term":"Tools"}},{"@attributes":{"term":"ci"}},{"@attributes":{"term":"coverage"}},{"@attributes":{"term":"pain"}}]},{"title":"Code demo using git, part 2","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/code-demo-using-git-part-2.html","rel":"alternate"}},"published":"2011-10-17T09:46:00+02:00","updated":"2011-10-17T09:46:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2011-10-17:\/code-demo-using-git-part-2.html","summary":"<p>In my <a href=\"https:\/\/programmaticallyspeaking.com\/code-demo-using-git.html\">first post<\/a> about using Git for doing a code demo, I mentioned\nin passing that making local changes during the demo can mess things up.\nI thought I&rsquo;d mentioned some more about cleaning up local changes.<\/p>\n<h2>The cherry-pick method<\/h2>\n<p>Cleaning up local changes when using the cherry-pick \u2026<\/p>","content":"<p>In my <a href=\"https:\/\/programmaticallyspeaking.com\/code-demo-using-git.html\">first post<\/a> about using Git for doing a code demo, I mentioned\nin passing that making local changes during the demo can mess things up.\nI thought I&rsquo;d mentioned some more about cleaning up local changes.<\/p>\n<h2>The cherry-pick method<\/h2>\n<p>Cleaning up local changes when using the cherry-pick method is dead\nsimple. Just run:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>reset<span class=\"w\"> <\/span>--hard\n$<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>clean<span class=\"w\"> <\/span>-fd\n<\/code><\/pre><\/div>\n\n<p>The first command effectively discards all unstaged modifications,\nrestores deleted files and clears the staging area. The second command\nremoves all untracked files, including directories thanks to the -d\nflag. (By the way, I assume you have a good .gitignore file so that no\nimportant files get removed by accident!)<\/p>\n<h2>The interactive rebase method<\/h2>\n<p>Resetting local changes, including newly added files, is done the same\nway as with the other method. <em>However<\/em>, if you have made local changes,\nthen the rebase process has probably been aborted, and you are facing a\nmessage like the following one:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>Aborting (2\/3)\nerror: Your local changes to the following files would be overwritten by merge:\n        world.txt\nPlease, commit your changes or stash them before you can merge.\nCould not apply fcf2240... Second part of the demo\n<\/code><\/pre><\/div>\n\n<p>The problem here is that git thinks that it is done with the second demo\ncommit already, despite the failure! Therefore, a\n<code>git rebase --continue<\/code> at this point (after cleaning up) tries to\napply the <em>third<\/em> demo commit, which is definitively not what you want!<\/p>\n<p>An option is to use <em>edit<\/em> instead of <em>reword<\/em> in the interactive\nrebase. That way, you can reset local changes all you want, and then\nsimply do <code>git rebase --continue<\/code> to continue the demo. However, you\nneed to do <code>git rebase --continue<\/code> in any case, so the simplicity of\nthe interactive rebase method as originally envisioned sort of\ndisappears&hellip;<\/p>\n<h2>Which method is best? - revisited<\/h2>\n<p>In the light of the possibly complications arising from local changes\nusing the interactive rebase method, I&rsquo;d lean towards the cherry-pick\nmethod! But perhaps we can automate it with a little script to make\nthings simpler? Here&rsquo;s one attempt (that mostly relies on git to do\nerror-checking, so you might want to add some of that):<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"ch\">#!\/bin\/bash<\/span>\n\n<span class=\"nb\">set<\/span><span class=\"w\"> <\/span>-o<span class=\"w\"> <\/span>nounset\n<span class=\"nb\">set<\/span><span class=\"w\"> <\/span>-o<span class=\"w\"> <\/span>errexit\n\n<span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"o\">[[<\/span><span class=\"w\"> <\/span><span class=\"nv\">$#<\/span><span class=\"w\"> <\/span>-lt<span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"w\"> <\/span><span class=\"o\">]]<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"k\">then<\/span>\n<span class=\"w\">    <\/span><span class=\"nb\">echo<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;Please specify a demo template branch!&quot;<\/span>\n<span class=\"w\">    <\/span><span class=\"nb\">exit<\/span><span class=\"w\"> <\/span><span class=\"m\">1<\/span>\n<span class=\"k\">fi<\/span>\n\n<span class=\"nv\">branch<\/span><span class=\"o\">=<\/span><span class=\"nv\">$1<\/span>\n<span class=\"nv\">bhead<\/span><span class=\"o\">=<\/span><span class=\"k\">$(<\/span>git<span class=\"w\"> <\/span>show<span class=\"w\"> <\/span>-s<span class=\"w\"> <\/span>--format<span class=\"o\">=<\/span>format:%H<span class=\"w\"> <\/span><span class=\"nv\">$branch<\/span><span class=\"k\">)<\/span>\n<span class=\"nv\">mbase<\/span><span class=\"o\">=<\/span><span class=\"k\">$(<\/span>git<span class=\"w\"> <\/span>merge-base<span class=\"w\"> <\/span><span class=\"nv\">$bhead<\/span><span class=\"w\"> <\/span>HEAD<span class=\"k\">)<\/span>\n<span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"o\">[[<\/span><span class=\"w\"> <\/span><span class=\"nv\">$mbase<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"nv\">$bhead<\/span><span class=\"w\"> <\/span><span class=\"o\">]]<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"k\">then<\/span>\n<span class=\"w\">    <\/span><span class=\"nb\">echo<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;The demo template head is reachable from this branch. Please switch branch!&quot;<\/span>\n<span class=\"w\">    <\/span><span class=\"nb\">exit<\/span><span class=\"w\"> <\/span><span class=\"m\">1<\/span>\n<span class=\"k\">fi<\/span>\n\n<span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"nb\">hash<\/span><span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"k\">$(<\/span>git<span class=\"w\"> <\/span>log<span class=\"w\"> <\/span>--reverse<span class=\"w\"> <\/span>--format<span class=\"o\">=<\/span>format:%H<span class=\"w\"> <\/span>master..<span class=\"nv\">$branch<\/span><span class=\"k\">)<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"k\">do<\/span>\n<span class=\"w\">    <\/span>git<span class=\"w\"> <\/span>show<span class=\"w\"> <\/span>-s<span class=\"w\"> <\/span>--format<span class=\"o\">=<\/span>format:<span class=\"s2\">&quot;Applying %h (%s)...&quot;<\/span><span class=\"w\"> <\/span><span class=\"nv\">$hash<\/span>\n\n<span class=\"w\">    <\/span><span class=\"nb\">echo<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;-- cleaning up...&quot;<\/span>\n<span class=\"w\">    <\/span>git<span class=\"w\"> <\/span>reset<span class=\"w\"> <\/span>--hard\n<span class=\"w\">    <\/span>git<span class=\"w\"> <\/span>clean<span class=\"w\"> <\/span>-fd\n\n<span class=\"w\">    <\/span><span class=\"nb\">echo<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;-- cherry-picking...&quot;<\/span>\n<span class=\"w\">    <\/span>git<span class=\"w\"> <\/span>cherry-pick<span class=\"w\"> <\/span><span class=\"nv\">$hash<\/span>\n\n<span class=\"w\">    <\/span><span class=\"nb\">echo<\/span>\n<span class=\"w\">    <\/span><span class=\"nb\">read<\/span><span class=\"w\"> <\/span>-p<span class=\"w\"> <\/span><span class=\"s2\">&quot;Press any key to continue...&quot;<\/span>\n<span class=\"w\">    <\/span><span class=\"nb\">echo<\/span>\n<span class=\"k\">done<\/span>\n<\/code><\/pre><\/div>\n\n<p>(Note to self: Don&rsquo;t store a script that removes untracked files in the\ndirectory where you test run the script! :-))<\/p>\n<p>How does the script work? Well, first it checks that the head of the\nspecified demo template branch isn&rsquo;t reachable from the current branch\nhead. If it is, then most likely the current branch <em>is<\/em> the demo\ntemplate branch. Next, it iterates over the list of commits in the demo\ntemplate branch (in order of oldest first, thus <code>--reverse<\/code>). For each\ncommit, it performs some cleanup before cherry-picking the commit. Then\nit waits for you to carry out the demo of that particular commit before\ncontinuing. Simple, right?<\/p>\n<p>A final note about the script: It assumes that the demo template branch\nis branched out from master. If that&rsquo;s not the case, the demo ghost will\nhunt you. :-)<\/p>","category":[{"@attributes":{"term":"Tools"}},{"@attributes":{"term":"git demo"}}]},{"title":"Uniprocessor HAL to multiprocessor HAL in Windows","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/uniprocessor-hal-to-multiprocessor-hal-in-windows.html","rel":"alternate"}},"published":"2011-10-17T07:01:00+02:00","updated":"2011-10-17T07:01:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2011-10-17:\/uniprocessor-hal-to-multiprocessor-hal-in-windows.html","summary":"<p>The other day, I decided to &ldquo;upgrade&rdquo; my virtual Windows 2003 server by\ndoubling the memory size and adding an extra CPU. The memory was not an\nissue, of course, but the extra CPU turned out to be. Although Device\nManager picked up the correct number of CPUs under Processors \u2026<\/p>","content":"<p>The other day, I decided to &ldquo;upgrade&rdquo; my virtual Windows 2003 server by\ndoubling the memory size and adding an extra CPU. The memory was not an\nissue, of course, but the extra CPU turned out to be. Although Device\nManager picked up the correct number of CPUs under Processors, the HAL\nentry under Computer was still listed as &ldquo;<em>Advanced Configuration and\nPower Interface (ACPI) PC<\/em>.&rdquo; Opening Task Manager confirmed that only\none CPU was indeed being used. Back in Device Manager, I found no easily\naccessible option to upgrade the HAL.<\/p>\n<p>After googling a bit, I encountered <a href=\"http:\/\/www.pimp-my-rig.com\/2008\/08\/article-acpi-uniprocessor-to.html\">this wonderful blog post<\/a>, which\nsaved my day!<\/p>\n<p>Essentially, do as follows:<\/p>\n<ol>\n<li>Download <a href=\"http:\/\/support.microsoft.com\/kb\/311272\" title=\"Download link for devcon.exe @ Microsoft\">devcon.exe<\/a> [microsoft.com].<\/li>\n<li>Copy the script below and save it as a cmd file (say,\n    upgradehal.cmd).<\/li>\n<li>Run the script!<\/li>\n<\/ol>\n<p>All the normal HAL upgrade warnings apply, of course. Since my server\nwas running as a VM, I simply took a snapshot before upgrading.<\/p>\n<p>The script:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">@<\/span><span class=\"k\">echo<\/span> off\n<span class=\"p\">@<\/span><span class=\"k\">title<\/span> <span class=\"s2\">&quot;Upgrading to ACPI Multi-Processor HAL..&quot;<\/span>\n<span class=\"k\">cls<\/span>\n\n<span class=\"k\">echo<\/span> ====================================================\n<span class=\"k\">echo<\/span> Upgrading to ACPI Multi-Processor HAL..\n<span class=\"k\">echo<\/span> ====================================================\n<span class=\"k\">echo<\/span>.\n<span class=\"k\">echo<\/span> please wait..\n\ndevcon sethwid @ROOT\\PCI_HAL\\0000 := <span class=\"nv\">!E_ISA_UP !<\/span>ACPIPIC_UP <span class=\"nv\">!ACPIAPIC_UP !<\/span>ACPIAPIC_MP <span class=\"nv\">!MPS_UP !<\/span>MPS_MP <span class=\"nv\">!SGI_MPS_MP !<\/span>SYSPRO_MP !SGI_MPS_MP <span class=\"p\">&gt;<\/span> nul\ndevcon sethwid @ROOT\\ACPI_HAL\\0000 := <span class=\"nv\">!E_ISA_UP !<\/span>ACPIPIC_UP <span class=\"nv\">!ACPIAPIC_UP !<\/span>ACPIAPIC_MP <span class=\"nv\">!MPS_UP !<\/span>MPS_MP <span class=\"nv\">!SGI_MPS_MP !<\/span>SYSPRO_MP !SGI_MPS_MP <span class=\"p\">&gt;<\/span> nul\ndevcon sethwid @ROOT\\PCI_HAL\\0000 := +ACPIAPIC_MP <span class=\"p\">&gt;<\/span> nul\ndevcon sethwid @ROOT\\ACPI_HAL\\0000 := +ACPIAPIC_MP <span class=\"p\">&gt;<\/span> nul\ndevcon update <span class=\"nv\">%windir%<\/span>\\inf\\hal.inf ACPIAPIC_MP <span class=\"p\">&gt;<\/span> nul\n\n<span class=\"k\">echo<\/span>.\n<span class=\"k\">echo<\/span> ====================================================\n<span class=\"k\">echo<\/span> Script Completed: press any key to reboot..\n<span class=\"k\">echo<\/span> ====================================================\n\n<span class=\"k\">pause<\/span> <span class=\"p\">&gt;<\/span> nul\n\ndevcon reboot\n<\/code><\/pre><\/div>\n\n<p>After the reboot, the HAL entry under Computer in Device Manager now\nread &ldquo;<em>ACPI Multiprocessor PC<\/em>,&rdquo; and Task Manager showed two CPUs being\nused. Voil&agrave;! :-)<\/p>","category":[{"@attributes":{"term":"Tools"}},{"@attributes":{"term":"hal"}},{"@attributes":{"term":"multiprocessor"}},{"@attributes":{"term":"windows"}}]},{"title":"My .screenrc","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/my-screenrc.html","rel":"alternate"}},"published":"2011-10-17T06:48:00+02:00","updated":"2011-10-17T06:48:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2011-10-17:\/my-screenrc.html","summary":"<p>Posted mostly for my own sake, since I need it each time I create a new\nVM, and I always end up googling for it.<\/p>\n<p>I found my favorite .screenrc <a href=\"http:\/\/more-plugins.se\/2008\/05\/02\/a-favorite-screenrc-setting\/\">here<\/a>. For easy copying:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>vbell off\nautodetach on\ndefscrollback 10000\nstartup_message off\npow_detach_msg &quot;Screen session of \\$LOGNAME \\$:cr:\\$:nl:ended \u2026<\/code><\/pre><\/div>","content":"<p>Posted mostly for my own sake, since I need it each time I create a new\nVM, and I always end up googling for it.<\/p>\n<p>I found my favorite .screenrc <a href=\"http:\/\/more-plugins.se\/2008\/05\/02\/a-favorite-screenrc-setting\/\">here<\/a>. For easy copying:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>vbell off\nautodetach on\ndefscrollback 10000\nstartup_message off\npow_detach_msg &quot;Screen session of \\$LOGNAME \\$:cr:\\$:nl:ended.&quot;\ncaption always &quot;%{= gk}%-Lw%{= rW}%50&gt; %n%f* %t %{-}%+Lw%&lt; %= %{= Gk} %H %{= rW} %l %{= Gk} %0c:%s %d\/%m %{-}&quot;\nshell -$SHELL\n<\/code><\/pre><\/div>","category":[{"@attributes":{"term":"Tools"}},{"@attributes":{"term":"screen"}}]},{"title":"Code demo using git","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/code-demo-using-git.html","rel":"alternate"}},"published":"2011-10-10T19:27:00+02:00","updated":"2011-10-10T19:27:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2011-10-10:\/code-demo-using-git.html","summary":"<p>I&rsquo;m very fond of <a href=\"http:\/\/git-scm.com\/\">git<\/a> for many reasons, one being its changeset-based\ncommit model. Today I ran a demo of some code for a customer, and I used\ngit as a demo driver - much like a TV chef brings out stuff he or she\nhas prepared earlier. There are \u2026<\/p>","content":"<p>I&rsquo;m very fond of <a href=\"http:\/\/git-scm.com\/\">git<\/a> for many reasons, one being its changeset-based\ncommit model. Today I ran a demo of some code for a customer, and I used\ngit as a demo driver - much like a TV chef brings out stuff he or she\nhas prepared earlier. There are at least two ways to run a demo using\ngit:<\/p>\n<ul>\n<li>by cherry-picking commits, and<\/li>\n<li>by using interactive rebase.<\/li>\n<\/ul>\n<p>Let&rsquo;s see how they both work! Suppose we have a separate branch, <em>demo<\/em>,\nthat contains the code we want to demo:<\/p>\n<p><img alt=\"Demo commits\" src=\".\/images\/git-commits.png\" title=\"git-commits\" \/><\/p>\n<p>The demo code consists of three separate commits.<\/p>\n<h3>The cherry-pick method<\/h3>\n<p>To use this method, start by creating a new branch based on master:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>checkout<span class=\"w\"> <\/span>-b<span class=\"w\"> <\/span>demo_impl<span class=\"w\"> <\/span>master\n<\/code><\/pre><\/div>\n\n<p>Next, obtain a listing of the commits that are in the original demo\nbranch:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>log<span class=\"w\"> <\/span>--format<span class=\"o\">=<\/span>oneline<span class=\"w\"> <\/span>master..demo\nb246a365af2476fdef2887d42b3f977d1526ec82<span class=\"w\"> <\/span>Third<span class=\"w\"> <\/span>part<span class=\"w\"> <\/span>of<span class=\"w\"> <\/span>the<span class=\"w\"> <\/span>demo\n368176859ef87c81549ffebd2d79e98833f892e7<span class=\"w\"> <\/span>Second<span class=\"w\"> <\/span>part<span class=\"w\"> <\/span>of<span class=\"w\"> <\/span>the<span class=\"w\"> <\/span>demo\nfa9ef86b53126428ba8859d2e7dc3818efbd9243<span class=\"w\"> <\/span>First<span class=\"w\"> <\/span>part<span class=\"w\"> <\/span>of<span class=\"w\"> <\/span>the<span class=\"w\"> <\/span>demo\n<\/code><\/pre><\/div>\n\n<p>Then, as part of the demo, cherry-pick one commit at a time from the\noriginal demo branch:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>cherry-pick<span class=\"w\"> <\/span>fa9ef86b53126428ba8859d2e7dc3818efbd9243\n<\/code><\/pre><\/div>\n\n<p><strong>Advantages<\/strong>:<\/p>\n<ul>\n<li>The demo takes place in a branch separate from the original demo\n    branch, which thus becomes a &ldquo;template&rdquo; that you cannot mess up.<\/li>\n<li>If you change the code as part of the demo, you need to clean the\n    local changes before you can continue. There&rsquo;s no risk that you\n    inadvertently sabotage the demo. (To abort a cherry-pick gone wrong,\n    do <code>git reset --merge<\/code>.)<\/li>\n<\/ul>\n<p><strong>Disadvantages<\/strong>:<\/p>\n<ul>\n<li>You need to keep a copy of the commit list to copy commit sha1s\n    from.<\/li>\n<li>There&rsquo;s much disruption in the form of typing and\/or using the mouse\n    inbetween demo steps.<\/li>\n<\/ul>\n<h3>The interactive rebase method<\/h3>\n<p>Working in the demo branch, start an interactive rebase for the three\ncommits:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>rebase<span class=\"w\"> <\/span>-i<span class=\"w\"> <\/span>HEAD~3\n<\/code><\/pre><\/div>\n\n<p>In the interactive rebase instruction, choose <em>reword<\/em> (r) for all three\ncommits:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>r fa9ef86 First part of the demo\nr 3681768 Second part of the demo\nr b246a36 Third part of the demo\n<\/code><\/pre><\/div>\n\n<p>Start the interactive rebase by saving the instruction and quitting the\neditor. Now, git applies each commit in turn, and then waits for you to\nedit the commit message. To continue the demo, simply quit the commit\nmessage editor without making any changes.<\/p>\n<p><strong>Advantages<\/strong>:<\/p>\n<ul>\n<li>Very little &ldquo;demo overhead&rdquo; - all you have to do is switch to the\n    commit message editor and quit editing.<\/li>\n<\/ul>\n<p><strong>Disadvantages<\/strong>:<\/p>\n<ul>\n<li>Since you do the interactive rebase in the original demo branch,\n    there&rsquo;s a risk that you mess things up. I did this by making some\n    local changes as part of the demo, then did a <code>git reset --hard<\/code>\n    when git told me that it couldn&rsquo;t continue with the rebase. The\n    commit was lost. Whoops! (Thankfully, <code>git fsck --lost-found<\/code>\n    saved the day.)<\/li>\n<\/ul>\n<h3>Which method is best?<\/h3>\n<p>Personally, I find the simplicity of the interactive rebase method\nappealing. But if you&rsquo;re afraid of messing up the commit history, go for\nthe cherry-pick method! (As an added bonus, the cherry-pick method lets\nyou skip demo steps if that for some reason makes sense in your\ncontext.)<\/p>\n<p><strong>Update 2011-10-17<\/strong>: Posted a <a href=\"https:\/\/programmaticallyspeaking.com\/code-demo-using-git-part-2.html\">follow-up<\/a> to this!<\/p>","category":[{"@attributes":{"term":"Tools"}},{"@attributes":{"term":"demo"}},{"@attributes":{"term":"git"}}]},{"title":"Cancer.js?","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/cancerjs.html","rel":"alternate"}},"published":"2011-10-06T08:13:00+02:00","updated":"2011-10-06T08:13:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2011-10-06:\/cancerjs.html","summary":"<p>A colleague made me aware of <a href=\"https:\/\/plus.google.com\/115094562986465477143\/posts\/Di6RwCNKCrf\">this post<\/a> by Ryan Dahl, the author of\nNode.js, where he complains that most software is overly complicated,\nthat the whole software situation is messed up and that all that matters\nis the end user experience. In a response to his own post \u2026<\/p>","content":"<p>A colleague made me aware of <a href=\"https:\/\/plus.google.com\/115094562986465477143\/posts\/Di6RwCNKCrf\">this post<\/a> by Ryan Dahl, the author of\nNode.js, where he complains that most software is overly complicated,\nthat the whole software situation is messed up and that all that matters\nis the end user experience. In a response to his own post, he openly\nadmits that Node.js is also too complex. But what turns out to be\ninteresting is that his post contains a rant about the complexity of\nUnix and the software built on top of it.<\/p>\n<p><a href=\"http:\/\/teddziuba.com\/2011\/10\/node-js-is-cancer.html\">This guy<\/a> took offense by the Unix rant and calls Node.js a cancer,\nand goes on to say that the seemingly all-accepted premise that\nasynchronous I\/O and an event loop saves the day is not true. (I think\nhe missed the point of the original post, but took the chance to release\nsome steam!) Anyway, to make his point he writes a tiny Node.js server\nthat computes a <a href=\"http:\/\/en.wikipedia.org\/wiki\/Fibonacci_number\">Fibonacci number<\/a> in a CPU-intensive way using a\nsimple recursive algorithm, demonstrating the possibility to &ldquo;block&rdquo;\neven with Node.js (though technically, blocking is probably the wrong\nterm).<\/p>\n<p>Finally, someone created <a href=\"https:\/\/github.com\/glenjamin\/node-fib\">node-fib<\/a> to show that it&rsquo;s indeed possibly\nto calculate a Fibonacci number recursively using Node.js without\n&ldquo;blocking&rdquo;.<\/p>\n<p>All of this got me thinking. First off, I too believe that much software\nis overly complicated, and that any software program of age is bound to\ncontain a lot of accidental complexity. While this can be caused by bad\ndecision-making, sloppy coding or over-ambition, it&rsquo;s also the case that\nmany decisions were probably sound in their context and it&rsquo;s only over\ntime that they have become obsolete and in retrospect diverging (the\nsaying &ldquo;the road to hell is paved with good intentions&rdquo; comes to mind,\nalthough it may be a bit harsh). Can we make perfect software from the\nbeginning? Of course not! We have to accept that we learn over time, and\nwhat we can do is to be agile:<\/p>\n<ul>\n<li>Abandon bad ideas and bad designs as soon as we realize that they\n    are bad.<\/li>\n<li>Write simple code that doesn&rsquo;t solve problems of the future (I think\n    it&rsquo;s ok to plan ahead though, but what that means is a different\n    discussion).<\/li>\n<li>Refactor the code as soon as we detect problems with it.<\/li>\n<\/ul>\n<p>Of course, software that has been released is not always easy to change,\nsince we have to assume that users now depend on all APIs, good or bad.\nBut if we keep it simple, our APIs hopefully won&rsquo;t be that bad.<\/p>\n<p>On to Node.js being a cancer. Is that true? I don&rsquo;t think so, but\nperhaps it has been over-used, over-exposed or over-something&hellip; I&rsquo;ve\nused the <a href=\"http:\/\/twistedmatrix.com\/trac\/\">Twisted<\/a> framework for Python a bit, and I like asynchronous\nI\/O and event loops! I find that thinking asynchronously results in a\nnice mental model of the software I&rsquo;m writing. It&rsquo;s almost declarative!\nBut I know that even if I have a hammer, not everything is a nail! There\nare certain problems that lend themselves well to being solved in an\nasynchronous way, and there are problems that do not. It&rsquo;s always\npossible to solve a problem using the wrong solution, and I think the\nkey is to constantly <em>question<\/em> what your&rsquo;re doing.<\/p>\n<p>Finally, node-fib. Well, it&rsquo;s just messy! With the algorithm intertwined\nwith the asynchronous infrastructure, the readability is drastically\nlowered. And if the readability of code is low, the code is not simple.\nPeriod! But what I find interesting about node-fib is the class of\nproblems it tries to solve, namely to instrument the code that performs\na lengthy operation in a way that disrupts the atomicity of the\noperation. Node-fib chops the algorithm into pieces so that it can be\nexecuted a little at a time. In one project, I instrumented an algorithm\nwith progress reporting to ultimately be able to show a progress bar in\na GUI. In both cases, the code that contains the algorithm is no longer\n&ldquo;clean&rdquo; and easily understandable. Its simplicity has been reduced\nthrough the introduction of dependencies on <em>infrastructure<\/em>. Apart from\nAspect-Oriented Programming, which is only applicable in some specific\nsituations and has its own <del>problems<\/del>challenges, I don&rsquo;t know of\nanything that lets you keep the algorithm entirely intact and\ninfrastructure-free. As with everything else, it&rsquo;s a trade-off!<\/p>","category":[{"@attributes":{"term":"Opinion"}},{"@attributes":{"term":"algorithm"}},{"@attributes":{"term":"complexity"}},{"@attributes":{"term":"infrastructure"}}]},{"title":"When security gets in your face","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/when-security-gets-in-your-face.html","rel":"alternate"}},"published":"2011-10-02T00:12:00+02:00","updated":"2011-10-02T00:12:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2011-10-02:\/when-security-gets-in-your-face.html","summary":"<p>When I started writing <a href=\"https:\/\/programmaticallyspeaking.com\/test-data-provider-using-python-metaclass.html\">that post<\/a>, I kept getting HTTP 406 Not\nAcceptable errors from the web server as I tried to preview it or save a\ndraft. I managed to narrow down the cause of the problem to two\nseemingly innocent words: <em>test<\/em> and <em>method<\/em>. Whenever my post\ncontained \u2026<\/p>","content":"<p>When I started writing <a href=\"https:\/\/programmaticallyspeaking.com\/test-data-provider-using-python-metaclass.html\">that post<\/a>, I kept getting HTTP 406 Not\nAcceptable errors from the web server as I tried to preview it or save a\ndraft. I managed to narrow down the cause of the problem to two\nseemingly innocent words: <em>test<\/em> and <em>method<\/em>. Whenever my post\ncontained &ldquo;test method&rdquo; (separated by a single space), I would get the\nerror. The workaround was quite simply to use two spaces instead of one\n(in code snippets, this didn&rsquo;t look good though).<\/p>\n<p>A bit of googling suggested that Apache&rsquo;s mod_security might be the\nculprit. A quick test script ruled out the blog software. I contacted my\nhosting provider, <a href=\"http:\/\/www.oderland.se\/\">Oderland<\/a>, to see if they could help me. They\nquickly responded that yes, it was indeed a default mod_security rule\nthat caused the problem. After they removed the rule, I could post &ldquo;test\nmethod&rdquo; again. Frankly, this was quite a relief - it&rsquo;s difficult to\nwrite about programming and testing without mentioning test methods!<\/p>\n<p>Kudos to Oderland support staff for fixing the problem at 9 pm a\nSaturday evening!<\/p>","category":{"@attributes":{"term":"Sysadmin"}}},{"title":"On discovering Test-Driven Development","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/on-discovering-test-driven-development.html","rel":"alternate"}},"published":"2011-10-01T23:51:00+02:00","updated":"2011-10-01T23:51:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2011-10-01:\/on-discovering-test-driven-development.html","summary":"<p>Test-Driven Development (TDD) is a programming practice that to me is an\nimmensely useful quality assurance tool. In brief, TDD is about writing\nunit tests first and letting the unit tests drive the design of your\ncode. Some of the most important benefits are:<\/p>\n<ul>\n<li>The public API your create becomes \u2026<\/li><\/ul>","content":"<p>Test-Driven Development (TDD) is a programming practice that to me is an\nimmensely useful quality assurance tool. In brief, TDD is about writing\nunit tests first and letting the unit tests drive the design of your\ncode. Some of the most important benefits are:<\/p>\n<ul>\n<li>The public API your create becomes usable and testable.<\/li>\n<li>Test coverage becomes very high, because you wouldn&rsquo;t add any code\n    without writing a test for it first.<\/li>\n<li>You catch nasty surprises early (read on for an example).<\/li>\n<li>You build a safety net that allows you to refactor your code later\n    on, knowing that you won&rsquo;t introduce bugs.<\/li>\n<\/ul>\n<p>Surprisingly, many people don&rsquo;t use TDD, presumably because they don&rsquo;t\nknow about the benefits (because if they did, why would they NOT use\nTDD?). The most common argument against using TDD that I have\nencountered is &ldquo;but I don&rsquo;t know which tests to write, I need to\nexperiment a bit with the code first.&rdquo; My response is usually that with\nTDD, they can experiment all they want with the added benefit that they\nknow when they are finished (when the unit tests are all green) or when\nthe experimentation has taken them off course (when the unit tests are\nNOT all green).<\/p>\n<p>Recently, I had a discussion with a customer about TDD. The person told\nme that there had been no company-wide directive to use TDD, so they\ndidn&rsquo;t. (But here had been one project in which they sort of &ldquo;piloted&rdquo;\nTDD, and it didn&rsquo;t work out so well.) For some reason, this resonated so\nbadly with me, and I soon figured out why. I have always considered TDD\nto be a personal tool that I as a programmer can use to be a better\nprogrammer, to write better code. And to be adept with any tool, you\nneed to familiarize yourself with the tool and practice using it. You\ncannot just be told to use it. But you can be encouraged to!<\/p>\n<p>So if you don&rsquo;t already use TDD, I encourage you to do so! It will be a\ndifficult journey with many obstacles, because TDD is really, really\nhard to master. Heck, writing a unit test regardless of methodology is\nhard enough already. But in the end, when you have added TDD to your\ntool belt, you will find it to be very powerful! And at this point,\nusing TDD will be part of your job as a programmer. Put in other words,\nTDD will be something you use for you own sake, and nobody else can\ncontrol whether or not you use it.<\/p>\n<p>I will end with a short story: A few days ago, I wrote unit tests for a\npretty simple value object class with three properties. The class\nnaturally implemented <code>GetHashCode<\/code> and <code>Equals<\/code> (it was a .NET class).\nWould you write unit tests for those methods? If you did, would you\ntest-drive them even? Perhaps to some people, these are methods that are\nso much infrastructure that writing tests for them is a waste of time,\nespecially since they can be automatically generated. But I test-drove\nthem, being the TDD addict that I am. And it totally saved my day! You\nsee, in Java I would let Eclipse generate the <code>hashCode<\/code> method, and the\npattern it generates is to start with a small hash value and for each\nproperty multiply the hash code of the property with a prime and add to\nthe hash value. I implemented the same approach in my value object\nclass, ran the unit tests and watched them go red! What happened? My\n<code>GetHashCode<\/code> implementation threw an <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.overflowexception.aspx\"><code>OverflowException<\/code><\/a> exception\nbecause of integer addition overflow.<\/p>\n<p>(I then went on to learn that this problem is well-known in the .NET\nworld, and there are various ways around it. For C#, there&rsquo;s\n<code>unchecked<\/code>, but this was VB. In Java, integer addition overflow is not\na problem, because as stated in the Java Language Specification, section\n<a href=\"http:\/\/java.sun.com\/docs\/books\/jls\/third_edition\/html\/expressions.html#15.18.2\">15.8.2<\/a>: &ldquo;If an integer addition overflows, then the result is the\nlow-order bits of the mathematical sum as represented in some\nsufficiently large two&rsquo;s-complement format.&rdquo;)<\/p>\n<p>So because of my unit tests, I became a better .NET programmer. Thanks\nTDD!<\/p>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"TDD"}}]},{"title":"Test data provider using Python metaclass","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/test-data-provider-using-python-metaclass.html","rel":"alternate"}},"published":"2011-10-01T23:41:00+02:00","updated":"2011-10-01T23:41:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2011-10-01:\/test-data-provider-using-python-metaclass.html","summary":"<p>In my <a href=\"http:\/\/airpnp.finkod.se\">airpnp<\/a> project, I had to write a <a href=\"http:\/\/developer.apple.com\/library\/mac\/#documentation\/Darwin\/Reference\/ManPages\/man5\/plist.5.html\" title=\"plist man page\">binary plist<\/a> parser in\norder to parse certain data posted by iDevices. To support my unit\ntests, I created a number of binary plist files using an existing tool.\nI ended up with 17 files, and quickly realized that I wanted \u2026<\/p>","content":"<p>In my <a href=\"http:\/\/airpnp.finkod.se\">airpnp<\/a> project, I had to write a <a href=\"http:\/\/developer.apple.com\/library\/mac\/#documentation\/Darwin\/Reference\/ManPages\/man5\/plist.5.html\" title=\"plist man page\">binary plist<\/a> parser in\norder to parse certain data posted by iDevices. To support my unit\ntests, I created a number of binary plist files using an existing tool.\nI ended up with 17 files, and quickly realized that I wanted to use a\ndata provider and a single test method. I&rsquo;m very familiar with\n<a href=\"http:\/\/testng.org\">TestNG<\/a>, where a data provider approach (in Java) would look\nsomething like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kd\">class<\/span> <span class=\"nc\">TestClass<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"nd\">@DataProvider<\/span><span class=\"p\">()<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"n\">Iterator<\/span><span class=\"w\"> <\/span><span class=\"nf\">providerMethod<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ return an iterator over test data rows<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">    <\/span><span class=\"nd\">@Test<\/span><span class=\"p\">(<\/span><span class=\"n\">dataProvider<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;providerMethod&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kt\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">testMethod<\/span><span class=\"p\">(...<\/span><span class=\"na\">data<\/span><span class=\"w\"> <\/span><span class=\"n\">parameters<\/span><span class=\"p\">...)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ test and assert<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>When TestNG runs, it calls the <code>testMethod<\/code> method with data generated\nfrom the <code>providerMethod<\/code> method&rsquo;s iterator as many times as necessary.\nPython&rsquo;s <a href=\"http:\/\/docs.python.org\/library\/unittest.html\">unittest<\/a> module doesn&rsquo;t have support for data providers, so\nI had to roll my own. Since the unittest module discovers test methods\nby enumerating the attributes of a type, looking for methods whose name\nstarts with &ldquo;test&rdquo;, I had to create such methods dynamically. Having\njust learned about Python metaclasses, I thought it would be fun and\neducational to create a metaclass-based data provider approach. (Note\nthat I don&rsquo;t claim that using a metaclass is the best solution for\nimplementing data providers. I don&rsquo;t even claim that it&rsquo;s a good\nsolution!)<\/p>\n<p>I ended up with a metaclass that iterates over my test data and\ngenerates a test method for each row of data. This is what the code\nlooked like:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\"># imports omitted...<\/span>\n<span class=\"n\">DATA<\/span> <span class=\"o\">=<\/span> <span class=\"p\">[<\/span>\n    <span class=\"p\">[<\/span><span class=\"s1\">&#39;plist\/true.bin&#39;<\/span><span class=\"p\">,<\/span> <span class=\"kc\">True<\/span><span class=\"p\">],<\/span>\n    <span class=\"p\">[<\/span><span class=\"s1\">&#39;plist\/false.bin&#39;<\/span><span class=\"p\">,<\/span> <span class=\"kc\">False<\/span><span class=\"p\">],<\/span>\n    <span class=\"c1\"># ...more data rows omitted...<\/span>\n<span class=\"p\">]<\/span>\n\n<span class=\"k\">class<\/span> <span class=\"nc\">DataProvider<\/span><span class=\"p\">(<\/span><span class=\"nb\">type<\/span><span class=\"p\">):<\/span>\n    <span class=\"k\">def<\/span> <span class=\"fm\">__new__<\/span><span class=\"p\">(<\/span><span class=\"n\">meta<\/span><span class=\"p\">,<\/span> <span class=\"n\">classname<\/span><span class=\"p\">,<\/span> <span class=\"n\">bases<\/span><span class=\"p\">,<\/span> <span class=\"n\">classDict<\/span><span class=\"p\">):<\/span>\n        <span class=\"k\">def<\/span> <span class=\"nf\">create_test_method<\/span><span class=\"p\">(<\/span><span class=\"n\">fname<\/span><span class=\"p\">,<\/span> <span class=\"n\">expected<\/span><span class=\"p\">):<\/span>\n            <span class=\"k\">def<\/span> <span class=\"nf\">test_method<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">):<\/span>\n                <span class=\"n\">fd<\/span> <span class=\"o\">=<\/span> <span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">read_file<\/span><span class=\"p\">(<\/span><span class=\"n\">fname<\/span><span class=\"p\">)<\/span>\n                <span class=\"n\">obj<\/span> <span class=\"o\">=<\/span> <span class=\"n\">read_binary_plist<\/span><span class=\"p\">(<\/span><span class=\"n\">fd<\/span><span class=\"p\">)<\/span>\n                <span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">assertEqual<\/span><span class=\"p\">(<\/span><span class=\"n\">obj<\/span><span class=\"p\">,<\/span> <span class=\"n\">expected<\/span><span class=\"p\">)<\/span>\n            <span class=\"k\">return<\/span> <span class=\"n\">test_method<\/span>\n\n        <span class=\"c1\"># generate new methods based on test data<\/span>\n        <span class=\"k\">for<\/span> <span class=\"n\">fname<\/span><span class=\"p\">,<\/span> <span class=\"n\">expected<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">DATA<\/span><span class=\"p\">:<\/span>\n            <span class=\"n\">part<\/span> <span class=\"o\">=<\/span> <span class=\"n\">os<\/span><span class=\"o\">.<\/span><span class=\"n\">path<\/span><span class=\"o\">.<\/span><span class=\"n\">splitext<\/span><span class=\"p\">(<\/span><span class=\"n\">os<\/span><span class=\"o\">.<\/span><span class=\"n\">path<\/span><span class=\"o\">.<\/span><span class=\"n\">basename<\/span><span class=\"p\">(<\/span><span class=\"n\">fname<\/span><span class=\"p\">))[<\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span>\n            <span class=\"n\">classDict<\/span><span class=\"p\">[<\/span><span class=\"s2\">&quot;test_&quot;<\/span> <span class=\"o\">+<\/span> <span class=\"n\">part<\/span><span class=\"p\">]<\/span> <span class=\"o\">=<\/span> <span class=\"n\">create_test_method<\/span><span class=\"p\">(<\/span><span class=\"n\">fname<\/span><span class=\"p\">,<\/span> <span class=\"n\">expected<\/span><span class=\"p\">)<\/span>\n\n        <span class=\"c1\"># create!<\/span>\n        <span class=\"k\">return<\/span> <span class=\"nb\">type<\/span><span class=\"o\">.<\/span><span class=\"fm\">__new__<\/span><span class=\"p\">(<\/span><span class=\"n\">meta<\/span><span class=\"p\">,<\/span> <span class=\"n\">classname<\/span><span class=\"p\">,<\/span> <span class=\"n\">bases<\/span><span class=\"p\">,<\/span> <span class=\"n\">classDict<\/span><span class=\"p\">)<\/span>\n\n<span class=\"k\">class<\/span> <span class=\"nc\">TestReadBinary<\/span><span class=\"p\">(<\/span><span class=\"n\">unittest<\/span><span class=\"o\">.<\/span><span class=\"n\">TestCase<\/span><span class=\"p\">):<\/span>\n    <span class=\"n\">__metaclass__<\/span> <span class=\"o\">=<\/span> <span class=\"n\">DataProvider<\/span>\n\n    <span class=\"k\">def<\/span> <span class=\"nf\">read_file<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">,<\/span> <span class=\"n\">fname<\/span><span class=\"p\">):<\/span>\n        <span class=\"n\">fd<\/span> <span class=\"o\">=<\/span> <span class=\"nb\">open<\/span><span class=\"p\">(<\/span><span class=\"n\">os<\/span><span class=\"o\">.<\/span><span class=\"n\">path<\/span><span class=\"o\">.<\/span><span class=\"n\">join<\/span><span class=\"p\">(<\/span><span class=\"n\">os<\/span><span class=\"o\">.<\/span><span class=\"n\">path<\/span><span class=\"o\">.<\/span><span class=\"n\">dirname<\/span><span class=\"p\">(<\/span><span class=\"vm\">__file__<\/span><span class=\"p\">),<\/span> <span class=\"n\">fname<\/span><span class=\"p\">),<\/span> <span class=\"s1\">&#39;rb&#39;<\/span><span class=\"p\">)<\/span>\n\n        <span class=\"k\">try<\/span><span class=\"p\">:<\/span>\n            <span class=\"n\">s<\/span> <span class=\"o\">=<\/span> <span class=\"n\">fd<\/span><span class=\"o\">.<\/span><span class=\"n\">read<\/span><span class=\"p\">()<\/span>\n            <span class=\"k\">return<\/span> <span class=\"n\">StringIO<\/span><span class=\"p\">(<\/span><span class=\"n\">s<\/span><span class=\"p\">)<\/span>\n        <span class=\"k\">finally<\/span><span class=\"p\">:<\/span>\n            <span class=\"n\">fd<\/span><span class=\"o\">.<\/span><span class=\"n\">close<\/span><span class=\"p\">()<\/span>\n<\/code><\/pre><\/div>\n\n<p>The approach above has several problems:<\/p>\n<ul>\n<li>The approach is not at all generic; it only applies to the\n    particular situation based on which it was conceived. In particular,\n    the metaclass has a dependency on the test class as well as on the\n    structure of the test data.<\/li>\n<li>The test data are defined outside of the test class. While not a big\n    problem, it&rsquo;s nicer to keep the test data closer to where they are\n    used.<\/li>\n<\/ul>\n<p>For this blog post, I decided to create a more generic solution, and the\nresult is shown below. The solution handles both problems, and resembles\nthe TestNG\/Java approach with some notable differences:<\/p>\n<ul>\n<li>The data provider is not technically an instance method, as it has\n    no <code>self<\/code> parameter. This is because we need to call it while\n    defining the class (type).<\/li>\n<li>The data provider method is discovered by name prefix, and binds to\n    a test method using a naming convention. This may be ok though,\n    since test methods are discovered by name prefix anyway.<\/li>\n<\/ul>\n<p><\/p>\n\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kn\">import<\/span> <span class=\"nn\">unittest<\/span>\n\n<span class=\"k\">class<\/span> <span class=\"nc\">DataProviderSupport<\/span><span class=\"p\">(<\/span><span class=\"nb\">type<\/span><span class=\"p\">):<\/span>\n    <span class=\"k\">def<\/span> <span class=\"fm\">__new__<\/span><span class=\"p\">(<\/span><span class=\"n\">meta<\/span><span class=\"p\">,<\/span> <span class=\"n\">classname<\/span><span class=\"p\">,<\/span> <span class=\"n\">bases<\/span><span class=\"p\">,<\/span> <span class=\"n\">classDict<\/span><span class=\"p\">):<\/span>\n        <span class=\"c1\"># method for creating our test methods<\/span>\n        <span class=\"k\">def<\/span> <span class=\"nf\">create_test_method<\/span><span class=\"p\">(<\/span><span class=\"n\">testFunc<\/span><span class=\"p\">,<\/span> <span class=\"n\">args<\/span><span class=\"p\">):<\/span>\n            <span class=\"k\">return<\/span> <span class=\"k\">lambda<\/span> <span class=\"bp\">self<\/span><span class=\"p\">:<\/span> <span class=\"n\">testFunc<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">,<\/span> <span class=\"o\">*<\/span><span class=\"n\">args<\/span><span class=\"p\">)<\/span>\n\n        <span class=\"c1\"># look for data provider functions<\/span>\n        <span class=\"k\">for<\/span> <span class=\"n\">attrName<\/span><span class=\"p\">,<\/span> <span class=\"n\">attr<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">classDict<\/span><span class=\"o\">.<\/span><span class=\"n\">items<\/span><span class=\"p\">():<\/span>\n            <span class=\"k\">if<\/span> <span class=\"n\">attrName<\/span><span class=\"o\">.<\/span><span class=\"n\">startswith<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;dataprovider_&quot;<\/span><span class=\"p\">):<\/span>\n                <span class=\"c1\"># find out the corresponding test method<\/span>\n                <span class=\"n\">testName<\/span> <span class=\"o\">=<\/span> <span class=\"n\">attrName<\/span><span class=\"p\">[<\/span><span class=\"mi\">13<\/span><span class=\"p\">:]<\/span>\n                <span class=\"n\">testFunc<\/span> <span class=\"o\">=<\/span> <span class=\"n\">classDict<\/span><span class=\"p\">[<\/span><span class=\"n\">testName<\/span><span class=\"p\">]<\/span>\n\n                <span class=\"c1\"># the test method is no longer needed<\/span>\n                <span class=\"k\">del<\/span> <span class=\"n\">classDict<\/span><span class=\"p\">[<\/span><span class=\"n\">testName<\/span><span class=\"p\">]<\/span>\n\n                <span class=\"c1\"># generate test method variants based on<\/span>\n                <span class=\"c1\"># data from the data porovider function<\/span>\n                <span class=\"n\">i<\/span> <span class=\"o\">=<\/span> <span class=\"mi\">1<\/span>\n                <span class=\"k\">for<\/span> <span class=\"n\">args<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">attr<\/span><span class=\"p\">():<\/span>\n                    <span class=\"n\">classDict<\/span><span class=\"p\">[<\/span><span class=\"n\">testName<\/span> <span class=\"o\">+<\/span> <span class=\"nb\">str<\/span><span class=\"p\">(<\/span><span class=\"n\">i<\/span><span class=\"p\">)]<\/span> <span class=\"o\">=<\/span> <span class=\"n\">create_test_method<\/span><span class=\"p\">(<\/span><span class=\"n\">testFunc<\/span><span class=\"p\">,<\/span> <span class=\"n\">args<\/span><span class=\"p\">)<\/span>\n                    <span class=\"n\">i<\/span> <span class=\"o\">+=<\/span> <span class=\"mi\">1<\/span>\n\n        <span class=\"c1\"># create the type<\/span>\n        <span class=\"k\">return<\/span> <span class=\"nb\">type<\/span><span class=\"o\">.<\/span><span class=\"fm\">__new__<\/span><span class=\"p\">(<\/span><span class=\"n\">meta<\/span><span class=\"p\">,<\/span> <span class=\"n\">classname<\/span><span class=\"p\">,<\/span> <span class=\"n\">bases<\/span><span class=\"p\">,<\/span> <span class=\"n\">classDict<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>All error-checking has been excluded for brevity. In practice, there are\na couple of things you would want to validate. Here&rsquo;s an example of how\nto use it (the <code>data_provider_test_len_function<\/code> method is a generator,\nbut it might as well have returned a list of lists or tuples):<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">class<\/span> <span class=\"nc\">TestStringLength<\/span><span class=\"p\">(<\/span><span class=\"n\">unittest<\/span><span class=\"o\">.<\/span><span class=\"n\">TestCase<\/span><span class=\"p\">):<\/span>\n    <span class=\"n\">__metaclass__<\/span> <span class=\"o\">=<\/span> <span class=\"n\">DataProviderSupport<\/span>\n\n    <span class=\"k\">def<\/span> <span class=\"nf\">dataprovider_test_len_function<\/span><span class=\"p\">():<\/span> <span class=\"c1\"># no self!<\/span>\n        <span class=\"k\">yield<\/span> <span class=\"p\">(<\/span><span class=\"s2\">&quot;abc&quot;<\/span><span class=\"p\">,<\/span> <span class=\"mi\">3<\/span><span class=\"p\">)<\/span>\n        <span class=\"k\">yield<\/span> <span class=\"p\">(<\/span><span class=\"s2\">&quot;&quot;<\/span><span class=\"p\">,<\/span> <span class=\"mi\">0<\/span><span class=\"p\">)<\/span>\n        <span class=\"k\">yield<\/span> <span class=\"p\">(<\/span><span class=\"s2\">&quot;a&quot;<\/span><span class=\"p\">,<\/span> <span class=\"mi\">1<\/span><span class=\"p\">)<\/span>\n\n    <span class=\"k\">def<\/span> <span class=\"nf\">test_len_function<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">,<\/span> <span class=\"n\">astring<\/span><span class=\"p\">,<\/span> <span class=\"n\">expectedLength<\/span><span class=\"p\">):<\/span>\n        <span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">assertEqual<\/span><span class=\"p\">(<\/span><span class=\"n\">expectedLength<\/span><span class=\"p\">,<\/span> <span class=\"nb\">len<\/span><span class=\"p\">(<\/span><span class=\"n\">astring<\/span><span class=\"p\">))<\/span>\n<\/code><\/pre><\/div>\n\n<p>It would have been nicer to use <a href=\"http:\/\/docs.python.org\/glossary.html#term-decorator\">decorators<\/a> to bind the data provider\nwith the test method. However, if you pass arguments to a decorator, it\nis not called until the method it decorates is called, and we need its\neffect earlier. Name binding was the simplest solution I could come up\nwith at this point!<\/p>\n<p><strong>Update, 2011-10-03<\/strong>: The code presented in this post does not work\nproperly with <a href=\"http:\/\/readthedocs.org\/docs\/nose\/en\/latest\/\">nose<\/a>, since nose discovers test cases differently from\nthe unittest module. Also, nose supports <a href=\"http:\/\/readthedocs.org\/docs\/nose\/en\/latest\/writing_tests.html#test-generators\">test generators<\/a> out of the\nbox, which makes it kind of pointless to make the code compatible with\nnose.<\/p>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"metaclass"}},{"@attributes":{"term":"Python"}},{"@attributes":{"term":"test"}}]},{"title":"Mocking Zope interfaces","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/mocking-zope-interfaces.html","rel":"alternate"}},"published":"2011-09-28T15:10:00+02:00","updated":"2011-09-28T15:10:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2011-09-28:\/mocking-zope-interfaces.html","summary":"<p>In one of my pet projects I use <a href=\"http:\/\/twistedmatrix.com\">Twisted<\/a> for handling asynchronous\nnetwork events. While browsing the Twisted source code, I encountered\nZope interfaces. In a dynamically typed language like Python, what good\nare interfaces?<\/p>\n<p>It turns out that Zope interfaces are slightly different from interfaces\nfound in a statically \u2026<\/p>","content":"<p>In one of my pet projects I use <a href=\"http:\/\/twistedmatrix.com\">Twisted<\/a> for handling asynchronous\nnetwork events. While browsing the Twisted source code, I encountered\nZope interfaces. In a dynamically typed language like Python, what good\nare interfaces?<\/p>\n<p>It turns out that Zope interfaces are slightly different from interfaces\nfound in a statically typed object-oriented language. They facilitate\nthe use of components in Python. Given a Zope interface, you can easily\nverify if an object claims to provide a particular service, and create\nan adapter on the fly that bridges two interfaces. I won&rsquo;t go into\ndetails; read <a href=\"http:\/\/twistedmatrix.com\/documents\/current\/core\/howto\/components.html\">this document<\/a> for more information.<\/p>\n<p>I decided to use Zope interfaces in my pet project, but when I ran my\ntests, my mock objects didn&rsquo;t work anymore. In this post, I&rsquo;ll show how\nI got back on track with my mocks! By the way, I use <a href=\"http:\/\/www.voidspace.org.uk\/python\/mock\/\">this mock\nframework<\/a>.<\/p>\n<p>Suppose that we have the following Zope interface in our code (in\n<em>foo.py<\/em>):<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kn\">from<\/span> <span class=\"nn\">zope.interface<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">Interface<\/span>\n\n<span class=\"k\">class<\/span> <span class=\"nc\">IFoo<\/span><span class=\"p\">(<\/span><span class=\"n\">Interface<\/span><span class=\"p\">):<\/span>\n<span class=\"w\">    <\/span><span class=\"sd\">&quot;&quot;&quot;The IFoo interface.&quot;&quot;&quot;<\/span>\n    <span class=\"k\">def<\/span> <span class=\"nf\">bar<\/span><span class=\"p\">(<\/span><span class=\"n\">action<\/span><span class=\"p\">):<\/span>\n<span class=\"w\">        <\/span><span class=\"sd\">&quot;&quot;&quot;Given action, do bar.&quot;&quot;&quot;<\/span>\n<\/code><\/pre><\/div>\n\n<p>We also have a function that we want to test, and the function accepts\nan object that implements the <code>IFoo<\/code> interface (also in <em>foo.py<\/em>):<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">def<\/span> <span class=\"nf\">baz<\/span><span class=\"p\">(<\/span><span class=\"n\">foo<\/span><span class=\"p\">):<\/span>\n    <span class=\"n\">foo<\/span> <span class=\"o\">=<\/span> <span class=\"n\">IFoo<\/span><span class=\"p\">(<\/span><span class=\"n\">foo<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">foo<\/span><span class=\"o\">.<\/span><span class=\"n\">bar<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;test&quot;<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<h3>First attempt<\/h3>\n<p>Let&rsquo;s create a unit test for the <code>baz<\/code> function, one that mocks the\nargument so that we can verify that its <code>bar<\/code> method was called. It may\nlook something like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kn\">import<\/span> <span class=\"nn\">unittest<\/span>\n<span class=\"kn\">from<\/span> <span class=\"nn\">mock<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">Mock<\/span>\n<span class=\"kn\">from<\/span> <span class=\"nn\">foo<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">IFoo<\/span><span class=\"p\">,<\/span> <span class=\"n\">baz<\/span>\n\n<span class=\"k\">class<\/span> <span class=\"nc\">TestBaz<\/span><span class=\"p\">(<\/span><span class=\"n\">unittest<\/span><span class=\"o\">.<\/span><span class=\"n\">TestCase<\/span><span class=\"p\">):<\/span>\n    <span class=\"k\">def<\/span> <span class=\"nf\">test_call<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">):<\/span>\n        <span class=\"n\">mock<\/span> <span class=\"o\">=<\/span> <span class=\"n\">Mock<\/span><span class=\"p\">(<\/span><span class=\"n\">IFoo<\/span><span class=\"p\">)<\/span>\n        <span class=\"n\">baz<\/span><span class=\"p\">(<\/span><span class=\"n\">mock<\/span><span class=\"p\">)<\/span>\n        <span class=\"n\">mock<\/span><span class=\"o\">.<\/span><span class=\"n\">bar<\/span><span class=\"o\">.<\/span><span class=\"n\">assert_called_with<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;test&quot;<\/span><span class=\"p\">)<\/span>\n\n<span class=\"k\">if<\/span> <span class=\"vm\">__name__<\/span> <span class=\"o\">==<\/span> <span class=\"s2\">&quot;__main__&quot;<\/span><span class=\"p\">:<\/span>\n    <span class=\"n\">unittest<\/span><span class=\"o\">.<\/span><span class=\"n\">main<\/span><span class=\"p\">()<\/span>\n<\/code><\/pre><\/div>\n\n<p>Our intention is for the <code>Mock<\/code> call to create a mock object that\nimplements the <code>IFoo<\/code> interface. This does not work as expected, though.\nInstead, we get an error message: &ldquo;AttributeError:Mock object has no\nattribute &lsquo;bar&rsquo;&ldquo;. What happened? Apparently, our mock survived the\n<code>foo = IFoo(foo)<\/code> part. This is because the mock dynamically satisfies\nall checks that the Zope framework throws at it. But the reason for the\nfailure is that when we call <code>Mock<\/code> with a class object, the resulting\nmock will only respond to the methods that it finds in the class using\n<code>dir(cls)<\/code>, but the <code>baz<\/code> method is not in that list!<\/p>\n<h3>Second attempt<\/h3>\n<p>Lucky for us, the interface class has a <code>names()<\/code> method that we can\nuse:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>    <span class=\"k\">def<\/span> <span class=\"nf\">test_call<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">):<\/span>\n        <span class=\"n\">mock<\/span> <span class=\"o\">=<\/span> <span class=\"n\">Mock<\/span><span class=\"p\">(<\/span><span class=\"n\">IFoo<\/span><span class=\"o\">.<\/span><span class=\"n\">names<\/span><span class=\"p\">())<\/span>\n        <span class=\"o\">...<\/span>\n<\/code><\/pre><\/div>\n\n<p>We get closer but not close enough. This time, the error is: &ldquo;TypeError:\n(&lsquo;Could not adapt&rsquo;, , )&rdquo;. But why do we fail earlier this time? Well,\nit&rsquo;s because in our first attempt the mock did mock all the required\ninfrastructure methods. But this time, it only mocks <code>baz<\/code>. And since\nthe <code>Mock<\/code> class has not declared that it implements <code>IFoo<\/code>, and there\nis no adapter installed, the mock isn&rsquo;t recognized.<\/p>\n<h3>Third attempt<\/h3>\n<p>It&rsquo;s not a good idea to dynamically change the <code>Mock<\/code> class to implement\nthe <code>IFoo<\/code> interface; that would possibly ruin other test cases.\nInstead, we create a sub class:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kn\">from<\/span> <span class=\"nn\">zope.interface<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">implements<\/span>\n\n<span class=\"k\">class<\/span> <span class=\"nc\">IFooMock<\/span><span class=\"p\">(<\/span><span class=\"n\">Mock<\/span><span class=\"p\">):<\/span>\n<span class=\"w\">    <\/span><span class=\"sd\">&quot;&quot;&quot;A specialized IFoo mock class.&quot;&quot;&quot;<\/span>\n    <span class=\"n\">implements<\/span><span class=\"p\">(<\/span><span class=\"n\">IFoo<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>And in our unit test:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>    <span class=\"k\">def<\/span> <span class=\"nf\">test_call<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">):<\/span>\n        <span class=\"n\">mock<\/span> <span class=\"o\">=<\/span> <span class=\"n\">IFooMock<\/span><span class=\"p\">(<\/span><span class=\"n\">IFoo<\/span><span class=\"o\">.<\/span><span class=\"n\">names<\/span><span class=\"p\">())<\/span>\n        <span class=\"o\">...<\/span>\n<\/code><\/pre><\/div>\n\n<p>This time, the outcome is much more pleasant; the test will pass!<\/p>\n<h3>A general solution<\/h3>\n<p>We can go even further, by defining a method that dynamically creates\nthe interface\/Mock sub class for us (error handling elided for brevity):<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kn\">from<\/span> <span class=\"nn\">mock<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">Mock<\/span>\n<span class=\"kn\">from<\/span> <span class=\"nn\">zope.interface<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">classImplements<\/span>\n<span class=\"kn\">import<\/span> <span class=\"nn\">types<\/span>\n\n<span class=\"k\">def<\/span> <span class=\"nf\">create_interface_mock<\/span><span class=\"p\">(<\/span><span class=\"n\">interface_class<\/span><span class=\"p\">):<\/span>\n<span class=\"w\">    <\/span><span class=\"sd\">&quot;&quot;&quot;Dynamically create a Mock sub class that implements the given Zope interface class.&quot;&quot;&quot;<\/span>\n\n    <span class=\"c1\"># the init method, automatically specifying the interface methods<\/span>\n    <span class=\"k\">def<\/span> <span class=\"nf\">init<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">,<\/span> <span class=\"o\">*<\/span><span class=\"n\">args<\/span><span class=\"p\">,<\/span> <span class=\"o\">**<\/span><span class=\"n\">kwargs<\/span><span class=\"p\">):<\/span>\n        <span class=\"n\">Mock<\/span><span class=\"o\">.<\/span><span class=\"fm\">__init__<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">,<\/span> <span class=\"n\">spec<\/span><span class=\"o\">=<\/span><span class=\"n\">interface_class<\/span><span class=\"o\">.<\/span><span class=\"n\">names<\/span><span class=\"p\">(),<\/span>\n                      <span class=\"o\">*<\/span><span class=\"n\">args<\/span><span class=\"p\">,<\/span> <span class=\"o\">**<\/span><span class=\"n\">kwargs<\/span><span class=\"p\">)<\/span>\n\n    <span class=\"c1\"># we derive the sub class name from the interface name<\/span>\n    <span class=\"n\">name<\/span> <span class=\"o\">=<\/span> <span class=\"n\">interface_class<\/span><span class=\"o\">.<\/span><span class=\"vm\">__name__<\/span> <span class=\"o\">+<\/span> <span class=\"s2\">&quot;Mock&quot;<\/span>\n\n    <span class=\"c1\"># create the class object and provide the init method<\/span>\n    <span class=\"n\">klass<\/span> <span class=\"o\">=<\/span> <span class=\"n\">types<\/span><span class=\"o\">.<\/span><span class=\"n\">TypeType<\/span><span class=\"p\">(<\/span><span class=\"n\">name<\/span><span class=\"p\">,<\/span> <span class=\"p\">(<\/span><span class=\"n\">Mock<\/span><span class=\"p\">,<\/span> <span class=\"p\">),<\/span> <span class=\"p\">{<\/span><span class=\"s2\">&quot;__init__&quot;<\/span><span class=\"p\">:<\/span> <span class=\"n\">init<\/span><span class=\"p\">})<\/span>\n\n    <span class=\"c1\"># the new class should implement the interface<\/span>\n    <span class=\"n\">classImplements<\/span><span class=\"p\">(<\/span><span class=\"n\">klass<\/span><span class=\"p\">,<\/span> <span class=\"n\">interface_class<\/span><span class=\"p\">)<\/span>\n\n    <span class=\"c1\"># make the class available to unit tests<\/span>\n    <span class=\"nb\">globals<\/span><span class=\"p\">()[<\/span><span class=\"n\">name<\/span><span class=\"p\">]<\/span> <span class=\"o\">=<\/span> <span class=\"n\">klass<\/span>\n<\/code><\/pre><\/div>\n\n<p>Now, it&rsquo;s sufficient to call the method above for each interface to\nmock:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">if<\/span> <span class=\"vm\">__name__<\/span> <span class=\"o\">==<\/span> <span class=\"s2\">&quot;__main__&quot;<\/span><span class=\"p\">:<\/span>\n    <span class=\"n\">create_interface_mock<\/span><span class=\"p\">(<\/span><span class=\"n\">IFoo<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">unittest<\/span><span class=\"o\">.<\/span><span class=\"n\">main<\/span><span class=\"p\">()<\/span>\n<\/code><\/pre><\/div>\n\n<p>And finally, the unit test can be simplified to this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>    <span class=\"k\">def<\/span> <span class=\"nf\">test_call<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">):<\/span>\n        <span class=\"n\">mock<\/span> <span class=\"o\">=<\/span> <span class=\"n\">IFooMock<\/span><span class=\"p\">()<\/span>\n        <span class=\"o\">...<\/span>\n<\/code><\/pre><\/div>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"mock"}},{"@attributes":{"term":"test"}},{"@attributes":{"term":"python"}}]},{"title":"Debugging Java focus problems using the focus log","link":{"@attributes":{"href":"https:\/\/programmaticallyspeaking.com\/debugging-java-focus-problems-using-the-focus-log.html","rel":"alternate"}},"published":"2011-09-28T14:28:00+02:00","updated":"2011-09-28T14:28:00+02:00","author":{"name":"Per"},"id":"tag:programmaticallyspeaking.com,2011-09-28:\/debugging-java-focus-problems-using-the-focus-log.html","summary":"<p>A while ago I set out to fix a couple of focus problems in a GUI at\nwork. One of the problems was that after a certain user operation, all\nkeyboard shortcuts stopped working (as you may know, keyboard events are\ndispatched up the focus chain until a component handles \u2026<\/p>","content":"<p>A while ago I set out to fix a couple of focus problems in a GUI at\nwork. One of the problems was that after a certain user operation, all\nkeyboard shortcuts stopped working (as you may know, keyboard events are\ndispatched up the focus chain until a component handles them). Another\nproblem was that after the user clicked in a component, another\ncomponent would start flickering. Actually, the problems are not that\nimportant, but the way to solving them are!<\/p>\n<p>Code that is triggered by a focus change is especially painful to debug,\nat least in Windows, because as soon as the debugger kicks in, the main\nwindow focus is transferred from the GUI of the application you&rsquo;re\ntrying to debug to the debugger window. Short of littering the code with\n<code>System.out.println<\/code> or attaching with a remote debugger, there&rsquo;s not\nmuch you can do.<\/p>\n<p>Lucky for us,\u00a0most (all?) focus events and actions in Java are logged to\na focus log. In this post, I&rsquo;ll show how to enable focus logging in your\napplication.<\/p>\n<p>Typically, we have a main class for running our program. Our approach is\nto create a separate main class that sets up the focus log and then\ncalls the real main class:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kd\">class<\/span> <span class=\"nc\">StartWithFocusLogging<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kd\">static<\/span><span class=\"w\"> <\/span><span class=\"kt\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">main<\/span><span class=\"p\">(<\/span><span class=\"n\">String<\/span><span class=\"o\">[]<\/span><span class=\"w\"> <\/span><span class=\"n\">args<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">enableFocusLogging<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">RealMainClass<\/span><span class=\"p\">.<\/span><span class=\"na\">main<\/span><span class=\"p\">(<\/span><span class=\"n\">args<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">private<\/span><span class=\"w\"> <\/span><span class=\"kd\">static<\/span><span class=\"w\"> <\/span><span class=\"kt\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">enableFocusLogging<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ ...<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Now, let&rsquo;s dig into the <code>enableFocusLogging<\/code> method. The name of the\nlogger is <code>java.awt.focus.Component<\/code>, and the first thing we need to do\nis get the logger instance:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">private<\/span><span class=\"w\"> <\/span><span class=\"kd\">static<\/span><span class=\"w\"> <\/span><span class=\"kt\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">enableFocusLogging<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ Obtain a reference to the logger<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">Logger<\/span><span class=\"w\"> <\/span><span class=\"n\">focusLog<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Logger<\/span><span class=\"p\">.<\/span><span class=\"na\">getLogger<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;java.awt.focus.Component&quot;<\/span><span class=\"p\">);<\/span>\n<\/code><\/pre><\/div>\n\n<p>By default, the focus logger does not have any log level set, and will\ntherefore inherit a log level from an ancestor (ultimately the root\nlogger if no logger in between has had its level set). All focus logging\nwill take place on one of the finer levels (FINE, FINER and FINEST), but\nsince we&rsquo;re debugging we&rsquo;re interested in everything:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"w\">    <\/span><span class=\"c1\">\/\/ The logger should log all messages<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">focusLog<\/span><span class=\"p\">.<\/span><span class=\"na\">setLevel<\/span><span class=\"p\">(<\/span><span class=\"n\">Level<\/span><span class=\"p\">.<\/span><span class=\"na\">ALL<\/span><span class=\"p\">);<\/span>\n<\/code><\/pre><\/div>\n\n<p>A logger sends all non-discarded log messages to one or more handlers.\nWithout a handler, we won&rsquo;t see anything. Therefore, the next thing to\ndo is to create a handler. A handler must extend the\n<code>java.util.logging.Handler<\/code> class. Fortunately, there are existing\nhandlers that we can use, and to keep things simple, let&rsquo;s use the\n<code>ConsoleHandler<\/code> class:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"w\">    <\/span><span class=\"c1\">\/\/ Create a new handler<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">ConsoleHandler<\/span><span class=\"w\"> <\/span><span class=\"n\">handler<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">ConsoleHandler<\/span><span class=\"p\">();<\/span>\n<\/code><\/pre><\/div>\n\n<p>Our new handler writes log messages to <code>System.err<\/code>, but not out of the\nbox. While the handler will configure itself using the global log\nmanager, it defaults to INFO level. (The benefit of having a handler\nlevel is that we can let different log outputs differ in verbosity.)\nAgain, this won&rsquo;t do in our case, so let&rsquo;s up the level:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"w\">    <\/span><span class=\"c1\">\/\/ The handler must handle all messages<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">handler<\/span><span class=\"p\">.<\/span><span class=\"na\">setLevel<\/span><span class=\"p\">(<\/span><span class=\"n\">Level<\/span><span class=\"p\">.<\/span><span class=\"na\">ALL<\/span><span class=\"p\">);<\/span>\n<\/code><\/pre><\/div>\n\n<p>Finally, the handle must be connected with the logger to receive the log\nmessages it let&rsquo;s through:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"w\">    <\/span><span class=\"c1\">\/\/ Add the handler to the logger<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">focusLog<\/span><span class=\"p\">.<\/span><span class=\"na\">addHandler<\/span><span class=\"p\">(<\/span><span class=\"n\">handler<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>And that&rsquo;s it! When you run your application through our new main class,\nyou will get a log of all focus events on the error console. Of course,\nyou can easily use a different handler to redirect messages to another\ndestination, a file for example.<\/p>\n<p>The full source code in all its glory, including imports, is:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kn\">import<\/span><span class=\"w\"> <\/span><span class=\"nn\">java.util.logging.ConsoleHandler<\/span><span class=\"p\">;<\/span>\n<span class=\"kn\">import<\/span><span class=\"w\"> <\/span><span class=\"nn\">java.util.logging.Level<\/span><span class=\"p\">;<\/span>\n<span class=\"kn\">import<\/span><span class=\"w\"> <\/span><span class=\"nn\">java.util.logging.Logger<\/span><span class=\"p\">;<\/span>\n<span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kd\">class<\/span> <span class=\"nc\">StartWithFocusLogging<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kd\">static<\/span><span class=\"w\"> <\/span><span class=\"kt\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">main<\/span><span class=\"p\">(<\/span><span class=\"n\">String<\/span><span class=\"o\">[]<\/span><span class=\"w\"> <\/span><span class=\"n\">args<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">enableFocusLogging<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">RealMainClass<\/span><span class=\"p\">.<\/span><span class=\"na\">main<\/span><span class=\"p\">(<\/span><span class=\"n\">args<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">private<\/span><span class=\"w\"> <\/span><span class=\"kd\">static<\/span><span class=\"w\"> <\/span><span class=\"kt\">void<\/span><span class=\"w\"> <\/span><span class=\"nf\">enableFocusLogging<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Obtain a reference to the logger<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">Logger<\/span><span class=\"w\"> <\/span><span class=\"n\">focusLog<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Logger<\/span><span class=\"p\">.<\/span><span class=\"na\">getLogger<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;java.awt.focus.Component&quot;<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ The logger should log all messages<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">focusLog<\/span><span class=\"p\">.<\/span><span class=\"na\">setLevel<\/span><span class=\"p\">(<\/span><span class=\"n\">Level<\/span><span class=\"p\">.<\/span><span class=\"na\">ALL<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Create a new handler<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">ConsoleHandler<\/span><span class=\"w\"> <\/span><span class=\"n\">handler<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">ConsoleHandler<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ The handler must handle all messages<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">handler<\/span><span class=\"p\">.<\/span><span class=\"na\">setLevel<\/span><span class=\"p\">(<\/span><span class=\"n\">Level<\/span><span class=\"p\">.<\/span><span class=\"na\">ALL<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Add the handler to the logger<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">focusLog<\/span><span class=\"p\">.<\/span><span class=\"na\">addHandler<\/span><span class=\"p\">(<\/span><span class=\"n\">handler<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>","category":[{"@attributes":{"term":"Coding"}},{"@attributes":{"term":"Java"}}]}]}