Why should you use F# when your team uses C#?

0

Why does functional programming matter?

Functional programming is the new hotness right now, but regardless of the hype, most modern programming languages are introducing FP-friendly features that make a big difference to software quality:

  1. Delegates
  2. LINQ
  3. Read-only properties
  4. Pattern matching
  5. Readonly value types
  6. Tuples

As we’re adding features and applying good software engineering practices, we’re actively working to make sure that the code we’re trying to implement is correct. An OO first language like C# provides support for this thanks through features such as static typing, scoping and access modifiers. If you make a mistake, the compiler will warn you. Although those features are great, there’s more that can help the developers to reason with their code and make sure that the code that was either added or maintained will behave as expected and have little to no ripple effects in the system(s).

That’s where functional programming shines. By embracing concepts such as immutability, developers have access to an implementation that is more predictable and less likely to have a mutation that wasn’t foreseen since you have 100% control on what is updated.

More to this is the declarativeness of the implementation. The F# type system evolves through expressions which makes the code declarative when embracing the functional paradigm. Here, we can focus on the concepts and make sure the workflow pipeline corresponds to the business requirements.

Another thing that helps developers in functional programming is that the strict type system is actually consider a friend. There’s a saying in the FP community that says once it compiles, it works. What’s to be understood with functional programming is that with a type system that is more strict, it like having compile-time tests that make sure the implementation is correct.

What is F#?

F# is a functional programming language that makes it easy to write correct and maintainable code.

F# programming primarily involves defining types and functions that are type-inferred and generalized automatically. This allows your focus to remain on the problem domain and manipulating its data, rather than the details of programming.

More here

 

Are there any company in the industry that use F# internally?

A month ago, I stumbled across a list of companies using Haskell in the industry. This kind of project was interesting and I couldn’t find one for F#. To solve that problem, I created a list of companies using F# and the F# community was really great and helped me expand that list. I invite you to take a look at the list!

The TIOBE Programming Community index is an indicator of the popularity of programming languages. The index is updated once a month. The ratings are based on the number of skilled engineers world-wide, courses and third party vendors. Popular search engines such as Google, Bing, Yahoo!, Wikipedia, Amazon, YouTube and Baidu are used to calculate the ratings. It is important to note that the TIOBE index is not about the best programming language or the language in which most lines of code have been written.

So by consulting the TIOBE list along with the result of the developer insights from stackoverflow, we can see that F# is quite popular in the professional and hobbyist worlds. When looking at functional first languages, F# comes on top and is located in the top 5 of the most paid programming languages globally.

2019-09-10_17-21-19

2019-09-10_17-00-33

The mission of the F# Software Foundation is to promote, protect, and advance the F# programming language, and to support and facilitate the growth of a diverse and international community of F# programmers.

Are there any companies that benefited from using F# in their product?

Kaggle: [..] we initially chose F# for our core data analysis algorithms because of its expressiveness. We’ve been so happy with the choice that we’ve found ourselves moving more and more of our application out of C# and into F#. The F# code is consistently shorter, easier to read, easier to refactor, and, because of the strong typing, contains far fewer bugs

Counterparty Risk Handelsbanken: Our first delivery is approaching rapidly and F# has proved itself as a real life-saver. We started off using C# in many places but have since then moved almost entirely into F# due to its ability to reduce the amount of code required and its simplicity when developing massive parallel computations. The performance is phenomenal. We can now re-calculate the entire bank portfolio from scratch in less than a second and the response-time for single deal verification calculation is far below 100 milliseconds(the original demand was 200 milliseconds to make the application usable for electronic markets). Although some gains are to be attributed to how we have built our calculation models, F# made it possible for us to implement our algorithms and techniques with very little code and with a huge similarity to the original mathematical models and regulations (which is important for verification of correctness). We have also been able to use the support for Async-workflows producing code that is simple and clear and easy to understand but still runs in parallel when required.

Bayard Rock: we work hard every day in the pursuit of new approaches towards anti-money-laundering. Before adopting F# there were often months of turnaround time between development of an idea and actually testing it on real data in our production environment. F#’s succinctness and composability allows us to rapidly iterate on ideas while the type system acts as a safety net. On top of this, it has the advantage of being a first class member of the .NET ecosystem and so integrates seamlessly with our Microsoft stack systems. This means that instead of months we can often see our ideas come to life in just days.

The benefits of functional programming in F# have given us a great advantage over our slow moving competitors. After three years of using F# our products have consistently gotten significantly better each year without sacrificing stability. Our clients often are amazed by how we can quickly adapt to unique challenges and how we can find the bad guys hiding in their data much more effectively than anyone else. Little do they know that it’s largely thanks to our secret weapon, F#.

GameSys: F# is becoming an increasingly important part of our server side infrastructure that supports our mobile and web-based social games with millions of active users. F# first came to prominence in our technology stack in the implementation of the rules engine for our social slots games which by now serve over 700,000 unique players and 150,000,000 requests per day at peaks of several thousand requests per second. The F# solution offers us an order of magnitude increase in productivity and allows one developer to perform the work that are performed by a team of dedicated developers on an existing Java-based solution, and is critical in supporting our agile approach and bi-weekly release cycles.

More here

What are the added benefits of F# for a C# team?

F# is not cluttered up with coding “noise” such as curly brackets, semicolons and so on. You almost never have to specify the type of an object, thanks to a powerful type inference system. And it generally takes less lines of code to solve the same problem.

F# has a very powerful type system which prevents many common errors such as null reference exceptions. And in addition, you can often encode business logic using the type system itself, so that it is actually impossible to write incorrect code, because it is caught at compile time as a type error.

Although F# is a functional language at heart, it does support other styles which are not 100% pure, which makes it much easier to interact with the non-pure world of web sites, databases, other applications, and so on. In particular, F# is designed as a hybrid functional/OO language, so it can do almost everything that C# can do as well. Of course, F# integrates seamlessly with the .NET ecosystem, which gives you access to all the third party .NET libraries and tools. Finally, it is part of Visual Studio, which means you get a good editor with IntelliSense support, a debugger, and many plug-ins for unit tests, source control, and other development tasks.

The conciseness of the type system in F# is particularly useful when doing domain driven design (DDD). In DDD, for each real world entity and value object, you ideally want to have a corresponding type. This can mean creating hundreds of “little” types, which can be tedious in C#

Type inference and low overhead type definitions. One of the major reasons for F#’s conciseness and readability is its type system. F# makes it very easy to create new types as you need them. They don’t cause visual clutter either in their definition or in use, and the type inference system means that you can use them freely without getting distracted by complex type syntax.

Reference

What are the things that F# can do that are impossible or hard to do in C#?

In C#, there is a disincentive for creating new types – the lack of type inference means you need to explicitly specify types in most places, resulting in brittleness and more visual clutter. As a result, there is always a temptation to create monolithic classes rather than modularizing them.

In F# there is no penalty for making new types, so it is quite common to have hundreds if not thousands of them. Every time you need to define a structure, you can create a special type, rather than reusing (and overloading) existing types such as strings and lists.

This means that your programs will be more type-safe, more self documenting, and more maintainable (because when the types change you will immediately get compile-time errors rather than runtime errors).

F# was built with features so developers could easily reason with their code. Here’s a non-exhaustive list of said features:

  1. Values are not allowed to change their type. (And this even includes implicit casts from int to float, say).
  2. Records with the same internal data ARE equal by default.
  3. Comparing values of different types IS a compile-time error.
  4. Values MUST be initialized to a valid state. Not doing so is a compile-time error.
  5. Once created, values ARE immutable by default.
  6. Nulls are NOT allowed, in general.

In equal circumstances, is F# faster than C#?

That depends on the context. Natural F# code (e.g. functional/immutable) is slower than natural (imperative/mutable object-oriented) C# code. However, this kind of F# is much shorter than usual C# code. Obviously, there is a trade-off.

On the other hand, you can, in most cases, achieve performance of F# code equal to performance of C# code. This will usually require coding in imperative or mutable object-oriented style, profile and remove bottlenecks. You use the same tools that you would otherwise use in C#: e.g. .Net reflector and a profiler.

In any given situation, it’s always important to remember that profiling the code is crucial. We cannot make assumptions based on sentiment; we need to take decisions based on data. At the end of the day F# is compiled down the same IL and will use similar constructs.

F# and C# both emit IL (intermediate language) which is what’s run on the CLR. This is why it’s possible to have C# calling F# and F# calling C#. That brings me to the following point which is, they can have pretty much the same performance. For certain tasks, such as concurrency and parallelism, F# performs better because of its  functional-first nature. If really required, it’d be possible to write imperative code in F# that would boost the performance of the implementation.

It does impact performance, but the order of magnitude is unlikely to be meaningful. It’s also worth noting that strictly immutable values that don’t change will have no performance impact.

“We made many improvements to F# and its tools,” Microsoft said in its release notes. “Performance and cleaning up existing experiences with .NET SDK-style projects has been the focus for this release. As always, we also received significant contributions from the wonderful F# community.”

Can the development team build the same kind of applications and tools with F#?

Yes. Being a .NET language, F# can interop without any problem with any library that was written in either VB.NET or C#. Another thing to take into account is that it’s possible to implement the data structures in F# and have a C# developer interact with those structures in their C# implementation.

Could you compare F# community resources vs. that of C#. Which one is growing at a faster pace?

As for this, because C# is more used in the industry, samples and documentation tend to be found in C#. I’m working with the F# community (outside of work) to add more F# samples and documentation out there,but that takes time. A thing to remember is that because they are .NET languages, if I find a fix in C#, I can surely apply it in F#.

 

Kevin

3 Tips & tricks for Kickass Developers in 2019

0

Hi,

For those looking for new ways to kick off 2019 with a bang with your .NET skills, keep on reading 🙂

1. Leverage more LINQ in your C# code

Lately, functional programming has been a really hot and trending topic. C# is becoming more of a functional programming language to stay on par with the industry trends and one of the feature that it provides to developers since .NET 3.5 (2007). It’s been then for over a decade and truly makes your code more readable.

With LINQ, you can express directly your intent when iterating through your collection instead of using a looping construct. When looking at a Where statement, immediately developers will understand that your statement is meant to filter data as opposed to writing the equivalent code in a loop, you need to look inside the loop to understand what’s going on.

2. Document your code as you type it

Something I’ve witness so much in 2018 was the lack of documentation in code. And let me tell you, 3 to 6 months after writing your own code, if you don’t maintain it for a while and it is poorly documented or even, not documented at all because you think you will remember, that’s wrong.

Writing documentation for your code shows deep understanding of your product and respect for next people in charge of maintaining the code and adding more features to it. When you need to do a knowledge transfer, it’ll be a breeze because the documentation is already there to back everything you have built from the ground up. More to the fact, if only you touch that code, you will be thankful for helpful documentation whenever a bug hits the system and you’re responsible to go through those lines and figure out where that nasty logical bug is hiding and finding a way to get rid of it.

3. Write your methods side-effects free when possible

Your code should not have the need to create side-effect. From a certain point of view, your code should strive to always generate the same output with the same input. What does that mean? It means that let’s say you create a method to increment a counter every time you click on a button in a user interface, you have in fact a mutable state that’s based on user input. So from the first time I click on button to the 100th time I click on it, I shall never have the same output since the state keeps being updated.

