Skip to main content

Posts

Showing posts with the label C#

From crappy to happy - dependency what, now?

Following the introduction on this series on a previous post, we will now talk about dependency injection and how it has the effect of allowing for more testable code. Sometimes when I talk about this concept it is difficult to explain the effect that applying it might have on the tests. For that reason I think it is better to demonstrate with a near-real-world situation. Obviously, keep in mind this is not real code, so don't worry about the design or implementation details that don't contribute to the point being discussed. The code As you can see, it is simple. There's a class called ShipManager (what else?) that receives position updates for the ships. It keeps the last position reported from each ship and does some calculation to see how much the ship moved. It assigns some values to the update and finally it persists the final version of the update. How do we start testing? When you think about it, tests are dead simple. A test either passes or it doesn...

From crappy to happy - refactoring untestable code - an introduction

I started testing my code automatically a couple of years in after starting my career. Working in a small company, there weren't really incentives for us to automate testing and we were not following any kind of best practices. Our way of working was to write the code, test it manually and then just Release It ™ , preferably on a Friday of course. I'm sure everyone can relate to this at some point in their career, because this is a lot more common than the Almighty Programming Gods of the Internet make us believe. I find that the amount of companies that actually bother writing tests for their production code is a fraction of the whole universe. I know some friends who work in pretty big companies with big names in the industry and even there the same mindset exists. Of course, at some point in time our code turned into a big pile of shit . Nobody really knew what was going on and where. We had quantum-level switcheroo that nobody really wanted to touch, and I suspect it i...

Follow up: improving the Result type from feedback

This post is a follow up on the previous post. It presents an approach on how to return values from a method. I got some great feedback both good and bad from other people, and with that I will present now the updated code taking that feedback into account. Here is the original: And the modified version: Following is some of the most important feedback which led to this. Make it an immutable struct This was a useful one. I can't say that I have ever found a problem with having the Result type as a class, but that is just a matter of scale. The point of this is that now we avoid allocating memory in high usage scenarios. This was a problem of scale, easily solvable. Return a tuple instead of using a dedicated Result type The initial implementation comes from a long time ago, when C# did not have (good) support for tuples and deconstruction wasn't heard of. You would have to deal with the Tuple type, which was a bit of a hassle. I feel it would complicate the ...

My simplest and most useful type

I have been doing some introspection on the way I write code to find ways that I need to improve. I consider this a task that one must do periodically so that we keep organized. There is a very, very simple problem that occurs in every application I know: How to return the results of an operation to the user? I've seen many implementations. Some return strings, some throw exceptions, some use out parameters, reuse the domain classes and have extra properties in there, etc. There is a myriad of ways of accomplishing this. This is the one I use. I don't like throwing exceptions. There are certainly cases where you have no choice, but I always avoid that. Throughout my architectures there is a single prevalent type that hasn't changed for years now, and I consider that a sign of stability. It is so simple, yet so useful everywhere. The name may shock you, take a look: Yes, this is it. Take a moment to compose yourself. Mind you, this is used everywhere , in every ...

Why i changed the blog's name

This one's *not* be about programming... mostly. Ok, it is. It always is. This is an explanation on why I changed the name I had for this blog. The previous name was officially Run or Debug, but now I called Left Fold. Why would you do that, you ask? Well, the main story is because I hated the previous name but still I didn't have the courage (or the will) to change it. And truly, I didn't have a better name in mind... Until recently! I started to learn F# recently and as a guy who comes mostly from C# a lot of concepts were new to me, and some were not new, I just didn't know their name. It has been quite a journey, as anyone who has the same background as me would understand. I jumped from a general OOP language to a non-pure functional language. One of those concepts "learned" is called a left fold. I am aware it does exist in C# too, and it is all but new, but hear me out, I just never had thought about it this way . So, what the ...

Entity Framework - Suporte para múltiplas BD

