Becoming a software developer – episode III

Becoming a software developer – episode III

Welcome to the third episode of my course “Becoming a software developer”, which will give you a quick overview of the core parts of the C# language will let you design better types and deal with errors in a proper manner.

All of the materials including videos and sample projects can be downloaded from here.


 

Scope

This episode will focus on the following parts of the language:

  • Generics
  • Exceptions
  • var

Abstract

Generics

By now, I’m pretty sure that you’ve already used some strongly typed collections while playing with your simple C# applications – for example List. And I guess that you were wondering what is the meaning of these parentheses? This is how we declare a generic type within our classes or methods. Generics provide a great amount flexibility by not having to define e.g. the strongly typed collections (which are classes) as in the previous example or methods that are tied to the specific type. They can also have the constraints, so we can make them both – flexible and secure and be certain that our custom generic types will not be misused.

Exceptions

Errors will always be the part of our software whether you like it or not, and it is our duty to deal with them in a proper manner. There are numerous ways how to handle the exceptions and I’ll present to you one of the approaches that I tend to use on a daily basis. Although, it doesn’t seem too difficult to put everywhere try/catch/finally blocks in order to handle the errors, as usual, the devil lays in the details – how to propagate them and report to the end user.

Keyword var is quite an interesting one as some people love it (like myself), some hate it and some have a rather mixed feelings. Given that you’ve ever worked with language like JavaScript you should feel like at home. By using var you can declare a variable (assign some value to it) without specifying the actual type, as the compiler knows what it is. For example, you can do the following:

As you can see it reduces a lot unnecessary (IMHO) code which would be typing a full type name on the left side of the variable (just like you were doing at the very beginning).
I tend to use var everywhere, however, it might be the good advise to use it only if you know the type that you’re assigning var. For example, if you would like to declare a variable by using var and assigning it to a result of some method that is not visible at the first sight, you might consider using a full name type on the left side. But like I said, personally I do use it almost everywhere and it’s really a matter of your personal (or team that you’re working with) choice.

Anonymous types are the other benefit of using var – e.g. you can do the following:

This is a regular object and you can access its properties like you were using a class. This feature has its usage for example when you want to perform a mapping (transforming one object into another) without a need to specify a class for the second type. With var you can quickly achieve such goal by creating the anonymous objects.