I’m not saying to never write mutable code. That’s not what I’m trying to share as a tip. Mutability is unavoidable, but it can be contained and isolated. Most of your code can be pure, as in stateless. You can make sure to have readonly fields and properties. You can also provide APIs that give you solely readonly collections that you can’t update. Instead of updating a meaningless field in your class that’s used only in a single method of said class, simply make it a local variable of a method and update it there. From the client’s perspective, if your method has within itself mutability, but the same input generates the same output, you’re golden 🙂

 

Kevin out.

Tech Questions #4: Should I use ToArray/ToList in LINQ queries?

0

Hi,

Quick word on LINQ

So today’s post is going to be focused around LINQ which is an acronym for Language INtegrated Query. For those who are unaware and would be interested in learning more about LINQ, I invite you to go on this page. In a few words, LINQ is the name for a set of technologies based on the integration of query capabilities directly into the C# language.

In the past, I have had some questions and I’m leveraging my blog to share my experience on the topic and hope to make you better developers by using the experience that I’m sharing. So, with no further ado, let’s dive into the tech question of the day!

#4: Should I use ToArray() / ToList() in LINQ queries?

So, when we use the LINQ, every extension method returns an IEnumerable and they can be chained together to let you, the developer, do whatever it is that you have to do, like say finding the name of author in the database which sold over 100 books in the year 2018 for instance. The power of LINQ can found in its deferred expressions. What’s a deferred expression? Good question! When you’re writing your LINQ expression such as

Your expression doesn’t go through the entire collection until told otherwise. What happens behind the scene is that until forced to moved the enumerator to the next index, LINQ is going to wait. What good does that bring you might ask? It also means that you won’t allocate useful memory until there’s no choice but to allocate it and do what it is that you have to do with it.

Back to Should I use ToArray/ToList in LINQ queries. The best answer that I can give you is that it depends on the context, but I frown upon the usage when deemed unnecessary. Why do I frown upon that? Because it allocates memory for your entire collection that will be generated by your LINQ expression. Using those methods have a performance hit on your entire expression of a size of O(n). Depending on the context, if I use one of those endpoints in the LINQ API, I’d use ToArray over ToList for purposes such as iterating through the resulting collection. ToArray has a bit less of a performance impact on your code. When your collection is too big, it must grow behind the scene an array of a size big enough to contain all your data and then returns said array. In the case of ToList, again, we’re growing an array, but once the array is set, we’re initializing a list object with the resulting array which means that you’re allocating X.Y Gb memory twice from your query.

As I mentioned earlier, it all depends on your context. Maybe after having your resulting collection, you’ll be in the need of a list for a specific endeavor. When I’m using LINQ, most of the time, I’m making sure that my API endpoints return IEnumerable<T> to let the users of my code do whatever they want with them. If you need to create a dictionary or a set from my method, the returning value lets you do that since IEnumerable is the common interface that collections point to (usually).

Thank you for your time,

Kevin 🙂

Hidden .NET Gems – ReactiveUI

0

Hi,

Today, I’m going to talk about an open source gem in .NET for developing WPF applications for people who are interested in reactive and functional programming. To understand the work behind ReactiveUI, one mst understand Rx, or rather Reactive Extensions for .NET. The goal of the syntax of ReactiveUI for read-write properties is to notify Observers that a property has changed. Otherwise we would not be able to know when it was changed as it’s mentionned on their website. This is super cool because it allows you to abstract mutable state away from your user interfaces and express the idea around a feature in one readable place whilst improving application testability.

To have a better understanding why you should take a look at reactive programming, take a look at the following Youtube videos:

Soon, I’ll be building a Xamarin application with ReactiveUI. I’ll also weight the pros and cons of implementing the business logic with Akka.NET and F#. Keep on reading and you’ll see it briefly.

 

Kevin

 

 

Hidden .NET Gems – Aliased generics

0

Hi,

I’ve started a job as C# software engineer consultant on the 15th of this month. It’s given me the opportunity to go back over my XAML with WPF and Silverlight and doing some refactoring with C#. Doing so, I’ve been pushing my C# foo & re-discovered some things that I hadn’t use in a while and discovered new things along the way. I thought a series such as this one would force me continue to discover new things in .NET, may it be about
C#, a library/framework, Visual Studio or whatever.  Today, well tonight on my end because it’s almost 11 PM, I want to talk about the following topic: aliased generics

using SimplerGenericNaming = System.Collections.Generic.HashSet<System.Collections.Generic.KeyValuePair<Namespace.SomeLongClassName, string>>;

It allows you to use SimplerGenericNaming, instead of HashSet<KeyValuePair<SomeLongClassName, string>> every time. It can be used  when you would like to use the same big long complex generic type in a lot of places. It’ll make you type that much less and that, I really like 😀

var myShortGeneric = new SimplerGenericNaming();

Of course, it may be a little long to have to define the exact type with the namespace at the top of the file. But it does make the code simpler to read in the end in the source file. Although, there may be a way to get around this which can be cool !

using Col = System.Collections.Generic;
using SimplerGenericNaming = Col.HashSet<Col.KeyValuePair<Namespace.SomeLongClassName, string>>;

This way, we get simpler naming, and aliased generics get a bit less of a hassle to use ! Do keep in mind that C# only supports closed aliases, meaning you “cannot name an unbound generic typedeclaration without supplying type arguments.” (section 9.4.1 of the C# Language spec).

Kevin

Posted in C#

FastOrder: real-time pizza order placement – Part 0

0

Hi,

I’m picking web and mobile development lately as they are super trendy at the moment. But it’s more than that. I’m a firm believer that in this profession, software development, we can’t keep still. We ought to ourselves to move way outside our comfort bubbles and try new things even if it’s a small proof of concept. We usually get to pick up more more insight on our own to approach problems and trying new techs might force us to follow the mindset of it. Doing so, we can see things in a whole new light. More than simply seeing things in a new light, we are in a profession where can do so much with just a computer, it’d be sad to keep doing the exact same thing over and over again. This brings us then to FastOrder.

C# 7.0 came out, ASP.NET Core looks hot for server development and I find that React looks a great tool for front-end development because I’m fond of functional programming. I was also thinking of mobile development and last year at a conference called “DevTeach” I was introduced to a programming language called NativeScript. This language enables programmers to do cross-platform development for both Android & iOS. Being that NativeScript uses Angular, I’ll get to work on both React and Angular and figure out what approach I prefer for front-end development.
FastOrder is an idea that came up to me. I didn’t want the usual slideshow web app or e-commerce thing that can usually find for introductory project for web development. I was gazing at my pizza one day and the idea popped in my head. What I’d like would be to showcase my own approach to design a pizza shop where clients would be notify right when cooking procedures are being completed and know where the delivery guy/girl is with their order. Being real-time, the information would always be present for the client as they request it.  This initial post is me introducing the idea on my blog. The next step will be to do the initial setup for the server and the mobile app that managers, clients and delivery people will use. I plan to use my DevSharper functional library so definitely be on the look up for progress on that project as well.

A fun thing I thought that could be done, even though it may not be realistic,  was to deploy a system where users could bet on long it would actually for the delivery. If the delivery people couldn’t manage to beat that time, that amount off the usual time needed to delivered the pizza would be deduced from the bill. Otherwise, the client would have to pay that extra 5% for instance. More than this, we can use data science on the data collected from the platform to see which pizza is the most popular or verify whenever people order pizza the most.

We’ll see what we can get out of FastOrder,

Kevin

Tech questions 1-3: Linq

0

Hey guys,

This is a new series I will try to maintain to the best of my capabilities. I’m this awesome blogger who happens to be also a Microsoft MVP called Iris Classon. After her first year of programming, she started to ask and get answers for what she’d call “stupid question”. Why would she consider them as stupid ? Well actually they’re not. They’re basically good questions that any developer, being a junior or an architect ( well less likely if you’re an architect), to ask and get answers too. Her series is really good and it got me thinking that I should start my own too. This begs the question to the why I would feel the need to do something like this for my blog ? We all want to get better in our field of expertise. Software engineering being extremely broad, it can get a “bit” confusing sometimes. My tech questions will lead me, I hope, to better myself and have not only a better understanding of the .NET framework, but any kind of technology that interest me right now or will interest me in a near/far future. I hope those questions will be helpful for the readers and followers of the blog.

To start the series, I will start with questions I have had in the past. Why ? It’s going to help me to stay on track and deliver answers for the tech questions on a regular basis. So let’s get cracking with LINQ. Why should we use LINQ in our C# solutions ? That’s quite a question. I cannot simply answer by the “well because it’s better that way.” and be done with it.

1. What is LINQ ?

The acronym LINQ stands for Language INtegrated Query. It allows .NET developers to query IEnumerable implementation to retrieve data as you would do in a SQL database. For instance, a list of int, which is a data structure implementing the IList interface which extends both ICollection and IEnumerable interface,  can be queried that list to see what’s the average of the values it contains. To be able to use LINQ, you’re going to add System.Linq directive in your source file (or have Resharper tell you exactly what references are missing from your code).

using System;
using System.Linq;
//Our very first linq call ! 🙂
public class LinqSamples
{
    public int AverageInts(List<int> list)
    {
        return list == null || list.Count == 0 ? 0 : list.Average();
    }
}

2. What are some benefits of LINQ?

Well there are many. You can bet that when you go LINQ, you won’t go back.  One of the first benefits of LINQ in your code is that makes it more declarative. This means that it can almost be read as plain English (as far as code goes).

using System;
using System.Linq;
public class LinqSamples
{
    //Worst name for a method I agree haha
    public List<string> OrderStringStartingByA_AndByLength(List<string> list)
    {
         return list.Where(str => str != null)
                    .Where(str => str.Contains("a"))
                    .OrderBy(strElement => strElement.Length);
    }
}

So basically, the method goes through the List to first manipulate only not null strings. Then it filters out of the list strings not starting by the letter ‘a’ and finally, orders the list by string length, from the smallest to the biggest string.

It can also reduce the complexity and the length code written using either a for or a       foreach loop. In order to write the equivalent of what I’ve just wrote using only foreach loops,  it would end up being something like :

using System;
using System.Linq;
public class LinqSamples
{
    //Worst name for a method I agree haha
    public List<string> OrderByA_AndLength(List<string> list)
    {
        var orderedList = new Lis<string>();
        foreach(var str in list)
        {
           if(str == null) break;
           if(!str.Contains("a")) break;
           orderedList.Add(str);
        }
        orderedList.Sort();
        return orderedList;
    }
    // See here : 9 lines vs 3 lines in the other example!
}

See here, we’ve been only using the type of LINQ called Linq to Object. The architecture was well thought; doing so, it lets pick up quite easily other types of LINQ such as LINQ to XML or LINQ to SQL.

3. What is a method group ?

In a few words, a method group is a set of overload methods resulting from a member lookup. This comes directly from the C# 3.0 Section 7.1. EventHandler handler = MyMethod; then “MyMethod” refers to a method group. There could be multiple methods with the same name, but different signatures. The method group conversion creates a delegate calling the appropriate actual method. In short, a method group is the name of a set method. There might just be one. Using proper conversions, the compiler will