Uma das limitações que o EF ainda tem é o seu suporte para múltiplas bases de dados. A opção simplesmente não é suportada à partida, apesar de atrair muitos votos no UserVoice . Antes de mais, quero dar crédito aos autores da ideia original. Esta ideia não  foi minha. Eu fiz download do script original, utilizei-o e depois reescrevi-o quase  completamente para lidar com alguns casos adicionais. Eu adoro Linq, por isso aproveitei para utilizar bastante na nova versão. O script original pode ser encontrado aqui . O truque é fazer o EF acreditar que todas as tabelas/objectos mapeados estão na mesma base de dados utilizando sinónimos. Eu não sei se todas as BD's suportadas pelo EF têm alguma feature semalhante a sinónimos, mas isto é certamente possível no SQL Server (que eu estou actualmente a usar). O meu script acrescenta a possibilidade de primeiro fazer backup dos ficheiros edmx  (algo que eu acho útil para evitar que o meu modelo fique corrompido), substitui os pr...

Entity Framework–Multiple Database support

One of the limitations that EF still has is the support for multiple databases. It simply does not support that option.out of the box. Allthough on UserVoice a lot of people have voted this feature, it still doesn’t exist. Credit where credit is due: this is not my original idea. I first downloaded the original script, used it and then i almost completely rewrote it to suit my needs and to improve certain aspects. I love Linq, so i used it a lot. The original and fantastic script can be found here The trick is making EF believe that those objects are in the database by using synonyms. I dont know if every EF-supported database allows synonyms or not, but this is possible in SQL Server (which i am using).   My script adds the ability to backup the edmx files first (which i find useful to prevent my model from being corrupted), replace the prefixes in the resulting model (which i had to do by hand with the other script) and finally reorder the navigation properties by al...

C# 2.0 - Generics

Este é um assunto já bastante discutido pela internet fora. Todos sabemos o que são Generics , e para que são usados, certo? Não. Existe uma variedade de razões pelas quais o leitor pode não saber o que são G enerics, e algumas delas são: O leitor é novo na linguagem, O leitor não é novo na linguagem, mas nunca se deu ao trabalho de tentar aprender. Se o leitor nunca aprendeu generics, isso   não significa que nunca terá de aprender. Se reconhece este snippet, então saiba que já estamos a lidar com generics . Portanto, qual é a vantagem de utilizar generics ? Type safety Generics permite-nos apanhar erros na compilação   em vez de em  runtime,  obrigando o programador a respeitar as regras de type safety que fazem do C# uma linguagem estática. Isto leva-nos a uma produtividade acelerada porque não temos que correr o programa para saber que cometemos um erro. Por exemplo, se no snippet acima tentássemos adicionar um novo item do tipo  string, o comp...

Truques com strings

Hoje, vamos falar uns truques simples com strings no C#. Eu sei que pode ser demasiado óbvio e repetido pela internet fora, mas ainda assim quero dar a minha opinão sobre o assunto. Vamos a isto! Imaginemos que temos uma List de qualquer type e vamos precisar dos seus valores separados por uma vírgula para serem enviados para uma stored procedure . O resultado desejado será, dada uma  List de {1,2,3,4}, uma string neste formato: "1,2,3,4". Como vamos resolver este problema? Já vi e fiz múltiplas soluções para o problema, por isso vamos ordenar as possíveis soluções (na minha cabeça) da mais complexa para a mais simples. Primeiro, podemos fazer isto: Vejam o quão complexo isto pode ser e o quão rapidamente se pode tornar insustentável. Quando repetido múltiplas vezes num projecto (imaginem ter isto repetido na vossa Camada de Acesso a Dados sempre que uma stored procedure  precisa deste input), isto pode tornar-se doloroso. Claro que poderiamos extrair este comportamen...

C# 2 - Static Members

In C# 2 there was a new addition in the functionality called static classes and members . When i say "members", i am referring to methods, properties, events and so on. I have a strong opinion about this modifier which i will share with you along the article, but let's start by looking at what "static" means. Take this code as example: Above we can see that we define two properties and one is static. In the main method we then create an instance of Person and set the normal property ( Name ). Now notice the Person.NumberOfBrains  assignment. This is the static property we created in the class. Notice that the access is made at class level , instead of instance level.  This means that there will only be one NumberOfBrains  value throughout all Person instances, but there will be a Name  value per each instance  of Person . Of course, the example is not the best, but you get the idea. Static applies when all  instances share the same value. There are so...

C# 2.0 - Nullable Types

