Fortsätt till huvudinnehåll

Inlägg

Visar inlägg från 2017

Clojure time!

Santa brought me a nice Christmas gift this year, Clojure for the Brave and True . A nice book for learning the basics of Clojure. Since I am not that experienced in functional programming, and especially not in Lisp, it feels like a good thing to take it from the start. For those of you unfamiliar with Clojure, check out https://clojure.org/ and read what Rick Hickey has to say about it. Here is one video to check out, The Value of Values (P.S. I really love how Rich looks like Weird Al)

Repositories or Command/Query Objects? What about CQRS? Unit of Work?

From time to time, when I learn something new or want to try out a new approach, I restart my "Record Collector" a project. It is a project I use for testing out ideas, and never gets close to a usable product. This time I wanted to try out creating components and setting up the relationship between them using inspiration from Clean Architecture. The Record Collector application keeps track of different records, and needs some sort of record repository. For my simple application is it enough to just have an in-memory list. But I got curious I wanted to see how larger applications, maybe targeting thousands of simultaneous users, tackles this. What I found was the Repository Pattern and CQRS. Here is some resources for any of you who wants to know how repositories or command/query objects can be implemented in large scale applications: The Repository Pattern (msdn) Youtube video by Mosh Hamedani explaining the Repository Pattern Blogpost discussing Repositorios vs

WPF application using MVVM created

Now I have created my first from scratch WPF application using MVVM. I like the concept of separating the view from the model, making it possible to change the view without having to touch the model. The dependencies also goes in the right direction, from the lowest level (the View) having knowledge of the next level (the ViewModel) that finally has knowledge of the highest level (the Model). No dependencies exist in the other direction. Code can be found on GitHub https://github.com/Backhage/WPF-MVVM-Sample

MVVM, MVC, MVP, eh?

I have never done much UI design. The concepts of Model View Controller (MVC), Model View Presenter (MVP), and Model View ViewModel (MVVM) have only been abbreviations that I know are related to how the UI are split into different entities, but I have never studied them further. Well, now that I have been working with C# for over 1.5 years, with an application that does have a graphical user interface, it's about time. So, goal of the day: learn about MVVM and create a WPF application that implements that pattern. Resource: https://msdn.microsoft.com/en-us/magazine/dd419663.aspx

Uncle Bobs Best Book To Date

I am deep into Clean Architecture, the latest book by Robert C. Martin (a.k.a Uncle Bob), and it is not at all what I expected, it is so much better! A book about Software Architecture must describe architectural patterns like the Layered Architecture, the Event Driven Architecture, the Microkernel Architecture, and so forth, right? WRONG! Uncle Bob attacks the subject from a completely different angle. The goal is a Clean Architecture, an architecture where components are separated in a way that just makes sense. Where code that belongs together is grouped together. Where a teams can work on different parts of the code without stepping on each other toes all the time. And where the software remains soft (i.e easy to change). I would say this is a book for the experienced programmer / software architect. To really understand the benefits of the architecture that is described you need to have seen some bad examples in real life. Once you have worked on new features that requires y

Clean Code

While I am awaiting the Clean Architecture book (the online bookstore I usually buy from was out of stock) I will sweep through Clean Code yet another time. Now that I have been working exclusively with OOP for 1.5 years it will probably be more rewarding to read it than it was the last time, when most of the code I wrote was procedural. I am confident that there are are many ideas in Clean Code that I can apply at work to make our code easier to understand and work with on a day to day basis.

Clean Architecture

I have just ordered a copy of Robert C. Martin's (Uncle Bob) latest book,  Clean Architecture . I firmly believe that a professional software developer should be able to solve complex software tasks, write clean and highly maintainable code, AND have a good understanding of the system's architecture. Unfortunately I have a large knowledge gap when it comes to software architecture, sure I am aware of different architectures like the layered architecture, the now so popular microservice architecture, event driven architecture, and so on. But my experience in this area is that someone with the title "Software Architecture" draws a lot of diagrams on he thinks that the system should work and then the development teams implements it the way they want it without paying much attention to the diagrams. Here I think that both the architectures and the developers need to improve. The architectures should be part of the development team and involved in the daily day-to-day