A method group is the name for a set of methods (that might be just one).
The ToString function has many overloads – the method group would be the group consisting of all the different overloads for that function. It is a compiler term for “I know what the method name is, but I don’t know the signature”; it has no existence at runtime, where it is converted in the correct overload. Also, if you are using LINQ, you can apparently do something like myList.Select(methodGroup) so you can replace this code:

A method group is the name for a set of methods (that might be just one) – i.e. in theory the ToStringmethod may have multiple overloads (plus any extension methods): ToString(), ToString(string format), etc – hence ToString by itself is a “method group”. It can usually convert a method group to a (typed) delegate by using overload resolution – but not to a string etc; it doesn’t make sense. Once you add parentheses, again; overload resolution kicks in and you have unambiguously identified a method call.

Hope you have enjoy this!
Kevin

A better tomorrow for source code with Roslyn

0

Hi guys,

I’ve spent quite some time in the past using the Roslyn API, in an internship and during the Google Summer of Code 2015. Thought I’d be a great idea to present it here.

The .NET Compiler Platform, known by the name of Roslyn, was made available to the public as an extension to Visual Studio in 2010. During the Build 2014, it was made an open-source project by Microsoft. In short, Roslyn provides a set of open source compiler and code analysis API for .NET languages but only Visual C# and Visual Basic are supported at the moment.

Before, when programmers were writing some code in order to solve any kind of issue,they hoped for the code to build and then run some tests on it and finally, build it on TFS and hope it works. Compilers were seen as some kind of magical tool that would check up the code worked or not. In the past, this system was working but as we progressed and get more complicated software, we, as programmers, we need great tools such as refactorings to increase our productivity.

This is where the open source project gets in play. The .NET Compiler Platform enables users to get more information concerning their source code. Instead of simply writing code and hoping for the best, it there are different APIs that can now be use for different tasks such as code analysis. In short, source code analysis is the act of automatically testing source code in the hope of finding bugs within the source code so that it can be fixed. Using a tool like code analysis can lead to many favorable circumstances like code transformation.

The compiler platform was built on top on the C# and Visual Basic compilers. Roslyn can be seen like a compiler as a service. The term “compiler as a service” or CaaS should not be looked like other services like Platform as a service (PaaS) ou Infrastructure as a service (IaaS). Roslyn was created in order to reengineer the compiler of C# and VB.NET. It exposes different phases of the development phase such like the compiling time.

The service given by the CaaS empowers programmers like never before. As it was mentioned earlier, the compiled code is now exposed and can be manipulated by users. Basically, this black box (.net compiler) is now broken apart in many pieces, that when, they all are put together, it creates what is called the syntax tree. In brief, the syntax tree is a representation of the code written in a source file. The syntax tree is code agnostic; it will not have any issues representing the code from a .cs or .vb source file.

This syntax tree uses three different components; SyntaxNode, SyntaxTrivia and SyntaxToken. The SyntaxNode are the core members of the tree, tokens and trivia directly depend on them to exist. Nodes can represent an “infinite” number of syntaxic which can go from a class declaration to initializing an object. As for tokens and trivia; tokens represent small fragments in code, such as identifiers (ex: variable’s name) or keywords (ex: int) and trivia represent all that is remaining in the file such as whitespace or comments.

While they give a lot of information concerning the source code, they don’t give quite enough. This is where symbols come in play. They provide semantic information that the compiler knows about the source code. The symbols contain the information the compiler knows concerning the elements within the source file. Inside symbols, it is possible to find information such as in which assembly a type has been declared or various information concerning a class or namespace. With this kind of information, it’s now possible to validate the type of node during the code analysis. Symbols are separated in two distinct types (interfaces) : ISymbol and ITypeSymbol. ISymbol will help users retrieve the information.

Keeping this in mind, it is now possible to move over to code analyzers and code fix providers. Roslyn analyzers enables developers to enforce certain rules within their code base such as using only “var” as local variable type. A Roslyn analyzer must inherits from the base class DiagnosticAnalyzer which expose a set of diagnostics the analyzer will be responsible for, using the property called “SupportedDiagnostics”. Another important fact concerning diagnostic analyzers is that the analyzers are initialize via the Initialize method inside DiagnosticAnalyzer sub-class. Using the parameter of type “AnalysisContext”, the analyzer registers on the type of node given. Look at the example below. It uses the static class SyntaxKind. This class contains all types and tokens. This class is extremely helpful to find out if a token is a comma or to specify that you’re looking for an object creation expression for your analyzer.


public override void Initialize(AnalysisContext context)

{

context.RegisterSyntaxNodeAction(

(nodeContext) =&gt;

{

Diagnostic diagnostic;

if (TryGetRedundantNullableDiagnostic(nodeContext, out

diagnostic))

{

nodeContext.ReportDiagnostic(diagnostic);

}

},

SyntaxKind.ObjectCreationExpression //When users creates object

);

}

A diagnostic analyzer is only used to find out if the rule was met. In a situation where the peculiar rule, let’s say that the call to the base constructor is redundant, the diagnostic analyzer will only look at object creation expressions and analyze them with the given algorithm. A code fix provider will fix the source code that needs fixing. The most important element in the code fix provider is the method “RegisterCodeFixesAsync”. The information that developers should keep in mind is that information concerning source code is immutable, it cannot be changed.
Using the Document property of the CodeFixContext class, it will be possible to access the syntax root of the source code by calling the method GetSyntaxRootAsync(CancellationToken). The remaining work for the developer will now be to retrieve the SyntaxNode object that created a diagnostic. Finally, the developer needs to create a new root tree where the node has either been removed or replaced by making sure it respects the diagnostic rule.

Well, that’s about it readers. This should be a great introduction for those wanting to dive into the code analysis world.

Kevin out.

GSOC 2015 : From NRefactory 6 to RefactoringEssentials

0

Hey guys,

In spirit of my withdraw from the Google Summer of Code program this summer, I thought I’d do a piece of the project I successfully completed last summer. So what brought me to the program last year ? I spent a few weeks on working on a new thing in .NET called Roslyn. For my internship, I had to develop design semantic rules that my senior programmer was giving me. The first one I had to do was detect when developers were using “synchronization primitives” such Mutex, Monitor or Semaphore. Internally, they had developed something else to help better avoid dead/live locks. Acting this way, they could refactor previous projects and make sure to use their internal structures.

That one took me a while because there weren’t any useful (in my opinion) links that I could find on the subject (Winter 2015). The one I am most fond of was one where my senior found out that they were many times developers were making syntactically and orthographic errors. My job was to develop an algorithm which could pinpoint those mistakes in either variables/members/parameter/method names or even in comments. Part of my algorithm to match the errors was to used a dictionary having all the possible errors for a word as values and the correct word as the key. Doing so, I had part of the solution to develop the refactoring in case my code analyzer picked up anything.

So, back to the GSoC 2015 program. I saw the Mono Project project, NRefactory. The NRefactory library defined code issues and code actions which are basically code analyzer and code fix providers in Roslyn. The library was implemented using FxCop. But there were more traction at the time towards Roslyn. The idea behind the project was to port NRefactory 5 to version 6 using the Roslyn API. Code issues were define and the task was to reimplement them in code analyzers and define a proper code fix provider. Here’s below a non-exhaustive list of what I’ve implemented over the course the summer.

  • Rewrite if return to a simple return
  • Remove redundant code : invoking ToCharArray on a string
  • Remove redundant code : empty finally blocks
  • Remove redundant code : useless parameters in a method declaration
  • Making a member static once I’ve seen that value is never changed

So here’s a link to my GitHub repo.

Kevin out.

 

 

Augmented Tactics: A role playing game prototype

0

Hi,

Today, I’ll be talking about a special project I have not only designed from A to Z but also implemented. Well, it’s not as  big as this sentence let’s it sound. I worked on developing a prototype of a mobile game in augmented reality. Being a huge fan of tactical RPGs, I found it natural to try to develop a tactical RPG prototype. Augmented Tactics tries to replicate the same experience players had when playing Final Fantasy Tactics. After working on this for about 2 months, and I will do it again this fall, I feel compel to talk about the work I did so that others might found inspiration for their project. When I’ll complete the next phase of the prototype, this time called “SmartTactics”, I will then talk about its progress.

What did I want to achieve ?

Being a huge fan of TRPGs like I’ve mentioned earlier, what I wanted to achieve was to re-create a typical battle system. Such a system would include a certain number of characters of different class ( Magician, Swordsman, Lancer, etc) in both parties. Those classes would have the special abilities such as attacking with a weapon (sword, axe or whatever) or spells and also,each of those classes would have a tactical advantage to one or more.

In many games, players must move their character in a squared field where depending of the character’s stats and class, he/she can move from 1 to a maximum squares (let’s say 7) during the movement phase. I wanted also to give different options to the player during the attack phase. With that in mind,  attacking an enemy from the side would give a bonus when attacking, which would be added to the attack bonus if that character had any special role advantage.

Characters coming from a Magician sub-class such as Spellsword, Healer, Dark Mage, etc, would have each have 1 to 2 different spells depending of the sub-class and the strength of those spells. Something that would be a fun mechanic (in my honest opinion) would spells that could interact with the environment. For instance, a spell that could create a line of fire and if a character goes through that line, he/she will suffer burn side-effects until the side-effect goes away or a special item is used to counteract that effect.

Talking about fun mechanics for my prototype,  each class would have certain number of action points which would include actions such as moving, attacking, rotating and so on and so on. The player would need to correctly use those points to form a strategy to defeat the AI. Not only that, working with Unity would provide me the chance to play with augmented reality.  Vuforia is an easy API that seamlessly integrates with the game engine and can project the 3D models using a special anchor in the real world.

Developing under TDD

In an effort to develop this game correctly, I design the tests using NUnit. I don’t have to tell you that TDD enabled me to think of the code I wanted to do in order implement, for instance, a character builder. The character builder creates a character, gives it stats and different kind of information. There’s one example below.


[TestMethod]
 [TestCategory("Character Builder")]
 public void CharacterBuilder_BuildAnNormalHealer_Successful()
 {
var character = new CharacterBuilder().CreateCharacter()
        .WithHealth(100)
        .WithStats(0, 10, 10, 10, 10, 10, 10, 10)
        .WithDirection(2)
        .WithType(8)
        .BuildCharacter();
    Assert.IsNotNull(character);
    Assert.IsInstanceOfType(character, typeof(BaseEnemy));
    Assert.IsInstanceOfType(character, typeof(NormalHealer));
 }

 

Player abstraction

I know that some systems are faulty  because of their design. Such design problems can be categorized as “too coupled”. Having that in mind,  most of the code is based on the following classes : CharacterObservable ,IChoiceAction and ICharacterActionCommand. The first abstract class give the power to manipulate characters at any stages, whether I’m building that healer class or that berseker is about to die and I have to notify the game manager to launch the dying sequence before destroying the game object. For those who find CharacterObservable  name funny, I based the work on the Observer pattern.


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Assets.GameCoreLogic.Managers;
using Assets.Map_AI;
using Assets.Scripts.CharactersUtil;
using UnityEngine;