Resources

  • https://www.pluralsight.com/courses/csharp-generics
  • https://www.pluralsight.com/courses/csharp-best-practices-collections-generics
  • https://www.youtube.com/watch?v=gyal6TbgmSU
  • https://www.tutorialspoint.com/csharp/csharp_generics.htm
  • http://stackoverflow.com/questions/77632/what-is-cool-about-generics-why-use-them
  • http://stackoverflow.com/questions/10956993/out-t-vs-t-in-generics
  • http://stackoverflow.com/questions/6723082/what-does-an-in-generic-parameter-do
  • http://stackoverflow.com/questions/10027611/what-does-out-mean-before-a-generic-type-parameter
  • http://softwareengineering.stackexchange.com/questions/272712/why-is-the-out-keyword-used-in-two-seemingly-disparate-contexts
  • http://stackoverflow.com/questions/8913814/why-do-c-sharp-out-generic-type-parameters-violate-covariance
  • https://msdn.microsoft.com/en-us/library/ms173160.aspx
  • https://www.dotnetperls.com/exception
  • http://stackoverflow.com/questions/14973642/how-using-try-catch-for-exception-handling-is-best-practice
  • http://csharp.net-tutorials.com/advanced/exceptions/
  • http://stackoverflow.com/questions/4307467/what-does-var-mean-in-c
  • http://answers.unity3d.com/questions/1087276/why-woud-i-use-var-in-c.html
  • http://softwareengineering.stackexchange.com/questions/42863/explicitly-defining-variable-data-types-vs-using-the-keyword-var
  • https://www.intertech.com/Blog/the-use-and-abuse-of-the-c-var-keyword/
  • Next

    • Delegates
    • Lambda expressions
    • Events

    In the next episode, we’ll talk about the delegates, lambda expressions and events. You’ll see how the language has been evolving within latest years into supporting some advanced concepts of the functional programming paradigm, which are extremely useful and help to reduce a lot of boilerplate and repetitive code.

    13 Comments Becoming a software developer – episode III

    1. zawisz

      Robisz robotę ziomeczku! Pomimo, że już troszkę programuje (nawet zawodowo – junior) to z tych pierwszych części kursu nadrabiam taką ilość niewiedzy (podstawowej), że jestem w szoku :O

      Pozdro Spetzu!

      Reply
      1. olek

        Cześć.
        Dobrze wiedzieć, że to od razu dobre podstawy.
        Ja jestem początkujący i cieszę się, że doświadczony programista chwali to, że podstawy są mocne.
        Jeśli ja mogę się na coś przydać, proszę o info.

        Reply
    2. Pingback: Patryk Huzarski | Personal Blog

    3. 0xmarcin

      I have a small remark, should really Pair extend Triple? Is Pair a Triple, I don’t think so, moreover if you use inheritance you lose some type checking protection (you may pass triple to method that expects pair – sometime this makes sense, sometimes its don’t). Since this is course for new developers I think composition should be promoted over inheritance from day one, in this case you may even want to just copy-paste fields IMHO.

      Reply
      1. Piotr Gankiewicz

        Good remark. In this sample, the Pair could be treated as TupleOfTwo while the Triple as TupleOfThree – I just wanted to keep the names rather simple :). And like I said at the beginning during the Q&A session, the composition is much better choice than inheritance, so I totally agree with you in that matter.

        Reply
    4. Pingback: Dew Drop - February 9, 2017 (#2418) - Morning Dew

    5. Kuba

      Cześć, w pierwszym linku do pluralsight wkradł się mały błąd i na końcu jest “<" prowadzący do 404. Natomiast kurs sam w sobie jest świetny 😉 Masz bardzo fajne podejście i dobrze wyjaśniasz podstawy. Cały semestr programowania na uczelni dał mi mniej niż Twoje parę godzin kursu.

      Reply
    6. Sebastian Pietrzak

      Cześć.
      Bardzo dobra robota.. 🙂
      Chciałbym zapytać o przypadki (może masz taki zestaw albo z doświadczenia) jakie operacje otaczasz blokami Try – catch? Np. jakaś obsługa plików.. ale co jeszcze? Może jakiś link z opisem takich sytuacji?

      Reply
      1. Piotr Gankiewicz

        Cześć,
        Dzięki! Jeżeli chodzi o try/catch to wszystko zależy od aplikacji. Na pewno musisz mieć takie konstrukcje w miejscach, w których wyjątek mógłby spowodować wyłożenie całej aplikacji (ew podpinasz się pod jakieś konkretne zdarzenie typu OnError jeżeli dany framework coś takiego udostępnia i tam obsługujesz błędy).
        Osobiście w aplikacjach webowych normalnie propaguję wyjątki i po prostu korzystam właśnie z takiego filtra lub callbacka, w którym sprawdzam jaki to jest rodzaj wyjątku i np. zwracam z poziomu API/widoku odpowiedni komunikat o błędzie. Gdy tworzę rozproszoną aplikację i mam zbiór (mikro)serwisów, to tutaj zazwyczaj stosuję podejście Command/Event handler i każdą operację opakowuję takim blokiem, przy czym całość ukrywam zgrabnie pod interfejsem.
        Taki przykładowy kod możesz zobaczyć np. tutaj:
        https://github.com/noordwind/Collectively.Services.Remarks/blob/master/Collectively.Services.Remarks/Handlers/CreateRemarkHandler.cs

        A sam interfejs IHandler/IHandler służący do opakowania tego wszystkiego jest tutaj (metody Execute):
        https://github.com/noordwind/Collectively.Common/blob/master/Collectively.Common/Services/HandlerTask.cs

        Reply

    Leave a Reply to 0xmarcin Cancel reply

    Your email address will not be published. Required fields are marked *