Fortsätt till huvudinnehåll

Inlägg

Visar inlägg från 2018

C# Enum as bit field

Bit field enum Whenever you wish to express combinations of properties of an object, bit fields are a good way to accomplish this. As a simple example, consider a file in the file system. It can be Readable , Writable , Hidden or a combination these. The different attributes can be defined as an enum : [Flags] public enum FileAttribute {   None      = 0b0000;   Readable  = 0b0001;   Writeable = 0b0010;   Hidden    = 0b0100; } To indicate that this enum is expected to be used as a bit field I have defined it with the FlagsAttribute . It is important to understand that the FlagsAttribute does nothing more than making some changes to how the ToString method of the enum works, making it possible to print out all flags. It does not introduce any validation or special treatment of the enum in any other way. I have defined the values of the different fields of the enum using binary representation, this should make it even more clear that this is a bit field and which bi

C# Deconstruct and Discards

 Deconstruct and Discards In the last post I mentioned the Deconstruct method and how it should not be mixed up with a Destructor . In this post I will show some examples and how you can use Deconstruct and especially in combination with something called Discards . The Deconstruct method can be defined within a class to provide a way to retrieve a Tuple of the data that makes up the type and Discards can be used by the caller to effectively ignore the members of the Tuple that aren't of interest. Sounds complicated? Hopefully the examples below will clear things out. Implementing the Deconstruct method Let's start with a simple container class holding attributes of a file in the filesystem. public class FileInfo {   public string Name { get; }   public int SizeInBytes { get; }   public bool ReadOnly { get; }   public FileInfo(string name, int sizeInBytes, bool readOnly)   {     Name = name;     SizeInBytes = sizeInBytes;     ReadOnly = readOnly;   }

C# Finalize, Dispose, and Deconstruct

Introducing the Concepts It is easy to get a bit confused when trying to figure out what resources you need to free explicitly and how to release the resources that your class has created or is holding references to. You will find that there is something called Finalizer , a clean-up pattern called The Dispose Pattern, and a special Deconstruct method that you can declare. In most cases though, you don't have to do anything and just let the Garbage Collector (GC) do its thing. However, if your class allocates unmanaged memory, open file handles, network sockets, database connections or similar, you need to ensure that these are properly closed and freed before the references are removed. I will go through the different concepts and hopefully clear out how to ensure that all resources are properly freed in your application. The Deconstruct method You might say that it is incorrect to even mention the Deconstruct keyword/method in this post, since it actually have nothing

When to use out parameters in C#

The out keyword In C# you can use the out keyword to define output parameters in your method signature. For example, the Int32.TryParse method in the System namespace has the following signature: public static bool Int32.TryParse(string s, out int result) From this you can read out that the TryParse method returns a boolean but also provides a result as an out parameter . The boolean will indicate whether it was possible to parse an integer value from the string s and store it in the result variable. You can call the TryParse method like this: if (Int32.TryParse(str, out var result)) {     Console.WriteLine($"The result is: {result}"); } else {     Console.WriteLine("Parsing failed"); } When is it a good idea to use out parameters ? Most of the time the use of out parameters adds complexity to your program. It will make the source code harder to follow since anyone reading the code will have to juggle several return values instead of just

C# Delegates, Action, Func, or Predicate

Introduction As a previous C developer I am used to working with function pointers and I found the C# Delegates quite easy to work with in comparison. One thing that made me a bit confused initially however were the Delegate types defined in the .NET framework. Why would I want to bother with Actions , Funcs , and Predicates ? After reading up on them I almost never define custom Delegates anymore. I will try to explain their use cases below. Delegates A Delegate in C# is similar to a function pointer in C or C++. You can always define a custom Delegate that matches any method signature you want. However, the .NET Framework defines a number of Delegates you can use so that you don't have to define your own. These Delegates are grouped into three different Delegate groups, Actions , Funcs , and Predicates . Actions An Action is, as the name implies, a Delegate that encapsulates a method that performs an operation and where you expect no result to be returned. The Ac

Override the Object.GetHashCode method, why you should bother

When you design a class you sometimes want to override the Equals method in order to use some internal fields to determine if two instances of the class are equal. For example let's assume that you have implemented a class Money that has two fields, one named _amount of type decimal and another one called _currency of type string . You decide that two objects of type Money are equal if and only if the amount and currency fields have the same values. The implementation of Equals looks like this: public override bool Equals(object obj) { if (obj is Money other) { return _currency.Equals(other._currency, StringComparison.Ordinal) && _amount.Equals(other._amount); } return false; } You then notice that you get a warning during compilation, Warning CS0659 'Money' overrides Object.Equals(object o) but does not override Object.GetHashCode() . So what is this all about? If you look into it a bit you will find that there is a rule sayin

String comparison in C#

In C#, a string is a sequential read-only collection of Char objects. A Char object is an instance of a Char struct, which represents a character as a UTF-16 code unit. Most programs, and programmers, do not care much about the internal representation of a string and a Char . As long as you know that strings are immutable and there is a big efficiency penalty involved in building up strings in loops without involving a mutable object, such as a StringBuilder , you are mostly fine. However, there are some things that are good to know when working with strings. One of these things is comparison using methods such as S tring.CompareTo and String.Compare . By default the Compare and CompareTo methods are Culture sensitive. This means, that depending on the language and culture setting of the machine running the application , comparison and sorting of strings might be different than on your development machine. This might be exactly what you want, or it might come as a complete surp

When to use float, double, and decimal in C#

If your dealing with numbers that have fractions you need a number type that can handle that case. When you define a variable in C# and assign it a fractional value, for example var myValue = 2.5; the default type is double . In many cases double works fine. But sometimes you want to use float or decimal instead. The major difference between float and double is that float uses 32 bits while double uses 64 bits. This makes double able to represent a much larger range of values with higher precision. So if memory space is not an issue you can safely ignore float and use double instead. One major drawback with float and double is that they use binary representation for the fractional part of the value. This becomes an issue when you need to have exact values for the fractional part. Not all fractional values, that looks really exact in the code, can be represented in binary. One example is 0.2 which gets rounded off when stored as a float or double. What this means is that y

Indexers in C#

A feature in the C# language that I have noticed that many developers, even some with years of C# experience, have missed is that it is possible to create Indexers. With Indexers you are able to use square brackets to access specific elements of a class, just like you would in an Array or a List: items =  new   List < int > { 1, 2, 3, 4 }; var  first = items[0]; Assume that you define an interface for a certain ability that a class can have. That ability being that it should be possible to set and get elements of the class using square brackets. You may define the interface like this: namespace  Indexer {      public   interface   IIndexable < T >     {         T   this [ int  index] {  get ;  set ; }     } } And a class can implement the interface like this: using  System.Collections.Generic; namespace  Indexer {      internal   class   Indexable  :  IIndexable < int >     {          private   readonly   IList < int > items;          public  Ind

Client package manager for Visual Studio

While following the examples in the Pro ASP.NET Core MVC 2 book I realized that currently it doesn't exist a package manager for JavaScript packages with good integration with Visual Studio. Prior to version 15.5 a package manager named Bower was integrated with Visual Studio. This support was however removed and the plan is to add support for a new package manager, called Library Manager, or LibMan for short in version 15.8 of Visual Studio. But the current version 15.7.4 have no good integration with any JS package manager. So, what can you do about it? Well you can use the Node Package Manager, npm. This has some integration with Visual Studio and adding a package.json to the root of your project lets you specify packages that is downloaded for you. But, the downloaded files are not included in your project, instead they are just downloaded to a folder named node_modules in your project directory. So, how do you add the files you need to your project? Well first of all, be

Hurt

I have to take a week off from coding 😢. Today I accidentally cut myself in the hand quite bad while cooking and had to go to the emergency to get stitched back together. Lesson learned, nerds should stay away from sharp objects.

Making some changes to the ASP.NET learning plan

After some thought I have decided to put some more time into the "learning by doing" parts of my focused ASP.NET learning. Even though the Little ASP.NET Core Book is a great resource for getting started quickly with ASP.NET Core it relies heavily on the MVC and Identity templates. Using templates is a nice way to get started quickly, but it also encourages developers to treat important features, such as authentication, as black boxes. I really want to learn things in depth so I will spend some more time on actually writing a couple of sample sites using a Empty template. To help me on my way I have decided to go with the book  Pro ASP.NET Core MVC 2 by Adam Freeman.

ASP.NET Core sample site done

Following the hands-on tutorial in The little ASP.NET Core book I was able to put together a sample ASP.NET site in just a couple of days. The book is targeting ASP.NET Core 2.0 but I attempted to use the latest official release, which at the time of writing is ASP.NET Core 2.1.300. I didn't expect any breaking changes between a version 2.0 and 2.1 but there actually are some things that do not work exactly as they did in 2.0. I have written them down on my GitHub page and there is also a feature request available on the book's GitHub page to change it so it is compatible with version 2.1 of ASP.NET Core. The author of the book, Nate Barbettini, has made a great work and I can really recommend having a look at the book. It is available for free at his website. However, if you want every sample in the book to work without any modifications you should probably use ASP.NET Core 2.0 for now.

Git repository for ASP.NET focused learning

I set up a Git repository on GitHub for the ASP.NET focused learning project, see https://github.com/Backhage/LearnASP.NET . Thanks to the Creative Common licensed book "The little ASP.NET Core book" things are progressing a lot faster than I initially planned. The book is a step-by-step guide that takes you through the details on creating a SQLite backed site with ASP.NET Core MVC. It shows you how to do it and explains why. If you, like me, have a couple of years of C# coding behind you most of the things will be quite easy to grasp. Entity Framework is used to work with the database making it easy to use LINQ queries to access data. The things that are a bit unfamiliar is the front end stuff. I created my first website in 1997 and wrote quite a lot of HTML and even some ASP (the old kind, not the ASP.NET kind), PHP and JavaScript during the years following that. However, I haven't been writing much front end stuff since then. But at least some if it is still fami

Focused learning, ASP.NET

I have decided that it is time to really broaden my knowledge on a specific topic. With all the things I have going on beside learning new, coding related stuff, stuff (full time work, family with two kids, and marathon training) I need to set up a study plan, goals and set off time for focused learning. The topic I have in mind is Web-based applications. I am thinking ASP.NET, Typescript, and Entity Framework. The application can be my good old friend "The Record Collector". Here's a quick plan, may have to be revised. Weeks Reading material. Collect links, books, etc on the topic. Tooling. Ensure all required tools and resources for developing and hosting a database backed ASP.NET web application are available. Sample site. Follow guide/tutorial to set up a sample site. Domain Model. Design the core domain model for the Record Collector application. Core implementation. Implement core functionality. Focus should not be on UI and persistence. Finish up core

Android Studio Impressions

I have some previous experience with Jetbrains IDE for Java development, IntelliJ. And I have a couple of years of experience using their Visual Studio plugin ReSharper. I think both of the products are great and therefore I was happily surprised to see that Android Studio is built on the IntelliJ Platform . If you know IntelliJ you will feel right at home using Android Studio. Of course there are several Android specific features, like automatic install of the Android SDK and support for starting and running your app directly on an Android emulator or on your own Android device. You also have access to a built in layout editor that you can use to design the UI for your app. It has some similarities to the layout view in Visual Studio that you use when designing UIs for WPF applications (like drag and drop of visual components, properties listing, etc). Overall it is pretty neat and easy to understand and work in. Of course you still have the possibility to edit the underlying XM

Switching to Android Studio

I thought Xamarin.Forms and Visual Studio would be a mature and stable development environment for developing apps for Android, iOS and UWP. I was wrong. First, as I wrote in the previous post, it does not work to start the Android Emulator from within Visual Studio. I filed a bug report towards Visual Studio and was informed that the development team is aware of the issue and are planing to release a fix on the 15.8 branch of VS. Not very prioritized to fix apparently. Second, Xamarin.Forms defaults to using a shared project for the common, not target specific, source files. Shared C# projects uses the new .NET project system by default. The support for XAML and code behind files still has problems in the new system. So, adding new XAML files to your project will not work from within Visual Studio, manual editing of the project files are needed. Also the static code analysis does not work well with XAML files in the new project system so you will get a lot of false errors. Thir

A mobile app using Xamarin

Today I started on a mobile app for my common-law wife. She is starting a workout program and I thought I could code up a simple Android app that she can use to keep track of the different exercises and the number of repetitions or duration to do them for. As I have been working with C# for couple of years now and I feel comfortable with it I thought I would try using Xamarin . I discussed the functionality for the first version with my partner and sketched up a simple model of the entities. Then I figured it would be a good idea to try out a simple tutorial to get a feeling for it and ensure I have all the needed tools installed. In the Visual Studio Installer there is a check box for mobile app development so I checked that and let everything install. Then in Visual Studio I created a new Android project, built it and pressed F5 to see what would happen. No go! The Android emulator wants virtualization to be enabled in order to run in hardware accelerated mode. So I had to rebo

To be really proud of your work

This week I was asked, without any preparation time, to explain something that I have coded that I feel really proud over. To me this was a really tough question. I don't normally look back on my coding projects and feel proud over what I have done. When I code things at home I do it for learning, trying out new things or improving my skills in certain areas. And the things I code at work they are, well, just work. I do, however, take pride in my work. In the sense that I put a lot of effort into making good, carefully considered decisions, try to master my craft, and write the best code I can. However, to me this is the base line, not something I only do on selected projects. So it is hard to look back and point out a single project, or piece of code, that I feel really proud over. I can however, think of a couple of projects that didn't turn out so good. Not because we didn't put a lot of effort into them, but because they weren't that good ideas to start with.

Book of the (last) month

I have been listening to the Coding Blocks podcast for a while. One series of episodes focus on Uncle Bob Martin's book Clean Architecture. I have already read that book and I enjoy hearing other reflections on the content. However, many times they compare topics in the book with things in Eric Evan's book Domain Driven Design (DDD). Since I haven't read DDD it is hard to follow the argumentation of the comparisons. Therefore I have decided to get a copy of DDD and read it through. Here's a link to the book on Amazon. Take a look.

Another month of TDD

Sad to say that I haven't been coding as much as I want to during the last weeks. There are a couple of reasons for this. One is that I have been sick. Three weeks straight of coughing and fewer that comes and goes. Terrible! You could think the reason for this is that I just sit on my butt all day coding. But that is not true. I actually have been training long distance running three times per week during the last year, aiming for completing a full marathon in 2019. Anyway, hopefully I will get well shortly and stay that way for some time now. The second reason for me not coding as much is that I have been working with bugfixing/support during the last month. It is not something that I, or anyone(?), enjoy doing for longer periods of time, but sometimes you just need to. So, not much to say about TDD this time. But I will stick with it. I am planning to do some of the more advanced Katas on Codewars or Hackerrank and those can be good candidates for TDD.

Plan to throw one away

One of the chapters in the famous book "The mythical man month" by Fred Brooks is titled "Plan to throw one away". The idea is that you should plan to throw the first version of your software away, and then re-write it the way it should be. It is very likely that you will end up with a better written product and the total time spent will be less than it would have been trying to fix all mistakes you made in the first version. It might sound counter-intuitive, but throwing the first version of the product might save you both time and money. It should be noted that the first edition of the book was published in 1975, long before agile software development techniques and things like Scrum became the reality of every software developer. However, with Scrum we've seen to forgotten this completely. We do not plan to test things out for one sprint, then throw it away and do it correctly the next. No, we want to deliver costumer value every single sprint, all the ti

Another TDD insight

Recently I have been writing some completely new code using TDD (no dependencies to existing functionality). With Kent Beck's money example fresh in memory I realized that I should write the tests, defining the wanted functionality, without any thoughts on the implementation. The application code should then be written without any constraints on number of classes etc. When I wrote the application code I tried a number of different approaches, adding and removing classes along the way, until I ended up with something that was clean and easy to extend when needed. All the time I had the tests running so that I could feel confident that my changes did not break anything. Also, as I kept adding new tests, some of the already existing ones became redundant, so I removed them to avoid duplication. Now, the tests does not cover every single edge case, and I am still unsure if it is the responsibility of the tests written during TDD to do that. Any thoughts on this are welcome.

Insights from Kent Beck's "The Money Example"

A very well known book on Test-Driven Development (TDD) is Kent Beck's Test-Driven Development by Example. I have just read through the first part, The Money Example, and now I am following it by writing the code i C# (most parts translate directly from Java to C#). One of the big insights I got from following Kent's thoughts is that a lot of effort should be put into the refactoring step. Kent quickly writes a small test followed by a simple implementation to make it pass, in many cases just returning a constant value. Then the big part of the work starts, making the application code generic and clean. Refactoring the code involves removal of duplication. Here an important insight is that there might be duplication not only of code, but also of data. For example, assume that the test expects the value 10 to be returned by the application code. Hard coding the application code to return 10 is data duplication and must be removed in the refactoring step. I believe that the

Uncle Bob's Bowling Game Kata

I found an easy TDD kata that you can use if you want to try out some TDD. It is written by Robert C. Martin (Uncle Bob) and can be found here . The code is in Java, but it is easily translated to any other C-like OO language. I wrote it in C#. You can find my code on https://github.com/Backhage/BowlingGameKata Even though it is easy I learned some new things by doing it. If you use Visual Studio and write the code in C#, you will notice how much you can use the "Exract method" feature when doing this kata. Breaking out variables and naming them properly will make "Extract method" really handy. Give it a try!

A month of TDD

It's soon been a month where I have gone hardcore TDD. Everything I code at home and everything I code at work has been done using the three rules of TDD: You are not allowed to write any production code unless it is to make a failing unit test pass. You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures. You are not allowed to write any more production code than is sufficient to pass the one failing unit test. Now, at home this is quite easy to follow, since home projects are almost always green field projects. However, at work it is brown field, and worse, the code at work is legacy code (in the way Michael Feathers defines legacy code. That is, code without tests). So, I have spent a lot of time putting existing code under test. Which is not always easy when it isn't designed to be easily testable to start with. At least, the parts where I am thinking about making changes has to be put under test. Fort

Professional Test-Driven Development with C# - part IV

Part IV is the final part of the book. It is titled "Requirements and Tools" and covers how to handle changes to the understanding of the requirements (you update the tests, add more tests if required, and change the application code accordingly), and lists a number of framework that can be used to make TDD easier. There is not much more to say about Part IV so I'll summarize the whole book instead: I was not impressed. Will pick up a copy of Kent Beck's Test-Driven Development: By Example and hope that one is a better read.

Professional Test-Driven Development with C# - part III

The third part of the book is called "TDD Scenarios" and handles how to test some things that usually is considered hard to test. This includes ASP.NET, services created with Windows Communication Framework (WCF), and graphical user interfaces created using the Model View ViewModel (MVVM) pattern. As in previous parts this heavily relies on third party frameworks. However, the essence is good. This is the best part of the book so far, just because it shows that it is possible to develop even these things using TDD. I would recommend looking into this part of the book if you ever are to develop something using WCF or MVVM. However, I am disappointed with the quality of the book in regards to the code samples. There are several copy/paste mistakes which are so obvious that a simple read through before sending the book to print should have been sufficient to find and correct most of them. A short review of part IV is coming up soon.

Professional Test-Driven Development with C# - part II

Ok, so let's do a quick review of Part II, chapters 6 to 8, of Professional Test-Driven Development with C#. Well, I get it. I think. It is hard to write an entire book on the topic of TDD. Part II is labeled "Putting basics into action" and here the author describes, quite detailed, how he usually works. But unfortunately only a small part of it actually covers writing code. Instead a lot of pages are used to describe how to define the project, how the author and his team defines user stories, the development process they use for Agile software development and then it is framework frenzy again. Frameworks covered is this section includes, NBehave, NHibernate, Fluent NHibernate, and Ninject. The author uses those for writing a total of two unit tests and one integration test. Most of the code describes how to use the frameworks, and very little is actual implementation. So far this book is targeting a person, or team, that wants ideas on how to set up a new C# proje

Professional Test-Driven Development with C# - Review of the first 5 chapters

There is a lot of resources available online when it comes to TDD. However, I have always found that a good book is better than most online resources. Therefore I borrowed home a book called 'Professional Test-Driven Development with C#' by James Bender and Jeff McWherter. So far I am 5 chapters in to the book (about 1/3) and here is some of my reflections regarding the content: The book provides many code examples, which is positive. There is however at least one code listing that is incorrect (looks like the wrong listing was inserted). The authors put great emphasis on Red-Green-Refactor. That no application code should be written before there is a failing test for it. Still in chapter 5 they write the application code first and then add the tests later - WRONG! A lot of focus is put on the use of frameworks. I understand that you shouldn't re-invent the wheel and that choosing a good test framework, like NUnit, is a good thing to do. However, you should be careful

Does TDD really improve software quality?

I have asked myself this question several times, and searched for answers, without coming up with any clear answer. Therefore I have decided to go hard core TDD for a longer period of time (at least 6 months) to really evaluate the effects. There are several things that I find confusing when it comes to TDD. One example is what actually defines a unit test. What is a "unit" anyway? After reading a bit about it I found a text claiming that the "unit" is "a unit of work", i.e. something quite small. Like converting a string to UPPERCASE or splitting a string into an ['a','r', 'r', 'a', 'y'] of chars. This work is usually performed by a single call to a single method in a single, isolated, class. So, what does it mean that a class is isolated? Does it mean that it doesn't have any dependencies to other classes? NO! In the context of TDD it means that any dependencies are supplied by the test environment, for exa

A quick way to get started with Clojure

Wish to try out some Clojure (you really should, the need to modify existing values in memory is a thing of the past)? Take a look at Clojure Koans , a great way to get some hands on experience using Clojure. I really hope that functional programming, or at least the idea of creating new values instead of altering the location in memory of the current value, grows big. Anyone who has working with multi threaded programs knows that synchronization issues is the biggest source of really nasty bugs today. Limiting these cases to an absolute minimum would make the world of the programmer a lot less painful.