namespace Assets.GameCoreLogic.Human_Game_Objects
{
public abstract class CharacterObservable : MonoBehaviour,IGameObjectObservable, ICharacter
{
protected ArrayList ObserversList = new ArrayList();
public BaseCharacterStats BaseStats { get; set; }
public Health Health { get; set; }
public List<ICharacter> CurrentEnnemies { get; set; }
public List<ICharacter> TeamMembers { get; set; }
public int MovementPoints { get; set; }
public PlayerDirection Direction { get; set; }
public Cell CurrentCoordinates { get; set; }
public Cell OldCoordinates { get; set; }
public bool IsDead { get; set; }
public int[] Position { get; set; } // [0]=x, [1]=y
public Animator Animator { get; set; }
public CharacterType CharacterType { get; set; }
public Role CharacterRole;
public bool isDamage;
public bool healthWasRaised;

public abstract bool CanDoExtraDamage();
public abstract void CheckIfCharacterDead();

public void Attach(IGameObjectObserver observer)
{
if (observer == null)
throw new ArgumentNullException(nameof(observer));
if (ObserversList.Contains(observer))
throw new InvalidOperationException("Cannot have duplicate observers.");
ObserversList.Add(observer);
}

public void Detach(IGameObjectObserver observer)
{
if(observer == null)
throw new ArgumentNullException();
if(!ObserversList.Contains(observer))
throw new InvalidOperationException("Cannot remove observer when observer not in the list.");
if(ObserversList.Count == 0)
throw new InvalidOperationException("The observer list is empty. Cannot detach.");
ObserversList.Remove(observer);
}

public abstract void Notify();
}
}

IChoiceAction interface let’s me create the sequence of action the AI can do. Through the interface, the AI can build an attack sequence to either attack the closest human player or the one most likely to get a maximum damage due to a certain number of parameters.


using Assets.Scripts.Artificial_Intelligence;
using Assets.Scripts.CharactersUtil;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Assets.Map_AI;

namespace Assets.GameCoreLogic.AI_Core_Logic
{
public interface IChoiceAction
{
#region Movement Decisions
bool ArePlayersWithinRange(List<BaseCharacter> humans);

bool CanMoveAway();

bool ShouldMoveAway();

void MoveAway();

bool IsFacingPlayer(BaseCharacter bs);

KeyValuePair<BaseCharacter, Tile> FindClosestTarget(List<BaseCharacter> humans);

KeyValuePair<BaseCharacter, Tile> FindEasiestTarget(List<BaseCharacter> humans);

void MoveTowardsTarget(BaseCharacter bs);

#endregion

#region Attack and Defend

bool ShouldInvokeDefend();

void InvokeDefend();

void AttackPlayer(BaseCharacter bs);

void AttackPlayer(List<BaseCharacter> bsList);

#endregion

#region Healer Needed
bool IsHealNeeded(BaseEnemy be);

Tile FindHealer(List<BaseEnemy> myParty);

bool IsHealerWithinRange(Tile healerPosition);

void MoveTowardHealer(bool healerIsInRange);

#endregion

void FinishTurn();
}
}

ICharacterActionCommand interface let’s me build the battle system. Through that interface, I can notify the command manager when the player wants to attack an enemy or when I need to move to a certain place.


using Assets.GameCoreLogic.Managers;
using Assets.Scripts.CharactersUtil;
using Assets.Scripts.GameCommands;

namespace Assets.GameCoreLogic.Game_Command_Actions
{
public interface ICharacterActionCommand
{
IReceiver Receiver { get; set; }
bool IsExecuted { get; set; }

void Execute(ICharacter caller);
void Execute(ICharacter caller, ICharacter characterToAttack);
void Execute(ICharacter caller, int raiseDefense);
}
}

Acting this way, my code looks for either interfaces or abstract classes. Being not couple, the code becomes very reusable in my opinion and it made that much easier for testing after designing my tests.

Artificial Intelligence

Map Intelligence

After designing the map as a List of List of tiles,  I made it simple to highlight the tiles in the game to show the entire range of movement of a given character during the move phase, if the player desires to move the character, it’s up to him. In order to know what to highlight, I look at the move points available for the character, and I try to create paths that are still “opened” for the A* pathfinder algorithm. That algorithm enables to find the shortest path between point A and point B. That an useful algorithm for the character intelligence.

Character Intelligence & Move Selector

All characters all have the same the same intelligence. Being that I only had 2 months to build a working prototype, I couldn’t put too much time working in a field in which I wasn’t familiar (AI). Basically, characters can decide to

  • Move towards the closest enemy and attack it (ClosestTargetCommandSequence)
  • Go towards the enemy which will suffer the greatest damage (AttackMostDamageableTargetCommandSequence)
  • Upgrade temporally the defense stats for the course of a turn (DefensiveCommandSequence)
  • Efficient Attack which would be able to plan 2-3 turns ahead to see which would mostly be always attacking most damageable targets and staying clear of small parties that could kill you. (That was planned but neither designed or implemented)
  • Move towards the healer when health is low or heal member in party with the lowest health.
  • Move away from danger which could be something like this character has a tactical advantage on self or if I attack this character, I’m putting myself in danger because I’ll be close to a party of three and health is below X %.

The move selector enables the AI to select which command sequence to perform at each turn. Depending of the situation, each of the command sequences are created and weighted. For instance, moving to the fullest of the available move points doesn’t give a big weight. But, having a low health (~30 % for example) gives a much bigger weight. The sequence with the highest weight is perform through the use of a List<Action>. This is custom AI. I wasn’t really using AI algorithms except the A* implementation that I found online.

What I’m planning for phase 2 -> SmartTactics

For phase 2, I’m thinking of using many AI algorithms to help build the hard mode of the prototype. Using supervised and unsurpervised learning algorithms, I will be able to create a better AI that I had developed last fall. First, I’ll train the AI to adjust itself against players with high offensive stats and low defensive stats. Then, I’ll make so to train it using high defensive stats and low offensive stats. I’ll see how the AI reacts when placed in a simulated environment where characters have mixed stats.

To make things more stimulating, I will let the AI get experience and be able to level up its characters. Doing so, I will have to let it learn how best upgrade the stats using its brain to see which stats give better reaction in the field for a given class after leveling up. I would also like to see if that smarter brain can pick the best equipment from the merchant for any class.

I would use many different parameters to help the smart brain to practice and get better over time, things such as getting bonus points if brain get beat its best time, the experience concerning when a given strategy was used or the remaining health points of a targeted enemy.

I’ve been dabbling with F# during my internship and at my part-time job this summer. With that in mind and wanting to pursue my work in functional programming, I was thinking to port the game in F# in either Urho3D, Xenko, Duality or even Unity game engine. So the Augmented Tactics prototype will be ported from C# to F#. Being that I remain in .NET, the work wouldn’t be herculean. Another thing would be to make fixes and implement small lacking features from the first prototype.

You can look at the work I did during those 2 months here :https://github.com/Kavignon/Augmented_Tactics

 

Interesting project : Render stereoscopic 3D images using Kinect 2.0

0

Hi guys,

Last summer, I got into an interesting course entitled “Emerging topics in information technologies”. During the first part of the course, we focused more on 3D computer vision techniques and how to manipulate 3D images.Issues such as depth-image-based rendering were obscure and captivating enough to get me motivated throughout the summer semester.

In order to go even deeper in our discussions concerning 3D images, we were given Kinect 2.0 for half the semester to do a small project in WPF. The goal of the project was to produce a 3D image in real-time on the 3D glasses free TV Dimenco screen using the Kinect 2.0. Achieving this goal would let to have an hands-on experience with analyzing 3D images and their rendering using a given technology stack.

So this was the workflow.

  1. Connect on the Kinect
  2. Connect on both the depth and color sensors from the Kinect
  3. Acquire a frame from each of the sensors
  4. Process the information coming from the color frame
  5. Process the information coming from the depth frame
  6. Map the depth of the environment with the color to ensure to render 3D environment properly
  7. Correct physical differences between the two cameras in the Kinect 2.0
  8. Insert an image header on the top left corner of the Dimenco screen
  9. Render mapped result of the cameras on the 4K screen

And voila!

As easy as all this can sound, this was not a trivial student project. Having some experience with C# and .NET made the work a bit easier for me than for my classmates who didn’t have the chance to get some experience with the MSFT stack. Although, it still took me the whole four weeks and 25 hours of development, mostly doing some trials and errors to find the optimal solution that would show the perfect 3D image in real-time on the 4K screen. My last problem by the time I hand in the project was that I thought, personally that the rendering could had been sped up and optimize. All things consider, the project was a success !

You can learn more of my project and use the source code here

Kevin out.

 

Bring more functionalities to types using extension methods

0

Hey guys,

What are extension methods ?

Extension methods are quite simple to understand and they can be quite useful in time of needs. An extension method give you the power to create a new method for any type that you would like. They’re static methods designed to extend the capabilities of a type without having to extend the type and add the method(s) that a programmer would like to use.

Extension methods must be defined in a separate static class as static methods, as it was mentioned earlier. Although they’re static methods inside a static class, those methods can be call using instance method syntax(e.g you can use a local variable/ parameter and have access to that extension method). When creating your static class, you need to keep in mind that not only everything must be static when you’re declaring the class and method but the first parameter specifies the type on which the extension method will act. When defining your method, the first parameter must be preceded by the this operator. In a few words, the this operator refers to the current instance of the class or object if you prefer. It enables you, when using this, to access any member to the current instance of your class.

Why use extension methods ?

Why would you need to define extension methods in your normal day life as a developer? Things can happen and sometimes, the library you’re using could be more restrictive than you would like such as the class you would like to extend for a few more functionalities is sealed. In those times, extension methods can be quite useful in order to achieve quickly what you’d like to do.  So here’s below an example of an extension method. What the sample will show you is an extension method with the sole purpose of reversing the value of an int.

Extension method example

 

using System;
//That easy to create your very own extension methods
public static class Int32Extensions
{
    public static int ReverseValue(this int value)
    {
        return -1 * value;
    }
}

public static Main(string[] args)
{
     var value = 10;
     Console.WriteLine(value.ReverseValue());
     Console.ReadLine(); // Will print -10 🙂
}

 

Before I forget, there’s something I would like you to do when designing your extension methods. Beware, it becomes easy to have only one class for every extension method you will use. Don’t. You should separate concerns and make sure to either you one static class per type or at least, regroup extension methods into one domain and make sure the types being extended in your class are quite similar.

 

Kevin out.

Posted in C#

Polymorphism: Empowering your objects

0

Hi there readers, So, we’re finally getting into the final pilar of object oriented programming, polymorphism. It’s a strange word at first, but we get use to it pretty fast.

What does the word polymorphism mean?

The root of polymorphism is traced back to the greeks. Poly means many and morphism mean forms. Basically, polymorphism gives an object the ability of having multiple forms. The fact that an object can have multiple forms means that while using inheritance of dependency injection (an advance topic which will be mentioned later), we don’t have to care what kind of object we’re calling during runtime. Having multiple forms means that while calling a certain function, in the hierarchy of objects, custom or not, it won’t matter which objects is being called. A real world example of polymorphism

Example

Everyone is a person, but each one as his own waking up routine at a specific time of the day:

  • As a waiter
  • As a lawyer
  • As a student taking classes at nights

Method overriding? Virtual methods? What are those ??

Basically, virtual methods are found in the parent class. Virtual methods are behaviors in parent objects which can be overridden by their children. To make sure a method can be use by the children and be overridden, not only it must have the virtual keyword in its signature, but it should also have the protected keyword to make sure that only children can use it. This is a key concept in oriented object programming.