Dynamic Programming

Since last time I have been looking a bit at Dynamic Programming (DP) and in particular combinatorial optimization problems, for example  the Knapsack Problem  and the  Change-making problem . For those of you that are interested in learning more about DP check out GeeksforGeeks  resources on DP . Here you will find reading material plus a LOT of different practice problems.

Been reading up on Dijkstra's search algorithm

Last weeks have been a bit slow on the algorithm front. Still on it though. I have been solving some Graph challenges on  www.hackerrank.com  and reading several different texts on Dijkstra's search algorithm. It seems like this is an algorithm that is a bit tough to understand and implement in a correct and efficient way. Dijkstra's algorithm can be used on graphs with weighted edges, i.e. different paths have different costs. As long as the weights have positive values Dijkstra's algorithm should work fine. The procedure is quite similar to Breadth First Search, the difference here being that the total edge weight can be less even when more edges are involved. It is therefore necessary to keep track of the current total, and if a shorter path is found, update the total and the parent node (can be used for printing the vertices visited when traveling the shortest distance from vertex v1 to vertex v2). Dijkstra's algorithm is also greedy, in the sense that it visi

Implemented some search algorithms

In order to get a good understanding of the differences between different sorting algorithms I decided to implement some of them myself. The sorting algorithms I implemented were Insertionsort, Heapsort, Quicksort, and Mergesort. These happens to be the same sorting algorithms that are used in the .NET framework. See  https://msdn.microsoft.com/en-us/library/b0zbh7b6(v=vs.110).aspx (Insertionsort, Heapsort and Quicksort used for System.Collections.Generic) and  https://msdn.microsoft.com/en-us/library/bb534966(v=vs.110).aspx (Mergesort used for IEnumerable.OrderBy). I have published them to GitHub for those who wants to take a look, see  https://github.com/Backhage/.NET-Algorithms Now I will continue and implement some Graphs algorithms, starting with Breadth First Search (BFS).

What does those version numbers mean?

Ever wondered what version numbers on software really means? What is the difference between version 1.0.1 and 1.1.2? And what about version 1.9.2 vs version 2.0.5? Well the truth is that there is no law that everyone has to follow, but if you are looking for some good guidelines and a specification that you can apply at your company, I suggest you take a look at  http://semver.org/spec/v2.0.0.html . The Semantic Versioning Specification is a set of rules that describes how to handle the version numbers of your software. It describes when to bump each part of the number, and how to add information about alpha or beta status. Even for components that are only used internally it is a good idea to have a common rule set regarding versioning. Only then does the version number really start to have meaning. So next time you make a breaking change to the public API, be sure to increment the major version!

Is it necessary to have some basic knowledge of algorithms and datastructures in order to be a good programmer?

The short answer, yes, absolutely. This is a follow up to my previous blog post where I claimed that you don't need to know advanced algorithms by heart in order to be a good programmer. That is still totally true. However, you should have at least some basic understanding of algorithms and data structures. Having this knowledge will help you select the correct tools for the job, for example knowing when to use a stack over a queue, when a linked list is a better selection than an array, when to use a hashset, or a dictionary, and so on. This will help you write easier and more robust code. It is also a really good idea to have some feeling for how your code will perform when input data grows. How will memory consumption and running time be effected if the input data grows by a factor 100, or 1000? This knowledge will help you identify performance bottlenecks in your application and help you come up with ideas on how to attack them. So, if you haven't done it already, ta

Do you need to be able to solve complex algorithmic tasks by heart in order to be a good developer?

Short answer, no, absolutely not. If your daily work consist of designing algorithms and implementing them in code, then you should have a good understanding of algorithms and how to adapt and apply well proven solutions to various problems. However, 99% of all development work does not involve writing complex algorithms. Take a look at the source code of any software. The absolute majority of the code will not involve any complex algorithms at all. Hence, there are a lot of other qualities that are far more important in order to be a good software developer. One of the top qualities is the ability to write clear and simple code that is easy to understand. Avoid using complex solutions unless absolutely necessary, keep the code as short and simple as possible and use clear naming. Another important quality that makes a good software developer is the ability to quickly find information and adapt it to the problem you are working on. Today there are tons of information available onl