It's 3 am and i don't feel like sleeping. I've been helping a friend to work on his code and now i'm only partially tired. Well, why not continue with my series on the evolution of C#? Let's do it! So, this time i'm going to talk about nullable types . Everybody used them already, but back in .Net 1.0 they didn't exist. How did you represent a "no value present" value? Sure, string can have null, but null is different than empty, right? How do you represent an empty numeric type then? You check if it is bigger than 0? Well for some cases that's just how developers did it. Either that or create a constant value that represents a "no value". But, to me, that is not expressive enough . Basically, a nullable type is only a non-nullable type wrapped in the System.Nullable struct. This is a generic struct, so it makes use of the Generic features of C# 2.0. The struct is very simple, it contains only a HasValue and a Value proper...

C# 2.0 - Partial Types

For those of you interested, i found a very interesting list of features that were introduced in C# in  here . This is a very complete list that contains all the features, and i'm explaining them one by one in this post series. We've talked about  Generics  and  Iterators . Now it's time for some partial types . A partial type  is a type which definition is spread across one or more files. It doesn't have to be in multiple separated files, but can be. This is a very simple concept that can give us many benefits, let's see: If a type is partial, multiple developers can work on every part of it. This allows a more organized way of working and can lead to production improvement.  Winforms , for example, generates a partial class for the form so that the client can separately edit other parts it. This way, a part contains information about the design and the other contains the logic of the form. In fact, this is a very spread pattern across .Net. Ent...

The evolution of C# - Part III - C# 2.0 - Iterators

It's been a while since i wrote the last post, but i did not forget my purpose of creating a series that shows the evolution of C#. Today i came here to talk about one of the most useful features of C#, even if you dont know you're using it. Let's talk about iterators ! What is an iterator? For those of you who didn't read about the iterator pattern somewhere in the internet or in the "Gang of Four" book, you can read a description  here . The iterator is a class/object/whatever which knows how to traverse a structure. So, if you have a list or collection of objects, an iterator would have the knowledge of how to traverse that collection and access each element that it contains. The iterator is a well known design pattern and is behind many of the wonderful that we have nowadays in .NET (Linq comes to mind). Why is it a feature? Truth be told, an iterator is a concept well known way before .NET even existed. Being an OO Design Pattern, the iterator has...

The evolution of C# Part II - Generics

This is a well discussed matter throughout the internet. Everyone knows about generics, what they do and what they are used for, right? No. There is a variety of reasons why you wouldn't know about generics, and some of them are: You are new in the language You are not new in the language but never cared to learn it Simply because you never learned the basics about generics, it doesn't mean you've never used it. If you recognize this snippet, then you are already dealing with generics: So, what is the advantage of generics? Type safety Generics will allow you to catch the errors at compile time rather than runtime by enforcing the rules of type safety that make C# a statically typed language. This leads to increased productivity because you don't have to run the code to know that something is wrong. For example, if in the snippet above you tried to add a new item of type string, a compiler exception would be thrown. Typically, in C# 1.0, you would use an...

The evolution of C# Part One - The beginning

Today, let's talk about some history. Not that World War history, but the history and evolution of C# as a language. I would like to analyze the principal parts in one of the mainstream languages of mass production in today's software. Beware that most of what i am about to say is the fruit of much research, in part because when C# and the .NET became available i had not written a single line of code yet, so you can say that i am a newborn in this world. I'm inclined to change that, though, but every new discovery is done with much enthusiasm on my part, and i'm very proactive, which sometimes may upset my colleagues. One of the reasons i'm writing this article - and this blog all the same - is because i love to learn new things and share it with others. Enough talk, let's get to the point! The beginning of .Net The .NET platform brings a brand new and fresh way of programming your applications. Microsoft created the term "Managed Code" to refer t...

A tip on strings

Today, let's look at a simple trick with strings in C#. It may be too obvious and repeated around the internet, but nevertheless i want to give my 2 cents on the subject. So, let's start! Imagine you have a list of any type and now you will need this values separated by a comma in order to be processed in some stored procedure. The desired output for a list of  {1,2,3,4} is a string like this "1,2,3,4" . How will you solve this problem? I've seen and done multiple approaches. Let's order the possible solutions (in my mind) from the most complex to the simpler. First, we can do: Notice how complex this can be, and how fast it can become messy. When replicated across an entire project (imagine the nightmare of having this replicated in your Data Access Layer whenever a stored procedure needs this input), this can be a pain. Of course, you could extract the behavior and create an extension method for it, but as we will see, it is not necessary. Our second...