Easily, it’s possible to see why such a feature can be attractive for programmers. We love code reuse and we hate rewriting the same piece of code. Some readers might wonder why we hate rewriting code, right ? Well, it’s pretty simple in fact. It’s a bad programming behavior, YOU SHOULD NOT DO THAT ! Having to rewrite code will double or even triple or X factor time the amount of time you need to invest into maintaining the software.

Back to virtual methods. Having a basic foundation for most of the component in your system simplifies the work that must be completed. More than just this, when you’re overriding behaviors, it’s because you have a darn god reason to do this. in fact, while you’re testing your code or going over your software a few months after writing it, you’ll understand exactly why you did why you did. We usually do this because we have a good reason why.

public abstract class Human
{
   protected virtual void Greetings(string name)
   {
       Console.WriteLine("Hi, my name is {0}:", name);
   }
}

public class Doctor : Human
{
   public void GreetingPatient(string patientName,string doctorName)
   {
     Console.WriteLine("Hello {0}",patientName);
     Greetins(doctorName);
   }
   protected override void Greetings(string name)
   {
     Console.WriteLine("Hi, I'm doctor {0}. It's nice to meet you.",name);
   }
 }

Inheritance: More than just titles or money

0

Hi there readers,

We have talked about the first principle of object oriented programming in an earlier post. Now, it would be time to talk about the second one, inheritance. In the normal world, we talk about inheritance when one is about to receive some piece of land or a title from a loved one in his/her family. In the programming realm, it is more than this. In OOP, inheritance happens when a class is based on another class . This relation is special because they share the same implementation. Doing so, the class (B), who inherits from the other (A), share the same behavior that A has. But why would programmers act like this? Why not simply copy-paste the code from the class A to the class B? Those are actually good questions you might have had.

I don’t know if you remember from earlier posts, but I had mentioned that having a software which had a lot of code was not the goal you should think of while writing code. Sometimes, there won’t be any other way than having a software which has 10,000.0 lines of code and it is okay. But what we aimed for is having a software that is as maintainable as it can be. When I say maintainable, what I mean is that simply finishing a project won’t mean that it won’t change in one day or one month or five years. A query from a client can make your project change over time,and while you’re going through those changes, you don’t want to change all the code that was written before. Having maintainable code can be achieved through different methods, and by this I don’t mean the methods we usually write in order to complete operations. One of them is code reuse.

Like it was said earlier, class B inherits from class A. Inheritance is a mechanism for code reuse. Not only B gets all the same behavior that A has,  but B has accessed to all the attributes from the class A. Has much as inheritance is a good principle to follow while doing OOP, there is something that we must keep in mind while using inheritance. When a class inherits from another, what we’re trying to achieve is to specialize a concept by adding new behaviors to the class. Basically, we have what we call the superclass which has some states and behaviors that can be common for many situations. Then, we have the subclasses which inherits those traits but add new ones. For example, we could have the superclass Person which has a Weight, Name and Age. Now, we have the classes Student, Manager and Employee.

The Student objects, since inheriting from Person, already have Name,Weight and Age. But a student has more than simply that like a grade point average (GPA) or a student id (ID). Employee is also inheriting from Person but has the properties Salary and  Bonus. Finally, we have Manager which inherits from Employee but only overrides behaviors from Employee.

That’s a benefit from inheritance. Even though we inherits from a superclass, if we like the behaviors from the previous class but there is some things that need to be change, then we can override those behaviors in order to achieve what we truly wish to do. Down below, we’ll see in code exactly what I said we can do with inheritance.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
      static void Main(string[] args)
      {
         Person aPerson = new Person("Bob", 70.45, 23);// creating a person
         aPerson.SayingHello("Sarah");

         Student aStudent = new Student("Bobby", 1023453235, 3.98, 83.67, 22); //creating a student
         aStudent.PrintStudentAverage(); //Printing the student's average

        Employee anEmployee = new Employee("Tom", 5, 25.50, 23); //creating an employee
        anEmployee.SayingHello(aStudent.Name); //The employee says hi to the student
        anEmployee.PrintEmployeeSalary(); // Printing the salary of the employee

        Manager aManager = new Manager("Kevin", 43.45, 23, 4);
        aManager.SayingHello(anEmployee.Name);
        aManager.PrintEmployeeSalary();

        Console.ReadLine();//Press Enter to quit this application
     }
   }

   public class Person
   {
     private double _weight; //we define the fields by starting with the underscore (_)

     public double Weight
     {
        get { return _weight; }
       set { _weight = value; } //We'll let the weight like this because over time, it can change
     }

     private String _name;

     public String Name
     {
        get { return _name; }
        set { _name = value; }
        //Usually, the name of a person does not change, so we'll make it private.
       //This means that no one who can access an object of Person will be able to modify the name
     }

     private int _age;

     public int Age
     {
       get { return _age; }
       set { _age = value; }
     }
     //Constructor
     public Person(String aName,double aWeight, int anAge)
     {
       Name = aName;
       Weight = aWeight;
       Age = anAge;
     }

     public Person() { }

     public void SayingHello(String personName)
     {
        Console.WriteLine("Hi, my name his : {0}. It his a pleasure to make your acquantaince {1} !", Name, personName);
     }
  }

     public class Student : Person
     {
        private int _studentID;

       public int StudentID
       {
          get { return _studentID; }
          set { _studentID = value; }
       }

       private double _gpa;

       public double GPA
       {
          get { return _gpa; }
          set { _gpa = value; }
       }

       private int _numberOfClasses;

       public int NumberClassesForTheSemester
       {
          get { return _numberOfClasses; }
          set { _numberOfClasses = value; }
       }

       private int _numberOfCredits;

       public int NumberOfCredits
       {
         get { return _numberOfCredits; }
         set { _numberOfCredits = value; }
       }

        public Student(String name, int id, double gpa,double weight, int anAge)
        {
           this.Name = name;
           this.StudentID = id;
           this.GPA = gpa;
           this.Weight = weight;
           this.Age = anAge;
        }

        public void PrintStudentAverage()
        {
            Console.WriteLine("The average of {0} is {1}", this.Name, GPA);
        }

        private void ComputeStudentGPA()
        {
           //not how we actually do it, it is more as a behaviour to add to this class
           GPA = NumberClassesForTheSemester / NumberOfCredits;
        }
     }

    public class Employee : Person
    {
      private double _hourlyWage;

      public double Salary
      {
         get { return _hourlyWage; }
         set { _hourlyWage = value; }
      }

       private int _bonus;

       public int EndOfyearBonus
       {
          get { return _bonus; }
          set { _bonus = value; }
       }

       private int _yearInCompany;

       public int YearsInCompany
       {
          get { return _yearInCompany; }
          set { _yearInCompany = value; }
       }

       public Employee(String name, int yearsOfLoyalty,double salary, int age)
       {
          this.Name = name;
          this.YearsInCompany = yearsOfLoyalty;
          this.Salary = salary;
          this.Age = age;
       }

        public Employee() { }

        public virtual void ReceiveBonus(int bonus)
        {
            EndOfyearBonus = YearsInCompany * 2 * bonus;
        }

        public void PrintEmployeeSalary()
        {
           Console.WriteLine("This is the salary : {0} $/h of {1}", this.Salary, this.Name);
        }
     }
     public class Manager : Employee
     {
        public Manager(String name, double salary, int age, int numberOfYears)
        {
           this.Name = name;
           this.Salary = salary;
           this.Age = age;
           this.YearsInCompany = numberOfYears;
        }

        public override void ReceiveBonus(int bonus)
        {
           EndOfyearBonus = 3 * YearsInCompany * bonus;
        }
     }
  }

Kevin

Encapsulation: How to make sure the user don’t mess up the software

0

Hi there readers,

We’ll begin our journey down the road of oriented object programming with the first principle: encapsulation. When we create a software, we have multiple pieces of data which communicate with each other to do exactly what we wish to achieve. While we would love to live in a world were the users of our software will do exactly what we hope they should do, they won’t. THEY WILL NOT. When we create a software, we must the users not as good users who will do what we want but as evil users. This way, while we’re creating a software, we’ll make sure it is bulletproof.

The first way we get to do that is with encapsulation. While some part of the data must be available to the users, or they won’t be able to use the software,  encapsulation creates a wall around the important and sensible data. We protect what is important so that no wrong or unpredictable behavior  This wall enables us to choose exactly what we wish to protect and make private and what we wish to make public for the user.

We are not going ahead of ourselves, we’re going to stay with how to make data public and private. What we really want to do is how we can access and/or modify data.   Before we get into that, we must first get comfortable with the following: fields and properties. At first, they might seem almost alike for the beginner, I myself took a little while before I got used to them, but they’re not. Fields are simply public that a class exposes.  Even though properties do exposes those variables, they give to users the ability to control how the values can be set or how they can be accessed.  But in the end, they are both a way to store and retrieve information when we’re manipulating objects in our software.

Like I said earlier, it can be hard to get used to them and to know which to use in a given situation. Usually, we use properties when one has to enforce the way a value can be retrieve any moment during the run time. We use fields for operations like a validation, for example, does this particular file exists at this moment when I need to use it (bool value).

We got to know about all of this, it would be a great time to see this all in action in an example.  We’ll create our first class with fields, properties and methods. Those are really what define an object. The properties and fields provide different states to the object and the methods give the object the behavior we expect it to have at run time.

We are going to create the class Person, class starts with an upper-cased letter, which will have a few fields such like a height or a weight.  The objects from the class Person will have a few different behaviors, such as saying hello to a fellow comrades.

Before we get into the code sample, I thought it would be a good idea to talk about how we do create objects. We have mentioned them but we barely scratch the surface. We have what the techies in this world call constructors.  They have the same name as the class we’re creating, and just like any other methods, they can, or not, receive parameters to initialize given attributes from the class at run time.


namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Person aPerson = new Person(&amp;amp;quot;Bob&amp;amp;quot;, 70.45, 23);
aPerson.SayingHello(&amp;amp;quot;Sarah&amp;amp;quot;);
Console.ReadLine();
}
}

public class Person
{
private double _weight; //we define the fields by starting with the underscore (_)

public double Weight
{
get { return _weight; }
set { _weight = value; } //We'll let the weight like this because over time, it can change
}

private String _name;

public String Name
{
get { return _name; }
set { _name = value; }
//Usually, the name of a person does not change, so we'll make it private.
//This means that no one who can access an object of Person will be able to modify the name
}

private int _age;

public int Age
{
get { return _age; }
set { _age = value; }
}

public Person(String aName,double aWeight, int anAge)
{
Name = aName;
Weight = aWeight;
Age = anAge;
}

public void SayingHello(String personName)
{
Console.WriteLine(&amp;amp;quot;Hi, my name his : {0}. It his a pleasure to make your acquantaince {1} !&amp;amp;quot;, Name, personName);
}

}
}

Kevin

Console Application: Managing a bank account

0

Hi readers,