Finished Algorithms part I

I really enjoyed the Algorithms course "Algorithms Part I" on Coursera. So much that I enrolled on another algorithm course (more on that in another post). The course is not easy. It requires quite a lot of effort in order to complete the programming assignments. But it is worth the effort. So, if you like some good programming challenges, I really recommend taking the course. You will also have a much better understanding on what impact different solutions will have on your application and how well it will scale. Most software programmers can write a program that handles tens or hundreds entries of data. Handling millions or even billions is a whole different story.

Algorithm time

Me taking a course on algorithms has been long due. Finally I have enrolled in (and successfully started) an algorithm course on Coursera. The course is given by Princeton Univerity and is simply called "Algorithms, Part I". Find more info about the course here: https://www.coursera.org/learn/algorithms-part1

More on F#

I have read and experimented quite a lot with F# during the last weeks. Must say that I am starting to like it. For those of you interested I recommend taking a look at the O'Reilly book "Programming F#" and starting with some basic Katas at Codewars. Personally I wrote a small file hashing application in F# today. Did a similar tool in C# a while ago and wanted to try out coding it in F# as well. Anyone interested in looking at the code can find it on GitHub: https://github.com/Backhage/FSharpFileHasher

Take a look at the beautiful F# code

I have taken a special interest in parallel and asynchronous data processing in F#. The absolute majority of the really hard to fix bugs that I have come across during the last years all have one thing in common, thread safety. Or rather, the lack of thereof. It is very easy to write a class in C#, Java, or C++ that is not thread safe. And if you try to make it thread safe it quickly can become quite complex and it is easy to forget to put a lock on a variable or make some subtle mistake that makes the lock useless (locking on a reference to an object that you later make a copy of, which makes locking the old reference useless, is a not so uncommon mistake that can be really hard to spot). Another thing about thread safety is that it is really hard to test for. All your tests might run perfectly fine, but then when you go into production, things starts crashing in really strange ways. F#, and other functional languages, addresses these problems and makes it easy to write code tha

Another go at functional programming

I have been wanting to learn functional programming for real for a while now. I must say, it has been tough. Being used to procedural and object oriented programming languages like C, C#, and Java, I am used to being able to grasp new programming languages quite fast. But functional languagues, that's a completely different story. In pure functional programming there are no variables, no states, none of the things you are used to in an object oriented language. It is like starting over from scratch. Let me give you an example, assume you want to calculate the sum of all even numbers between 0 and 100 squared. How would you go about implementing that? Well, I would define a variable, sum, that keeps track of the sum so far. Then I would create a for loop, for (int i = 2; i <= 100; i += 2), in which I add i * i to sum. In functional programming however, you should avoid mutable values and loops. So what to do? Well here is one example on how you can do it in F#: [0..100]

Some reflections on time consumption creating new threads