We’ve seen quite a few things in the last few days. Now, it’s time to put all the fundamentals to good use. Today, we’ll create a console application in which a user can access the menu of its bank account.  At first, the user will need to set up his password to get inside his account. Then in order to withdraw money, a user will need to make sure he had deposit money earlier before. In a situation in which he tries to withdraws more than he previously had, the bank will print an error message to tell him that the operation is impossible. If he tries to withdraw money that he owns, the console application will print the amount of money that was withdrawn and how much he has left. After each operation, the console application will always ask the user if he wants to quit, if so, he will only have to press the ‘q’ letter.

In this console application, we’ll mostly use methods to reduce the code that has to be in the main method. For the purpose of just looking how something like would work, we’ll start with a bank account with 2000$. This our first real console application, so we won’t go too deep. We won’t manage, for now, what happens if we were to withdraw more than what we have in our bank account, the console application will show a negative balance.


class Program{
  static void Main(){

       String confirmedPassword=null; //The first password of our user
       String userPassword=null; //The password we'll try to confirm with confirmedPassword
       char selectedAnswerFromUser='n'; //Selected answer from user after each operation
       char selectedOperationFromUser='0';
       int numberOfTimesTypingWrongPassword=0; //we'll verify if the user types the wrong password
       confirmedPassword=CreatePassword();
       while(selectedAnswerFromUser != 'q' ||                  numberOfTimesTypingWrongPassword &amp;amp;gt;=3 ||                selectedOperationFromUser != 'q')
             {
                Console.WriteLine(&amp;amp;quot;Please, enter your password&amp;amp;quot;);
                userPassword=Console.ReadLine();
                 if(ConfirmPasswordBankAccount(userPassword,confirmedPassword) == false)
             {
         while(ConfirmPasswordBankAccount(userPassword,confirmedPassword) ==false &amp;amp;amp;&amp;amp;amp; numberOfTimesTtpingWrongPassword &amp;amp;lt;3)
          {
             Console.WriteLine(&amp;amp;quot;Please enter the good password to access your account&amp;amp;quot;);
             userPassword = Console.ReadLine();
             numberOfTimesTypingWrongPassword++;
              AlertUser(numberOfTimesTypingWrongPassword); //won't do anything until we reach the value of 3
           }
          }else{
             selectedAnswerFromUser =         ConfirmOperation();
             if(selectedAnswerFromUser!='q')
             {
                decimal accountBalance=2000;
                decimal withdraw;
                decimal deposit;
                switch(selectedAnswerFromUser)
                {
                  case p:
                      PrintAccountBalance(accountBalance);
                      break;
                  case d:
                        Console.WriteLine(&amp;amp;quot;Please insert money to deposit&amp;amp;quot;);
                        String input = Console.ReadLine();
                        if(Decimal.TryParse(input,out deposit)
                        {
DepositMoney(balance,deposit);
                        }
                        else
                        {
                          deposit=0.0m;
                                   DepositMoney(balance,deposit);
                          Console.WriteLine(&amp;amp;quot;The balance did not change because you did not type numerical values&amp;amp;quot;);
                        }
                        break;
                       case w:
                           Console.WriteLine(&amp;amp;quot;Please inser the amount you wish to withdraw from your account&amp;amp;quot;);
                           String input=Console.ReadLine();
                           if(Decimal.TryParse(input, out withdraw)
                           {
                             WithdrawMoney(balance, withdraw);
                           }
                           else
                           {
                             withdraw=0.0m;
                             WithdrawMoney(balance,withdraw);
                             Console.WriteLine(&amp;amp;quot;The balance did not change because you did not insert a correct amount&amp;amp;quot;);
                            }
                           break;
                   }
                }
              }
            }
          }
        }
     }
   } 

 //Creates the password for the bank account
 static String CreatePassword()
 {
   String aPassword= null; //initialize the string to null, it has to value for the moment
   Console.WriteLine(&amp;amp;quot;Please, insert a password for your bank account&amp;amp;quot;);
   aPassword = Console.ReadLine();
   return aPassword;
 }

 //Will make sure that we enter the good password
 static bool ConfirmPasswordBankAccount(String firstPassword, String secondPassword)
 {
 return secondPassword.Equals(firstPassword); //Verifies if the two password are a match, if yes, return true. Otherwise false
 }

//Alerts a user after 3 type he types the wrong password
 static void AlertUser(int numberOfErrors)
 {
    if(numberOfErrors &amp;amp;gt;=3)
    {
      Console.WriteLine(&amp;amp;quot;There is something wrong with your bank account. You cannot access your bank account today.&amp;amp;quot;);
     }
 }

//Method which will confirm what operation the user wants to achieve
static char ConfirmOperation()
{
   char answer;
   Console.WriteLine(&amp;amp;quot;If you wish to continue, please press c. Otherwise, press q&amp;amp;quot;);
   answer = Console.ReadLine();
   if(answer != 'q' || answer != 'c')
   {
     while(answer != 'q' || answer != 'c')
     {
         Console.WriteLine(&amp;amp;quot;Please press either c or q to pursue with this software&amp;amp;quot;);
         answer= Console.ReadLine();
      }
     }
   else{
        Console.WriteLine(&amp;amp;quot;To print the current balance of the account, press p. To deposit money in the acocunt, press d. To withdraw money from the account, press w. To quit, press q&amp;amp;quot;);
        if(answer!='p' || answer!= 'd' || answer !='w' || answer !='q')
        {
           while(answer != 'p' || answer !='d' || answer!='w' || answer !='q')
           {
              Console.WriteLine(&amp;amp;quot;Please enter either of the following : q, c,p or w&amp;amp;quot;);
              answer=Console.ReadLine();
           }
        }
     }
 return answer;
}

static decimal DepositMoney(decimal balance, decimal moneyToDeposit)
 {
   balance+=moneyToDeposit; // The += operator is equal to say              balance= balance+moneyToDeposit;
   PrintDepositMoney(moneyToDeposit); // Prints what we've deposited

   PrintAccountBalance(balance); //Prints the new balance

   return balance;
 }

 static decimal WithdrawMoney(decimal balance, decimal moneyToWithdraw)
 {
   balance -= moneyToWithdraw; //Substracts money from the account balance

   PrintWithdrawMoney(moneyToWithdraw); //Prints the money we wanted to take from our account

   PrintAccountBalance(balance); //Prints the account new balance
 return balance;
 }

static void PrintAccountBalance(decimal balance)
 {

   Console.WriteLine(&amp;amp;quot;This is the current balance : {0}&amp;amp;quot;,balance); //Prints the accounts current balance

 }

 static void PrintDepositMoney(decimal deposit)
 {

   Console.WriteLine(&amp;amp;quot;You have deposit this in your account : {0}&amp;amp;quot;,deposit); //Prints the money we wished to insert in our account

 }

 static void PrintWithdrawMoney(decimal withdraw)
 {

    Console.WriteLine(&amp;amp;quot;You have withdraw this from your account : {0}&amp;amp;quot;, withdraw); //Prints the money we wished to take from our account

 }

Kevin

Programming basics : Methods

0

Welcome reader,

We’ve gone through a lot of the core fundamentals of programming with C#. We’ve seen how to evaluate conditions in our program flow and different ways to repeat a block of code with the help of loops. We’ve seen different notions that can help us to really understand how a software program works with the basics.

At first, when we create a console application, we dwell in the fact that the software application has X lines of code. Sure, having a lot of code seems fun, we look like we know what we’re doing. As fun as it may look, a lot of code is really hard to maintain. While we may think that as soon we’re doing writing a software that it’s done, we may have to come back in a few days or months to improve its functionality.

But that’s not the topic of this post. What we’ll learn today is to create methods. Using methods can reduce the code we need to have in the main method, which was seen in a previous example. A software program runs from the main method which will do exactly what our program needs to do. Sounds weird huh ? Code can exist outside the main method, but to be used, the code must be called in the main method.

Basically, a method helps us to not have to repeat code, and that’s something we should always try to achieve while we are developing something. Why would we want to do that ? Because if a piece of code has a bunch of errors, if we duplicate it in several places, we’ll have to look for all those pieces and correct what was wrong. That is not a good practice, we should aim to not do that.

Methods can be simple, we could only need something which would take the name of a person as an input and print a welcome message. Like this


static void PrintWelcomeMessage(String personName)

{

    Console.WriteLine(&quot;Welcome in this software application, {0}&quot;, personName);

}

With methods, the naming convention changes. The first letter is upper-case. Moreover, the first word of the method has to be a verb, it shows exactly what the method is trying to achieve. In the previous example, the method is “PrintWelcomeMessage”. It’s easy to understand that the method is printing a welcome message and takes a parameter, a string data type. For now, we’ll won’t focus on the static keyword.

More than just the naming convention, methods, as it was mentioned earlier, can take, what we call, parameters. Sometimes, they don’t. Parameters are values that are placed inside the parenthesis. We have to define the type of the parameter and give a name to the variable, like we always have done before.


static void PrintWelcomeMessage(String personName, int ageOfPerson)

{

    Console.WriteLine(&quot;Welcome in this software application, {0}&quot;, personName);
    if(ageOfPerson&gt;18)
    {
       Console.WriteLine(&quot;You are a minor&quot;);
    }else{
         Console.WriteLine(&quot;You are not a minor&quot;);
    }

}

We haven’t discussed another keyword that has appeared in this post, “void”. Void means that the method won’t return any value after it has reach its end. When we’re using methods, we can decide if we want a method to return something, like the result of a computation. We’ll try out a class(classes will be discussed at length in a later post) which is given by the .NET framework, Math. Thanks to this previous class, we can use different math skills which we could have learned before such as square root, sinus or power.


static double[]  ComputeDifferentValues(int a, double b, double c)

{

     double[] myMathComputedArray =  new double[5];

     for(int i=0;i&lt;5;i++){

        switch(i){

          case 0:

                myMathComputedArray[i]= Math.sqrt(a+b+c);  //This will compute the square root of(a+b+c)

                break;

          case 1:

                myMathComputedArray[i]=Math.pow(a,b); //This will compute a power b

                break;

          case 2:

                myMathComputedArray[i]=Math.Abs(a-b-c);//returns the absolute value of a double floating-point number

                break;

          case 3:

                 myMathComputedArray[i]=Math.Ceiling(b);//returns the smallest int (integer) value that is greater than or equal to the double value that was passed as a parameter

                break;

          case 4 :

                myMathComputedArray[i]=Math.Sin(a); //returns the sine of the given angle

                break;

        }

     return myMathComputedArray;

}

As we could have seen in the last code sample, when we perform any kind of operation and we want to have it later, we have to return what we which to have. In this case, we used a switch to store different values in an array. When we were done, we used the return keyword, which return the variable we which to return we need it.

We have covered basics to some point. There is a lot we need to know before we can get better. But now, with what we know at the moment, a lot can be achieved.  We’ll see how to create console applications in order to resolve issues with all we’ve seen so far in later post such as creating a menu for a user who wishes to withdraw money from his bank account or how to manage an inventory.

Programming basics: what are strings ?

0

Welcome reader,

When we first talk about, it was mentioned that the String data type were to be discussed in a later post. So what exactly are String ? If you remember, we have the char data type, which is used to store a single character inside a char variable. Sometimes, we need to manipulate more than just one character. What previous programmers did to get around this issue was to use Arrays.

Arrays can really simply your work when you have to store a lot of information into your program. You have to look at arrays like entities in which you can store multiple variables of the same data type in a single structure.

In programming,  an array type is use to describe a collection of elements of the same data type like it was said before.  Each element in the array can be access with identifying keys (indices). Usually, when we have a ten values that we want to store, we start counting from value 1 to value 10. In computer science, we start counting starting from 0.  A quick trick to know the last identifying key of your array would be to take its length and reduce it by one. The length of an array is defined as how many elements it can possibly store.

This is how arrays works :

Array in Java Comparision

Something must be kept in mind while we’re using arrays : they are static. STATIC. Usually, when we use variables, the value that is stored in the variable can be modified at any time. When we initialize an array, we either directly store the values it will hold or we give the maximal length of the array. If ever we were simply initialize the array with its maximal length, every value in the array will either be undefined (null) or 0. Null values will be aborted in a later post. We’ll see below how to do such things.

arrays


//this is how to initialize an array of int

//With a maximal length of 10

int[] anIntArray = new int[10];

//the new operator can be omitted if an initializer is provided

int[] arrayOfNumber = {1,3,5,7,9,11,13,15,17,19};

//once we initialize an array, its maximal length can't be CHANGE !

//but the values that are stored can be modified.

//Storing values in an array can be achieved with the help of their indices

anIntArray[0]=1;

anIntArray[1]=2;

//so on and so on until we reach the last indice

//Storing values can be achieved with the help of loop

//Example with a for loop and using the size (maximal length) of the array

for(int i=0; i<anIntArray.size();i++)

{

anIntArray[i]=(i*2)+3;

//Accessing the indices of the array to store a value, one at a time

}

Arrays have a lot of potential when we are developing a software application. In fact, as it was mentioned before, the programmers of the old had to use char array to store what have become String value. We’ll see an example how to create a char array and showing the values of the array for the user.

4

char chABC[26]= {'a','b','c','d','e','f','g','h',i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};

for(int i=0;chABC.size();i++){

Console.Write(chABC[i]);

}

Now, we can directly manipulate the String class ( more on classes and null later).  Doing so, we can directly store input from the end-user like a name  or an address. We can also have information which will never change to present to the end-user such as “warning, you are entering a dangerous zone, please make sure you know what you’re doing or get out of here.”

What’s particular with the string data type is the following : it is immutable. That’s kind of big word for beginners and it is somehow kind of hard to understand at first. Like arrays, strings cannot be modified. But not in the same way as arrays. When a string data type is initialized, it holds a certain value. If along the way, a programmer was to modify the same string variable, it would not cause any problems. But, it would be as if the programmer created a new string. A string only points to certain memory at a time, if the value is modify, it will never be the same string even though it is the same variable.  After a while, what is called extension methods are used to modify data type that are immutable such as string. This is a more advanced topic and will be discussed at length in a later post. We’ll see below an example how of to initialize a string variable


string ourFirstString="This is a string variable. We'll be able to show text with it to end-users of our software application";

Console.WriteLine(ourFirstString);

Kevin

Programming basics : Using loops

0

Welcome reader,

This blog post will cover the use of loops. Loops are used to repeat the same operation(s) at least once. Usually, most programs you can think of will need this kind of functionnality. We can use loops to go through data or let a program start from the start, they can even be use when we need to compute data. In order to execute a loop, a condition must be validate, which was why we had to know how to manage the program flow of a software application.

The first loop we’re going to see is the while loop. In order to know what is happening in a loop, we must first know how to write a loop. When using a while loop, we’re telling the computer the following statement: while the following condition is true, please perform all the stuff that is inside the loop. It is thanks to this condition that the loop will know when it has to stop the looping operation. While this must sound like an easy task to do, this is a well known issue for beginners: infinite loops. For example, like we saw earlier with the comparison operators, if we were to tell while the value of 1,  the while loop will never know when to stop because the value, in the condition, does not change. We’ll see below how to write a while loop with an example :


char selectedAnswerFromUser='Y';

while(selectedAnswerFromUser== 'Y') //We are evaluating the condition the the    equality operator and not the assign operator !

{

Console.WriteLine("Would you like to stop this loop? Please press y for yes or n for no");

selectedAnswerFromUser =Console.ReadLine();

if(selectedAnswerFromUser== 'n')

{

Console.WriteLine("GoodBye ! ");

}

if(selectedAnswerFromUser !='y' || selectedAnswerFromUser != 'n')
{
   Console.WriteLine("Please, you can either press the y or the n letter!");

}

To continue, there is a similar loop to the while loop; it is called the do while loop. The single difference is that the do while will be performed at least once even if the condition is not true. That is the difference between the while and do while loop. We’ll see below an example of the do while loop :


int a=2;

int b=5;

do{ //We start the loop without giving a condition, it will be given below

a++; //The ++ operator tells the computer to increment the value of the a variable by one

Console.WriteLine(a); //This will print the value of a while we are performing the loop

}while(a<b); //in the do while loop, after giving your condition, finish your statement with the ';'

While we are using loops, you can also use variables to count the number of times the loop will perform. We saw the ++ operator earlier, which is meant to increment the value of a variable by one after the line has been read. We have an equal operator in case we want to decrease the value of a variable; the — operator. Here where it gets tricky: depending on which side you put the operators, the have different effects :

  1. variable++ :  The value we use is the value before the incrementation (Postfix incrementation)
  2. ++variable:The value of the variable we’re using is the value after the incrementation (Prefix incrementation)
  3. variable–: The value we use is the value before the variable decreases by 1(Postfix decrementation)
  4. –variable: The value we use is the value after the variable decreases by 1 (Prefix decrementation)

Thanks to those, we’ll now see how to create a condition in a while loop.


int a=5;

while(a<20) { ++a; Console.WriteLine("This the value of the a variable : {0}",a); //This the modulo operator. //It divide the variable a by 2 and looks for remainders //if there are none ->the value will be 0

// else -> We'll see the remainder

if( a%2 == 0 )

{

Console.WriteLine("The value of a will be diminish by 2. This is the value of a now: {0},a);

a=a-2;

}else{

int remainderFromModulo=a%2;

Console.WriteLine("This is the remainder of the modulo : {0}",remainderFromModulo);

}

a=a+3;

}

The last loop we’re going to see in this post is called the for loop. This loop is different from the previous ones that we first saw. This kind of a loop is used when we know exactly the number of times we are going to repeat the block of code until the condition becomes false. The structure is a bit different as we can see below :


for(int i=0;i<5;i++)

{

//do stuff

//when the i variable has the value of 5, then the for loop will stop its iteration

}

In the for loop, we first have to initialize which variable is used to iterate, but it does not have to hold the value of 0. Then, after the semi-colon, we have to give a condition to the loop, which, like we know, use to know how long we have to iterate. And finally, we have to specify if the value of this variable is going to increase or to decrease. Also, we don’t have to increase/decrease by the value of 1. It was used to serve as an example.

Kevin

Programming basics : manage program flow final part

0

Welcome reader,

This will be the final part in the programming basics mini series in how to manage the program flow of your software application. We’re going to see how to manage the flow of your program when we’re using a switch. It is a structure that is mostly use when we have predefined conditions.When this happen, knowing exactly those condition, we’ll have the correct operation to perform if it is met. For example, when someone is doing an exam, we could have three states

  1. He didn’t know what to do, so he had a 0
  2. The knowledge on the topic was not mastered he managed to get 11 out of 25
  3. The student mastered the topic and had 25 out of 25

If conditions like these we found in our application, it would be better to use a switch instead of the if-else if – else structure because we’ll have less to write. We’ll see below the structure of a switch statement :


/*

Everything in this code will not work

it is used to demonstrate how a switch statement is written

*/

switch (aVariable)
{
 case /*ValueOfAVariable*/:
        /*Operation*/;
 break; //tells the computer to stop the operation in this case
 default: //Represent what to do if no condition is met
        /*Operation*/;
}

In a swich statement, a case represents the value of the variable we’re evaluating in the switch. If a case is met, then all the operations for this case will be perform until the machine find the line with a break statement. Moreover, the cases can be link altogether. Like it was said before, until the computer find the statement “break;”, the switch will continue to operate. Below, we’ll see an example of such a switch:

switch(value)
{
   case 1:
   case 2:
   case 3:
   case 4:
     //do some stuff
     break;
  case 5:
  case 6:
    //do other stuff
    break;
  default:
      //do some default stuff
      break;
}

Also, we have the ternary operator, which embeds the way the if-else structure work. We’ll be able to find the structure of the ternary operator below for when you want to assign a value to a variable:

  • dataType variable = ( aCondition) ? (firstValue) : (secondValue) ;

The ternary operator evaluates the given condition. If it is true, firstValue will be assign to variable. If the condition was to be false in our program, then secondValue would be assigned to variable. We’ll try out a code sample to see how it could be useful:


int minValue=15;

int midValue=30;

int maxValue=45;

int aMaxValue=(midValue&gt;maxValue) ? midValue : maxValue;

All of this covers how to manage the program flow in your software application. If for the moment this does not look useful, in the next posts,  it will get more clear as we get deeper into programming as our knowledge of the basics gets better.

Kevin

Programming basics: manage program flow part two

0

Welcome reader,

We’ll pick up where we left with how to manage the program flow of a software application. We saw how to use the if-else if-else structure. To evaluate a condition, we need comparaison operators. Those are use evaluate a boolean expression, which will either result a true or false. Below, you’ll be able to find them.

Operator

Description

==

Equality

!=

Inequality

>

Greater than

<

Less than

>=

Greater or equal

<=

Less or equal

&&

Called Logical AND operator. If both the operands are true, then condition becomes true.

||

Called the logical OR operator. If any the operands is true, then the condition become true.

!

Called the logical NOT operator. It uses the reverse logical state of a an operand. Which means that if an operand was initially at true, the NOT operator makes it false during the evaluation

Thanks to these operators,  there is a lot that can be achieved to evaluation an expression. We’ll use them in samples to try to understand how they work. You can use more than just one to evaluate a given condition in your program flow.

Here, we can see how to evaluate operand(values on each side of the operator) with the greater than and less than.
float bankAccount=2500;
if(bankAccount&gt;3000){
  Console.WriteLine("You have quite a big account");
}else if(bankAccount<1000 && bankAccount>2000){
Console.WriteLine("You have more than 1000 $ and less than 2000 $ in your account");
}else{
    Console.WriteLine("We can't evaluate the value in your account, here's how much you have now : {0} $",bankAccount);
}
This sample will show how to use the NOT opeator.
bool aBoolValue=true;
if(!aBoolValue){
    Console.WriteLine("That's not right ! Is it ?"); //You should see this as false
}
if(aBoolValue){
  Console.WriteLine("That is true! If you have guess that the ouput, good job!");
}
Finally, we’re going to see how to use the equality operator. Beware, because this is a general known issue for beginners; the “=” is use to assign values and the “==” is used to evaluate is two values are equals. Because if you use the “=” operator, it will be a true expression. Why? Because you are assigning a value to a variable; doing so you’re asking the computer, for example, is it true that this variable as the value of 8?
int ageOfPerson=18;
if(ageOfPerson == 18)&lt;/div&gt;
{
   Console.WriteLine(&quot;You are consider as an adult in Canada&quot;);
}
//next example is a bad example. Please be sure not to reproduce code likethis one
if(ageOfPerson=21)
{
    Console.WriteLine("You can vote in any country that you want, or I think ?");
}
We will learn how to use switches and the ternary operator in the last part of how to manage the program flow.
Kevin

Programming basics: manage program flow part one

0

Welcome reader,

Our journey into programming began with the use of variables, how to name and how to store data in them. Programming goes a bit further than this. When you tell your machine to perform a given operation, sometimes, you want to check a state or a condition before your console application performs the work that needs to be done. In your daily life, these events surely happens often such as “if I get 80 or more on this test, I’ll go to X party” or else if “I get a bonus in the end of year, I’m going to go to the Bahamas”. I think you can see a pattern? Basically, we do the same thing in a software application such as if this events does happen, perform this task. In short, we evaluate conditions and, depending of what happened and what we are looking for, we’ll either perform a task or we coule just do nothing.  In programming, we use if-else if-else, the ternary operator or switches(more on them in a later post). We’ll code below an example in which will create a variable storing an integer value. We’ll evaluate conditions and then print the value of the variable if one of these conditions are met.


public static void Main(){

int ageOfClient=30;

//the operators which were use to create the condition will be explained in the next post

//using the if- else if - else structure

if(ageOfClient<18){

Console.WriteLine("The client is a child");

}

else{

Console.WriteLine("Your client is an adult");

}
}

// the ternary operator will be mention when we'll talk about strings.

Kevin

Programming basics: My first console application

0

Welcome reader,

We haven’t create an application since the start of the programming basics. It is sort of a ritual that the first program that a programmer writes will print of the screen the following : “Hello World!”. So, we are actually going to write this as our first console application.

Open your IDE and select Console application. Copy paste the follow code below and hit the run button in your IDE :

public static void Main()
   {
      System.Console.WriteLine(&quot;Hello, World!&quot;);
   }

There, you have the most basic application you can create. You are actually using a method called “WriteLine” and putting information inside the parenthesis. This information that was passed as a parameter (they will be discussed at length during the method post) was then written on your screen.

There you go ! It wasn’t so bad, you can now call yourself a “developer” or a “programmer”. As we’ll progress, you’ll see that programming isn’t so hard as long as you put your time in it and really want to learn. Being passionate about what you’re trying to achieve will help you to master a lot of subjects. Don’t beat yourself down if there was ever a subject that eluded you even if it was the 100th that you tried to do it. Take some time off and come back, make sure you understand the core fundamentals before moving foward !

Kevin

Programming basics: naming convention, indent and white spaces

0

Welcome reader,

We’ll follow where we left off when we’ve talked about variables. When you are behind you screen, there is a lot more going on then just writing lines in the IDE to make you computer do something.  There are a set of rules that you should always stick to make your code clearer. Before, we talked about commenting your code.  Comments are meant to explain the purposes of your program. As an example,  when you’re creating variables, placing comments can help explain what you’re trying to do with those variables. When you’re programming, your instructions will be read by the IDE. Comments will be ignore by the IDE.

There are different ways to comment code. You can place comment on one line. You can also you what I call paragraph commenting. These will come handy when we’ll describe the behavior of methods. You’ll find some commenting examples.


//This is a single line comment

/*

This a paragraph comment. While I'm inside the /**/

all that will be written will be ignored by the IDE

*/

int myIntVariable; //Explain the usefulness of your variable with this comment 

More than just comments, there are other ways to make sure that other programmers who might read your code will appreciate reading it. As you could have seen, when I’m writting my variables, I follow a set of rules which I strongly suggest that you should also follow. This is called the “camelCase” convention. When you’re creating something like a variable or a method (more on methods later), these are the rules that you’ll have to follow.

  • The name of your variable cannot start with a number such as “123MyVariable”
  • The name of the variable should always start with a lower case letter such as “myVariable”
  • When you’re trying to write a composed name, you can either do this : “thisIsTheNameOfTheVariable” or use the underscore to separate either word of the variable’s name like this :  “this_Is_The_Name_Of_The_Variable”
  • Never forget to give a meaningful name to your variable

Finally, even following those set of rules is not quite enough. A good programmer should always indent his code a have a moderate use of white spaces. Well, I’ve just blurred some words that won’t really mean something to you so I’ll explain what I’m trying to tell you. Indenting code is a convention where you place tabs in the blocks of code. As for white spaces, there just meant to make code easier to read. It could all be close together, but that wouldn’t do any good if one must spend some time, trying to decrypt what you’ve wrote.

You’ll find below an example :

/*
The following block of code won't work
It will serve as an example to make sure
that you understand indentation
*/
//indentation
int variable_1=10;
{
   int variable_2=13; //See? There was a tab after the curly brace
}

//white spaces(none)
int variable_3=15;
double variable_4=20.0;
decimal variable_5=0.05m;
short variable_6=56;

//white spaces
/*
Putting white before and after operators(more on them later)
is helpful. Your code does not have to be too cramped
More than just that, separate your variables makes it also easier to read

What I suggest is if you have a set of variables that have a relation
altogether, let them be in a group but after create an empty line and then
resume your coding activity
*/
int variable_7 = 123;

double variable_8 = 234.98;

decimal variable_9 = 0.45m;

First real life project : Managing orders

2

Welcome reader,

This post is a small break from the programming basics serie. I’m going to talk about a real life project I will talk about in this blog. It will be an open source project, which will be accessible from my GitHub account profile.  Before going talking more about the basics, I thought it would be a good idea to talk about what could be achieved when we will put everything that was learned and mastered here in this blog.

You have to create a software application which will store a large number of clients. These clients will make orders and they have to save in a database which must be available a least 95% of the time. Sometimes, special orders takes more time than usual before they come in, when this happens, you can either make it so that when it happens, you automatically send emails to users or u make a query in the database to select users and then send the email. For emails in this situation, you should have templates which would just receive dynamic data so the user of the software has less manipulation to do.

For users, the fun would be to have a self-contained mobile application . What I mean is this:

  • sign in into the app with all our information.
  • Be able to see whats going on in our account.

Moreover, while using a mobile device, such as a phone or a tablet, users would have notification of what going on. Even if emails are sent to the email account, it would even better to select what kind of feedback from the company a customer would like to receive.

In this example, we have a software application which must use a database. The information must be available at least 95 % of the time, so the fail rate has to be really low. The information on the orders must be available online so the users can access it from his mobile device with their app.

In our dev world, there are many ways to complete a task. What I recommend is usually go with what you know so you’ll know what you’re doing while you are doing it. But, in a realm in which things move faster than when oneself blinks his eyes, I think it would be a benefit to try out new technologies in order to gain experience.

For this kind of problem, I have chosen to use:

  1. C# with the object oriented paradigm
  2. Windows Phone (Universal App)
  3. The Android Operating System
  4. Reactive Extension (Rx)
  5. LINQ
  6. The Firebase database

Honestly, I haven’t really experimented the technologies #2, 4 and 6. But I’m not going into this series before we’re ready to do it. So during that time, I’ll get my hands dirty. In the developers community, when someone says getting their hands dirty, it is meant as programming. In order to understand something, we really need to experiment by ourselves, even if the code makes sense to you, I strongly suggest that you at least copy paste it into your IDE and run the application to see how it works on your machine. What would be best is to modify the code, play with it until you truly understand what’s going on.

On the topic of the open source project, I’m going to take you step by step in my solution. This is going a more advanced serie, but bear no fear, if there things that you don’t understand, post comments and I’ll answer you to the best of my knowledge. At first, we will setup our database before going into coding. Then, we’ll design our software application for the company. Then design our mobile app. Afterwards, when the designs are completed, I’ll explain the more complex parts of my implementation, but not all of it. You’ll be able to find the project on my GitHub. Don’t worry, it’ll be commented!

Kevin

Programming basics : variables

0

Welcome reader,

This is the first part of a mini-serie to introduce the basics of programming with C#. Don’t forget to look at my GitHub account. I haven’t decide yet, but surely I will create a project which will resume every topic that I’ve talked about during the Programming basics serie.

So, we’re finally there, will start talking about the programming at last! In this serie, I assume that you’ll have already downloaded your IDE( if you don’t know what’s an IDE, please go read my blog post about IDEs) on your machine. Like I have mentionned before, I’ll be using the Visual Studio Community Edition IDE in this blog.

The introduction to programming start with a fundemental topic : variables. When you are programming, you are telling your machine exactly what you want it to achieve. In order to do so, you have to manipulate data directly on your machine, and when you’ll be running your software application(more of running later), the code that you’ve given will look like this:

0101010 0101 010101 01010

For the untrained eyes, it’s only 0s and 1s. But that is called binary code. This is what your machine use to achieve an operation that you have order it to do.  Even when you are on your user interface of you operating system, you are telling your computer what to achieve for you such as

Opening a folder

Save a file

With the IDEs,  our life is easier, we don’t need to actually manipulate data on the computer with binary code, we use variables. What this means is this: variables points to different parts of the computer memory. In short, variables have a name and a value.They hold different kind of data which can be manipulate and consume by a programmer in order to achieve his goal. Below, you’ll be able to see all the variables that are accessible in most programming languages:

  • byte – 8 bits
  • short – 16 bits
  • int – 32 bits
  • long -64 bits
  • float – single precision 32 bit floating numbers
  • double – double precision 64 bits floating numbers
  • decimal – 16 bits
  • bool – boolean value (true/false)
  • char – holds a character
  • String (it will be discussed in a later post)

From byte to long, these represent integer values such as 0, 100, 200. We have access to different kind of integer values, and when you are programming, you have to choose carefully the exact type you need because each type has its own weight in bit. The more you use, the bigger the software application will be. To understand the difference between the type of integer you can choose, you will find below the range of values each one has:

  • byte [0,255]
  • short [-32768,32767]
  • int [-2147483648,2147483647]
  • long [-9223372036854775808,9223372036854775807]

For example, if you create a software application which will only hold employees ages, using long variables because of their weight. Rapidly, in an application with around a million employees, the software would be heavy to process because you’re using the wrong type of data. In this case, knowing that the human’s span life is around 80 years, using the byte type would be much better. While using variables, you should always use your judgement in order to be memory efficient. Lower, you’ll be able to find an example of a byte variable containing the age of an employee:


byte employeeAge=30;

As you can see, when using a variable, the variable’s name is on the left and the value,which will be assigned, is on the right.  To continue, the float,double and decimal types should be use only when you to consume data which contained the full value of number like 1.25.


int firstValue=1.25; //firstValue will only be 1 because it is an integer
float secondValue=1.25; //secondValue will be 1.25

Console.WriteLine(firstValue);//Will display the value of 1
Console.WriteLine(secondValue); //Will display the value of 1.25

Upward, you can see some code sample showing the use of two variables and C# function(more on functions later) in order to display data to the screen. There’s quite a lot going on in this sample, the part with the double slash is called comments. Comment will be discussed in the next part of this serie. Moreover, as you can see, the names of the variable don’t really represent anything. When using variables, the names you use should always be meaningful. By always doing so, you’ll be able to understand the code you’ve written a while back faster without, or almost, need of comments.

To finish, the char type can only hold a character as a value. A character can be anything such as a alpha or numerical character. The char data is assigned with single quotes. You can see an example below.


byte charVariable='1';

To wrap up, variables have a meaningful name and a value. When using variables in your software application, you should make sure to always use the right type in order to be memory efficient.

Kevin