Today I wrote some tests with the goal to verify thread safety on a part of production code. Using TDD I wrote a test that started two new threads that both updated the same object, and while they were running I verified the object's data. By putting this in a loop I was able to get a unit test that failed on each run. By adding locks at the correct places I got the test to pass. But looking at the time it took to run the test I noticed that it was quite slow. I knew that the updates to the object's data were fast and started wondering if it was the start and join of the threads that were slowing it down. So, instead of using new Thread(task) I switched to using Task.Run(task) and task.Wait() instead of thread.Join() . The main difference here being task adding a job to a pool of worker threads while new Thread creates a completely new thread that is stopped and disposed after it has run to completion. By doing this small change the test time decreased by 25% (from 80

Some database theory

For reasons at work I am currently looking into how storing and retrieving data from databases works. Was introduced to an abbrivation that I didn't know of earlier, ACID. ACID is a combination of Atomicity, Consistency, Isolation, and Durability. Atomicity - requires each transaction to be "all or nothing". A transaction may consist of several writes to the database, however, if any of these fail, or is interrupted, the entire transaction must be invalidated in order to have the database in a valid state. Consistency - requires that any transaction will bring the database from one valid state to another. No transactions may currupt the database. Isolation - ensures that concurrent transactions results in a system state that would be obtained if they were executed sequentially . Read that sentence again, it is a tricky one. Be able to perform concurrent transactions in a way that the result is like they have been done sequentially... Durability - ensures that a tra

Design Patterns Overview - Observer

The observer pattern is a behavioral pattern that lets several objects, observers, subscribe to state changes at another object, the Subject. As with the Iterator, the .NET framework contains interfaces that are recommended when implementing the design pattern. These are named IObservable and IObserver. The subject should implement the IObservable interface while the observers implement IObserver. Of course, you do not absolutely need to use these interfaces in order to implement the observer pattern but it is good to know that they exist.

Design Patters Overview - Iterator

The iterator design pattern is an integrated part in many languages and frameworks. In C# you can implement the IEnumerable interface (defining the GetEnumerator method) to make a class iterable. Using the yield keyword makes the method return an iterator. This is so simple in the .NET framework that I did not bother to create a UML diagram this time. Check the code in my GitHub repository  for an example on how to implement IEnumerable.

Design Patterns Overview - Factory

No software design patterns overview can be complete without describing the Factory pattern. I would say this is one of the most commonly used patterns. Let's get right to the UML diagram. As can be seen an interface, Creator, is defined for creating a Product, but it is the ConcreteCreator that decides which subclass of Product to instantiate. From the client you instantiate the ConcreteCreator and use that to create the products. It is the resonsibility of the ConcreteCreator to see to it that the product is created correctly. This adds a nice level of abstraction since any changes to how the ConcreteProduct is created only needs to be reflected in the ConcreteCreator. The users of the product does not need to change their implementation.

Design Patterns Overview - Decorator

Ok, time for a structural pattern. I really like the Decorator pattern idea. Basically you create an abstract base class, Component. This you subclass to create concrete components, AND, to create Decorators. The decorators add functionality to the concrete components, and since they all subclass the abstract components you can add several decorators, add just the functionality you need. As with the previous patterns I have added example code in my  repository on GitHub .

Design Patterns Overview - Builder

The Builder Pattern is another creational pattern. It is used for creating different setups of complex aggregated objects. This sounds a lot more complex than what it really is. One easy to understand parable I like is when you go to a fast food restaurant and order a hamburger meal. In order to create the meal, different parts need to be combined. There might be 5-10 different burgers, fries or salad, different soft drinks etc. Ok, so create (build) a meal, start off by creating a new HamburgerMealBuilder, then using that you define the type of burger, fries or salad, Coke or Fanta, and so on until you have the complete meal. There you have it, a perfect use of the builder pattern. To understand the diagram better, take a look in my repository on  github . And by the way, do not use the C# code from Wikipedia, it is incorrect (the [NotNull] attribute does not exist any more, and far worse, the CarBuilder does not Build new cars, it only hands of references to the same single o

Design Patterns Overview - Prototype

Second pattern out is the Prototype pattern. This is a simple creational pattern that you can use when you want to create an object that you later on wish to create many copies, clones, of. The clones will get the same properties as the prototype. In my sample code  on github  I use the  MemberwiseClone  from the .NET framework. Take note that this creates a shallow copy of the object. Any references that the object holds will not be cloned, hence both the original and the clone will reference the same object. If you do need a deep copy, there is information available on the  MemberwiseClone  page on different options to achieve this.

Design Patterns Overview - Abstract Factory

I am currently involved in designing a new feature for a product at work. When discussing with one of the architects I realized that I need to refresh my memory on Software Design Patterns. First out is 'Abstract Factory'. I created a UML diagram using PlantUML. The name of the interfaces and classes are heavily inspired by the information available on Wikipedia. Sample code (C#) that demonstrates this, and other patterns, are available in my repository on github . The source for the PlantUML diagrams are included.

Next project, artificial neural networks

After I finish the Asteroids clone in Java (I now have a running version, but without all the polish) I am planning to read up on, and test some, artificial neural networking. The little I have read about it so far sounds very interesting. I am planning to start off with  this course  on Practical Deep Learning For Coders. A course that handles image recognition, convolutional neural networks, over fitting and under fitting, embeddings, natural language processing (NLP) and recurrent neural networks. Lets get finished with the game! (I have had a slow week since I have spent several days in bed with a fewer, not able to function at all, but now it starts to feel better).

Regarding the new features in C# 7.0

I have read through the  New Features in C# 7.0  blog post on Microsoft Developer Network (MSDN) and also tried them using Visual Studio 2017. My conclusion is that there is nothing revolutionary in C# 7.0. The features are all "nice to have" stuff. Out variables It is now possible to declare an out variable right where it is passed as an out argument. Example: // Before C# 7.0 int x; int y; GetSomeInts(out x, out y); // From C# 7.0 GetSomeInts(out int x, out int y); Personally I think this can be good to limit the scope of variables when using the Try-pattern (a method that returns a boolean to indicate success or failure and results as out parameters): if (TryParse(s, out string a, out string b)) {     // string a and b in scope and can be used here. } else {     // string a and b not in scope. } Pattern matching I am not a big fan of passing generic "objects" around and letting methods behave differently depending

Genetic Algorithm Kata - Done!

Continued with the games programming a bit - adding a Polygon Wrapper class that lets polygons wrap around the edges of the screen. Interesting solution. Also took a break from the games and solved a 2 Kyu task on Codewars that involved implementing a genetic algorithm. It was really interesting to see how such an algorithm can be used to solve a specific problem. The kata, with a thorough description, can be found on Codewars:  https://www.codewars.com/kata/526f35b9c103314662000007 Good stuff! Give it a try.

Async Delegate BeginInvoke Callback Example

I found it hard to find a straight forward example of Asynchronous invocation of a delegate using BeginInvoke and a callback that is called when the delegate is completed. So I wrote one myself. 1: using System; 2: using System.Runtime.Remoting.Messaging; 3: using System.Threading; 4: 5: namespace AsyncDelegates 6: { 7: public delegate int Add(int a, int b); 8: 9: class Program 10: { 11: private static volatile bool isCalculating; 12: 13: static void Main(string[] args) 14: { 15: Console.WriteLine($"Main() running on thread {Thread.CurrentThread.ManagedThreadId}"); 16: var theDelegate = new Add(Adder); 17: isCalculating = true; 18: theDelegate.BeginInvoke(7, 5, AdderCallback, null); // Runs the Add method on a separate thread. Calls AdderCallback when Add has finished. 19: while (isCalculating) // The isCalculating boolean is set to false in the AdderCallback method.

Games programming update

Still focusing 100% of my limited spare time on getting through the games programming book. Currently reading up on, and implementing, algorithms for intersection testing. Now I know what an Axis Aligned Bounding Box is ;).

Learning some Game programming

I recently bought a book called  Fundamental 2D Game Programming Java  that I am reading/coding through. The fact that the example code is written in Java is nothing that should scare you away from this book. All concepts that are explained are generic for game programming and not specific to Java. Currently I am at chapter 4, time and space, and have learned how to keep movement speed intact independent on frame rate and now I am learning how to transform world space to screen space. It is interesting to learn some new concepts that are different from the coding I have done previously. If you want to look at the code I have a  repo available on GitHub . Currently there is an Eclipse project file available so it can be imported easily to Eclipse. I am however considering using IntelliJ instead.

Taking the next Dvorak step

I have been using some kind of sv_dvorak hybrid for the last year or so. The layout I have been using has all the shift+digit and alt-gr+digit combinations intact. This however means that characters often used when coding, like (), {}, and [] requires some really awkward positioning of the fingers to type. Therefore I have decided to go all in on the  Dvorak Simplified Keyboard . This layout is also included by default in Windows so no need to install any external programs or layouts when using a Windows computer (as I do at work). With this change I will have no use of looking at the keys on the keyboard. Maybe I should go for an all black, completely blank,  Das Keyboard Ultimate .

Wish to create services with .NET?

If you wish to create service based applications (microservices is the hype, right) using .NET I suggest taking a look at Windows Communication Foundation (WCF). Links can be found below. WCF is a .NET framework that makes it easy (relatively speaking) to build service based applications. It works well for sending both simple and very complex data between service endpoints that can be located both locally and remote. Take a look at the introduction to WCF presented here:  What is WCF And take the Getting Started Tutorial here:  Getting started tutorial Note that there are some minor errors in the tutorial text but I am sure you will be able to figure it out.