Why students in college should participate in Google Summer of Code (GSoC)

0

Hi everyone,

Today’s post is targeting students in college. The main idea is to sell you the idea of participating in the Google Summer of Code program that Google host every year since 2005. Oh and by the way, this is just free publicity, the program does not provide any money to me in order to get a post out of me! I love the program, after all, I’m an alumni!

What is Google Summer of Code (GSoC)

For starters, as a student, you must ask yourself, why would I want to participate in something I’m not even aware of, right ? Well indeed, that’s a good question. So, in a few words, it is an open source program hosted by Google during the summer break to provide the chance for students to truly experience software development and get a few bucks of out it.

A vast number of open source organizations are providing one (1) to many project ideas that a student could pick up, develop it during the summer and deliver before the end of the program. When you’re assigned to a project, you’re given a mentor who shall be there for you. By being there for you, I mean they will review the code you will deliver through a pull request and answer your questions whenever you have some. Usually, organizations will have a way to communicate instantly with the core maintainer such as a Slack channel.

Finally, it’s a remote position. When you given a project, you’re going to work in your home country and chances are that your mentor is located in an other one. In this day and age, this kind of situation isn’t problematic. I mean, a lot of companies out there have distributed team members where they aren’t even on the same time zone, but they still make it work!

Why participate? Is this a real job experience?

Again, very good questions coming from students! So, no, this isn’t a real job experience. Albeit it isn’t a real job experience, you gain so much from the program that it doesn’t matter. You get the chance to work with something that will either be completely new and thus, gain experience and new skills at the end of the program or, you can pick up a project in a technology stack that you’re accustomed with and simply add an original project to your portfolio.

Oh, and also, you get a referral to apply at Google, if you manage to complete your summer project successfully! It only works once, but you can use that referral up to 3 different positions within the company!

How does one apply to the program?

You don’t have to be in computer science or in software engineering to participate, although, it helps to have experience in software development. You need to demonstrate that you able to complete the project and also, that you’re passionate by software development.

Each organization can have their own personal pipeline to assess the individual skills of the people applying to their summer projects, and that’s necessary due to the sheer number of students applying every year and that number since to grow exponentially every summer! Some organization could ask to interview you online when the competition is fierce for top notch projects, some could ask for a basic code fix in their code, it all depends on the context! It basically comes to select a project and writing a presentation of yourself to showcase

  • Who you are
  • Why you’re interested by the project
  • Why would you be the perfect individual to take on this project
  • A brief summary of your industry experience related to the project
  • What you expect to be able to do in the summer
  • Your summer timeline for the project
  • How much can I expect to make through the summer?

Closing words

So, I hope this little incentive piqued your interest and pushes you to apply this year! By the way, you do not have to take on the most difficult project, take one that resonates with you because that’s where you’ll be able to shine. Oh and before I forget to mention it, students can expect to get up to 5500$ US during their summer!

Learn more on their website.

P.S If you want to learn more about the project I did while I was a student, I welcome you to go on my blog post on the topic and my Github repository where the code is located.

Kevin

Advertisements

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 🙂

Follow my social media activity

0

Hi,

Quick post, I promise!

I update my blog and you can now follow me on the social networks I’m active on 🙂

I created a YouTube channel to share my experience and knowledge, but mostly, to document my experiences as I’m trying to pick up new skills and maintaining acquired skills.

On my Instagram account, you will be able to find code memes, motivational posts, activities I do on my free time (sometimes not even coding related), events (i.e. hackathons), and so on and forth.

On my GitHub account, you will be able to find all the code I’ve ever written and be aware of my current projects for the year in process.

Sometimes, I use Twitter, but mostly to talk technology subjects. You can come talk to me with no fear; I’m quite nice in fact 🙂

Lastly, my StackOverflow account. This year, I’m top 20% overall of all the users you can find in Stackoverflow (only those with a reputation of 200+ can be ranked). My goal this year isn’t to be like top 5% overall or anything. What I want to do is to answer more questions about the things that I do know and try to provide the better content to the community that has been such great thing in my life. I really love how the community grows and how everyone truly wants to help anyone in need!

That’s it 🙂

Follow me and I promise an interesting year for 2019 😀

Kevin out.

Onto finding my dream job

0

Hi readers,

It has been way too long since my last post and I’m truly sorry.

I’ve been reflecting on my year of 2018 workwise and some part of it wasn’t so fun and I wanted to share my experience. I have had a total three different employments that year and I went on 35-40 interviews total (phone interview, online coding test, in-person meetings) in 6 weeks. It has been crazy and tiring, but everything work out for the best.

When the year started, I was on a consultant contract, but I really didn’t like it. I was brought in to maintain and add features on a Silverlight application. I didn’t feel challenged and that is what I look for in an employment. I helped them sort it out and helped improving the hiring process by designing a document designed to determine the strength of the candidates and the limits of their technical know-how.

I found an interesting job perspective in a Montreal startup where I was hired as a back-end .NET core developer. On my first week, with the two other new hires, we were asked if one of us wanted to learn and ramp up on React.js & Redux to replace the current two front-end consultants. I decided to become a front-end developer instead and started learning. Since I had no knowledge, I was a bit too reliant on them and that was because I felt out of my depth. In retrospective, that wasn’t the best of decisions. Because I had software engineering and web experience, I then became a full-stack developer, creating the endpoints on the database and showing off the data in an appealing fashion for the end-user. In the end, it didn’t work out. Things happen, it’s life and that’s ok.

By then, we’re in the summer of 2018 and I’m looking for a new place for work after my contract was over. And I found my dream job at Robotmaster. We’re in the field of robotics and we provide an interface to seamlessly integrate offline operations such as programming, simulation and code generation. We deliver error free programs for your Robotmaster is the ideal off-line programming solution for all applications that require CAD/CAM for robots including: trimming, 3D machining, deburring, polishing, welding, dispensing, grinding, painting, etc.

At this job, I found people I can interact with and see as an extended family, whenever I’m not knowledgeable on a given topic I’m assigned on; we’re given the time to grow and learn. That’s actually the key point I love about this opportunity. We can grow in anyway we prefer. I’ve been focused on WPF development and algorithms but I’m thinking of learning the ropes of DevOps in 2019.

Sometimes, we may end up in places we don’t expect to be and that’s perfectly fine. What I’d like to you to remember from my post is to re-evaluate where you are right now and truly ask yourself if you love what you’re doing. I think we owe it to ourselves to love what it is that we do since the work is such a big portion of our lives; it has to resonate with you, otherwise, there’s no point with investing all that time.

Kevin out.

2017 successes

0

Hi,

I’m starting the year by taking a look back to last year. A lot of things has happened  and right now, I’m looking ahead for things to come. Many things happened to me. I’m trying to sort them out.

January – August 2017

Those were my last months as an undergrad student in software engineering. I’ve finally graduated. This was a great moment for me ! I was looking forward to it for the past four years !

I’ve had companies tried to recruit me, for instance, Amazon & G-Research. That felt amazing. The thing was that because of personal reasons, even though the opportunity, the tech stack and the location would have been great reasons to relocate, I couldn’t for personal reasons. Maybe in the future, if I have the same opportunities as I once had, I’ll reconsider if those reasons aren’t an issue when they come back.

I’ve got my first job as a software developer in a mobile games studio in Montreal. I was hired as a tools programmer. Ever since I got into software engineering, I wanted to get into the video games industry. I’ve started there in May and I ended things in the last week of September. I wasn’t as passionnate as my peers concerning video games. That much I’ve seen by spending time with them. I didn’t play games on my free time. I wasn’t motivated by my job as much as I wanted to be. I appreciated the time I spent there; it helped me to grow as an engineer, all thanks to the role I was given and my mentors.

August – December 2017

I decided to get into a consulting engineering firm. As a consultant, I’m acting as a programmer analyst II at CAE. I’m mostly working in C#. Within the responsabilities of the role, I feel more empowered by my job than ever. I can now coach interns by answering their questions or helping them through debugging whenever they need help. I was also ask to help for interview process with interns. I’m also helping my team to build their coding standards for PHP & C#.

I’ve decided to get more serious about giving back to the community. I’ve started a C# book for beginners developers. They’ll get to see the fundamentals and build a few projects that lets them grow into their new found skills.

I’ve also decided to move outside of my zone of comfort. In order to do so, I’ve decided to get into Golang and Python in 2018. Since I’m interested by AI & ML, I think it’s the perfect opportunity to get started in Kaggle competitions in 2018 and also complete the Data engineering on Google Cloud Platform I’ve purchased in December. To get to learn about Go, I’ve decided to take my passion of basketball and make it useful by building a model that can generate a potential winning bracket for the NCAA March Madness.

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 – Path.Combine

0

Hi,

I’ve learned about the magic of the method Combine from Path a few months ago. Usually, even in production code, we tend to use string concatenation through either directly using ‘+’ or StringBuilder. Thing is, you do not want to directly use string concatenation to build your path. Try to think about using your code in an other OS, what then ? There’s more logic to think about to build your path. That’s not something that you want. Less code is better code for you, because there’s less to maintain 🙂

Path.Combine does a lot of good ! For whatever OS your code might run on, it will build the correct path by using Path.PathSeparator. While building your path, it’s going to check whether or not the first path already has a separator at the end so it won’t duplicate it. While combining the paths, it’s going to check whether or not every paths, starting from the second one you provide, is a root path or not. It’s really easy to use to ! Being that it can accept an infinity of paths, you have no excuse to not use this jewel of .NET!

Path.Combine(firstPath, secondPath, ..., nPath)

 

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#

SmartSavings: Go full-stack mobile dev – Part 0

0

Hi,

This is my third and probably last post of the day. As you probably know, I’m currently in the process on working on multiple projects and getting out of my comfort zone and I’m going to share my experiences right here with you, readers, so may not have to go through the same challenges.

In order to truly get out of my bubble, I think developing in an entirely new language is required for me. Looking at many available options, I finally set my sights on Golang, google’s programming language. It looks pretty solid, makes me go back through the basics and work with the concurrent paradigm which I really liked with Akka when I got the chance to work with it.

I was looking for a good tech that would let me write my server using something new to me, micro services and serverless architecture. Researching on the web what was already available, I found this great library called go-kit that will enable me to write my micro service system that I’m currently designing. I figured out for fun, since I’m already using Google’s programming language, I should also use their cloud services to build my serverless architecture with Google Cloud Platform. In order to get more knowledge on the platform, I will be signing up for the data engineering specialization on Coursera that starts tomorrow, on the 27th.

As the title said, I’m willing to do an entire mobile application using only Golang. In order to do so, I found something called GopherJS. It’s a Go to Javascript transpiler, or rather a compiler that takes as input Go source code and will output correct Javascript code. Using GopherJS, I can implement my front-end logic without having to stop coding in Go. This is going to be the first time I used something like this. After this, I’ll be able to know whether or not it was a good decision based on scale of a project to use a transpiler so engineers won’t have to get out of their way and simply implement the business logic without having to get out of their stacks and keep being effective. In order implement quickly the app for both Android and iOS, I’ll be using React-Native.

SmartSavings is an idea to solve an issue of mine when I’m going out. I never know where to go or what to do. It’s an mobile recommandation system to help solve that exact problem that I’m having. Basically, after quizzing the users to understand their taste for food and bars, the app will then be able to propose a top 10 spots to go based on those tastes and the position of the user in the city. More than that, it’ll be able to point out what deals that can be found near the current location such as the restaurant A is having a promotion for lunch from 11 AM until 3pm or 16 oz of beer costs 3$ less at this bar than its surroundings for the next two hours. An app like this would be not only a time-saver but also a money saver because it’ll help me make better decisions whenever people want to go to either a restaurant or a bar.

More on SmartSavings as it progresses.

Kevin

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.

Implementing a Stack in F#. Tail Recursion.

0

Viral F#

Since Push requires stacks to manipulate its data, we need an implementation of this data structure. There is of course a .NET implementation, however, it is not a “functional” data structure, in a sense that it is mutable. It is easy enough to implement our own, purely functional, immutable stack.

F# list is a logical choice for an underlying implementation. It derives from Seq (i.e. implements all IEnumerable flavors), has a useful length property which we would like to have for our stack as well:

What remains is to implement basic operations, which are all static members of the Stack module.

These are pretty straightforward. pop function has a slight quirk: we would like to return both the value of the head of the stack as well as “the rest” of the stack. So the return type in this case is a tuple.

Another slight irregularity: stack functions work on…

View original post 270 more words

Bullet points formatter

0

Hey guys,

So this week I worked on a small code kata. The purpose of this project is to simply be able to format text into a bullet point like any text editor allows you to do it. To complete this challenge, I decide to use F# since it’s so great for prototyping and get fast results. The project had the following requirements:

  • Produce an outline of headings
  • Heading values are provided

Here’s an example of what should be printed in console :

  1. Software development is

A. An awesome thing to do

2.  Why do code katas ?

A. They are

i. Entertaining

ii. Challenging

So as we can, we have three different level of formatting to do on the string and heading values are provided for the formatting. Those requirements led to the following code :

code language="fsharp"]
 open System
 open System.Linq 

type Indexes = {
     Primaryint 
     Secondary int
     Third int 
 }
type BulletPointStyle =
     | NumberedStyle 
     | LetteredStyle 

type HeadingWeight = 
     | HW1 
     | HW2 
     | HW3 

type Heading = {
     Weight HeadingWeight
     Text string
 }

type Node = {
     Line Heading 
 }

type Outline = {
     Text string 
     HeadingIndexes Indexes
 }
 with 
     member x.addContent str = { x with Text = x.Text + Environment.NewLine  + str }

let updateIndexes (oOutline) (hHeading) = 
     match h.Weight with 
     | HW1 -> 
         let indexes = { o.HeadingIndexes with Primary = o.HeadingIndexes.Primary + 1Secondary = 1 ;Third = 1 }
         { o with HeadingIndexes = indexes }
     | HW2 -> 
         let indexes = { o.HeadingIndexes with Secondary = o.HeadingIndexes.Secondary + 1Third = 1 }
         { o with HeadingIndexes = indexes }
     | HW3 ->
         let indexes = { o.HeadingIndexes with Third = o.HeadingIndexes.Third + 1 }
         { o with HeadingIndexes = indexes }       

let determineBulletStyle (hwHeadingWeight) = 
     match hw with 
     | HW1 -> NumberedStyle
     | HW2 | HW3 -> LetteredStyle

let getLetter (indexint)=
     (("ABCDEFGHIJKLMNOPQRSTUVWXYZ".[index-1]).ToString())

let formatTextNode(nNode) (oOutline)
     let header = n.Line
     let mutable text = ""
     let style = determineBulletStyle header.Weight
     let indexer = o.HeadingIndexes
     match style with 
     | NumberedStyle -> 
         text <(indexer.Primary.ToString()) + "" + header.Text
     | LetteredStyle -> 
         let head = 
             match header.Weight with 
             | HW2 -> String.Join(""Enumerable.Repeat(" ",4)) + getLetter indexer.Secondary
             | HW3 -> String.Join(""Enumerable.Repeat(" "8)) + String.Join(""Enumerable.Repeat("i"indexer.Third))
             | _ -> ""
          text <head + "" + header.Text 
     text

// Folds an Outline and a list Nodes to an Outline
 let formatTextOutline(nodeListNode list) =
     ( { Text = ""HeadingIndexes = { Primary = 1Secondary = 1Third = 1 } }nodeList) 
     ||> Seq.fold (fun outline node -> 
         let text = formatTextNode node outline
         let outline = outline.addContent text
         updateIndexes outline node.Line
     )

[<EntryPoint>]
 let main argv = 
     let nList = 
         [
              { Line = { Weight = HW1Text = "Software development is" } } 
              { Line ={ Weight = HW2Text = "Super fun" } } 
              { Line ={ Weight = HW3Text = "But challenging" } } 
              { Line ={ Weight = HW3Text = "And rewarding" } }
         ]
     let outline = formatTextOutline nList
     printf "%s" outline.Text
     0 // return an integer exit code

[/code]

So basically, the process is made thanks to formatTextOutline and formatTextNode. Through those functions, I can create the Outline record that holds the formatted text and the indices for the level of formatting (Indexes). When I get in formatTextNode, I can first establish the heading style of the line thanks BulletPointStyle discriminated union(DU) type. Using the style enables me to know if I only have to take care of numbers or the letters. When I have to deal with characters, the HeadingWeight DU becomes handy to see whether or not I’ll be using a single tab (4 spaces) or a 2 tabs (8 spaces).

There you go ! 🙂

Kevin out

Goals for 2017

0

Hey guys,

I’ll start by wishing you readers an happy new year. Lots of things are changing for me this year. I’ll go a quick review of last year

  • I was a full-time intern at Genetec working as Software Developer from Jan to April
  • I gave a tech talk in my local .NET meetup concerning F# and an introduction to functional programming
  • I was a part-time intern at Genetec working there as a FP R&D software developer from May to December
  • I was in the Google Summer of code program for a month before I got too sick to continue working on the project
  • In the fall, I wanted to push forward AugmentedTactics with SmartTactics using F#. The project turned out to be too big for the 3.5 months so it became a tactical role playing game framework (More on this in a later post).
  • I was a top 15% user of stackoverflow (overall top 28% users)
  • I became a 5 Ryu in C# on the codewars platform (www.codewars.com)
  • I got accepted in the Artificial Intelligence Nanodegree program (AIND) (More on this in a later post)
  • Got an interview with both Amazon and Twitter

This year, I’m finally finishing my undergrad in software engineering that I’ve started in the fall of 2013. So I’ve got a lot things to look forward and to think of such as possibly pursuing my studies at a higher level (Master’s degree in software engineering for instance). So I’ve made some kind of bucket list of things I wanted to achieve this year.

  • Get an interview with Google (checked)
  • Become on the proficient level on the codewars platform (4 Kyu)
  • Get a paper published in the CODE magazine (.NET magazine)
  • Do one last hackathon before graduation (doing McHacks 2017 – More on this in a later post)
  • Complete the AIND program
  • Get to know the Python, C++ and Haskell/Scala languages
  • Complete the Google Summer of Code 2017 program
  • Use my TRPG framework and build an AR prototype with it
  • Be a top 20% overall on stackoverflow
  • Write at least 30 posts on the blog
  • Visit a new country
  • Learn a new instrument (been dying to learn the trumpet !)

Well that’s it !

Kevin out.

 

 

Shaping your profesional skills structure

0

Hey guys,

So, professional shaped skills… What’s that. Basically, it’s the form your skills take concerning your expertise in your individual field(s). This form will depend on both depth and broadness. Trying to learn as many things as possible will lead to little depth and a large broadness of skills. The exact opposite leads to an ‘I’ form where you’ve picked up a single domain and you’ve decided to become an expert.

The problem with being a jack of all trades, we can’t justify our opinion on a particular subject, you may be not be in a place to answer that question. Although your opinion may not be value because you’re not expert, I do believe that trying to learn as many things as possible will bring you baggage. This baggage can help form some sort of highly credible hypothesis when you’re asked, let’s say, by a client a particular question such as what should be done in case you’d like to build a website and include the X feature.

Let’s talk about the expert. The expert is the go to guy. He’s the guy you want in your team to be able to quickly build a project from the ground up and see it through. Some problems may occur and because of his/her experience, you will have sound advice when you need to ask the hard questions. Although becoming an expert may seem like the thing to become, I’d advise to think it over again. Becoming an expert in one thing may lead to problem career wise in my honest opinion. You may wake up on morning and feel like you’ve waisted 5, 8 or even 12 years in a field and it doesn’t attract you any longer. You don’t have anything else to fall on.

This brings me to the principal shapes for professional skills. T-shaped skills is when someone would combine some deep expertise on a topic with a broad and more shallow knowledge on things. Pi-shaped skills would be to have two deep expertise and comb-shaped skills one person having multiple set of skills.

In my case, if I were to pick right now the set of skills I’d like to deepen and the rest would be “noise” helping me getting a better all-around software engineer, I would only pick a few. Here’s the list below.

  1. Artificial intelligence and machine learning
  2. Functional programming
  3. Mobile cross-platform development
  4. Oriented-object architecture/design (OOA/OOD)
  5. User experience design

Yes some of those skills are far from each other and some are pretty close to each other. Thing is, right now, there perfectly aligned with the set of skills I have / want to have. More than that, I think those 5 fields are large enough to let me bounce on feet whenever I feel the need.  I can start projects of my own whenever I’ll feel the need. Bottom line, I may not become the best guy in each of those fields. Nevertheless, I think the challenges those fields will make me face throughout my career will make a better developer.

Which one should people try to aim for ? Try to pick 1 or even 2 skills you’d like to develop in your domain. For someone in software development, I could say you could try with web development and databases and move on to other related subjects once you feel comfortable enough to work juggle with new things. Comb-shaped skills are hard to maintain and it makes sense. You need to spend a lot of time to cultivate them and even more time to maintain them. As you become more and more advanced, you’ll need to read research papers, go to meetups and even conferences to deepen your knowledge.

Right now, the skills I decided to work on may seem hard to maintain. I think we should know our limits and see how much time we can afford to spend on those skills. Since I’ve started my career in software engineering, I’ve been able to see what I’m good at but more importantly, what I’m bad at. With those specifics in mind, I decided on the abilities I want to have in a near/far future. I’ll finish with this: have a broad knowledge to become a better generalist and at least one thing where you are an expert.

Becoming a strong generalist will help you decide what you may like enough to start spending more time in it in order to become a specialist. Don’t forget to have some insights on competitive technology stacks that are out there. Each of them will have their strong/weak points.To work on a project, one would need to be aware of what’s out there to be able to make a wise decision.

 

Become better, learn better, do code katas !

1

Hey guys

Today, I’m here talking about how to better ourselves us developers. We’re always learning while working and that’s bad. We should instead learn in our own time and practice before trying to use our tools to resolve the bugs in the software and the features requests from the clients. Learning on the job takes that much more time to work on our things when we should only be working on what we’re being paid for. There are many ways to learn and I’m not saying that sharping your skills with code katas is the best way to do it. No. What I’m trying to say is that you should try to spend some of your free time and practice one of your many languages.

prime-factors-code-kata-practicing-tdd-2014-7-638

Through code katas, one can learn and practice many core and advances computer science/software engineering concepts. A code katas is a problem that must be solve in any way possible. The fun of doing them is trying different ways to solve a problem and see which way would be the best way to resolve the issue. Using a code kata platform such as Codewars, after solving a problem, you can see the solutions of other people. This way, even if you’re an advanced user of X language, seeing other solutions can bring you perspective and show some internal API function you couldn’t have thought of.

And yes, I know you want to become better. One cannot become a master of his/her craft without devoting time to practice and practice. Practice makes better. It’s undeniable. We need to practice and better ourselves. This way, you can be a even better software engineer at work and earn that well deserved promotion. If you’re an entrepreneur, well practicing will help you learn things that code bootcamp couldn’t show you because you have a limited time to see a bunch of stuff.

But let’s get one thing clear. It’s not productive to repeat the same problem. It does not bring you closer to the path of enlightenment. Let’s look at it this way. When we’re babies, we must practice for a long while before we can learn out to walk by ourselves. But after that, “practicing walking” doesn’t make your walking any better, does it ? Practicing the same thing will be beneficial if only you try to include constraints and twists to make it an even better scenario. For instance, well this time, I can only used one kind of data structure or I have to used a maximum of X local variables or I can only used a certain amount of character space.

Code katas bring you closer to the path of enlightenment in cases where you do make it harder and trying other problems. As you solve more code katas, try to take on harder problems. Doing so, this practice is actually worthwhile and those challenges will introduce you to new ways of thinking. I think you can pretty much gather that I strongly recommend acting this way. One thing that I must say is this: try to solve your katas without using an IDE. You’ll be able to remember your basics and try to focus on a simple solution without letting the IDE make life easier for you.

I’ve been talking about using efficiently code katas to improve yourself. I can’t speak for everyone out there, but I would like to attain mastery as quickly as possible. As I said before, to get to the level of skills that you would like to get, you need to practice at an higher level of difficulty. Being used to practice to a hard level, what you do on a constant basis will seem that much easier.

To become better, we must :

  1. Practice smarter. Not repeat the same things but try harder challenges or adding twists in scenarios and make those challenges harder.
  2. Cast aside some of your personal time. Doing nothing more than what you have to do won’t bring where you’d like to be.
  3. Don’t use IDE. IDEs will make it that much easier to use complicate constructs and will auto-complete your solution. Well, I’m saying that for people who are practicing for an interview. You have to remember your language API and be able to solve a problem in front of the technical team who’ll judge if you are at the right technical level.
  4. Look at other’s people code. See, when you solve a problem, you might think that the solution you have is the best one and that was the only way to do it. Looking at other people solutions will bring you clarity and will broaden your vision.

 

On an ending note, you can’t learn everything you want to learn through code katas only. You must also cast time aside for personal projects or try to contribute on open source work. All of this work is necessary to bring you a little closer to the level you’d to be on. And when do get on that level, try to go even further !

 

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

 

GSOC 2016 : The end

0

Hi guys,

Well because of health problems, I won’t be able to meet the expectation for the midterm evaluation coming next week and I will have to step down from the program. It pains me to do so since the project was taking me out of my comfort zone and forcing to adapt to a new stack and way of thinking. I thought that such a project was a necessary stepping stone for my growth as an aspiring software engineer  to be (graduation in July 2017).

Next year, I will apply again and with luck, my health won’t be an issue this time around !

 

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.

 

Euler problems

0

Hi guys,

Late post before I go to bed. I don’t know if you ever heard about Euler problems ? It’s a series of challenging computer and mathematical programming problems. They require some thinking in order to be solved. The reason behind solving them is to acquire better skills at problem solving, which is something that I yearn for. They provide sometimes unusual context in which the mind of the solver will be challenged.

Not only it serves as a way to improve problem solving skills, it’s a tool being used to learn new abilities such as acquiring skills in other programming languages that one may not be familiar with. In make sense to first solve the problem with something that you’re familiar with and then move on to something a bit less familiar. Starting this summer, I will deepen my knowledge in C#, C++,  F# and Java. In the same process, I will also provide solutions in languages I haven’t yet touch :  Lua, Python & Scala

I invite you all to try them by yourself, they’re quite fun to do !

You can take a look at my progress 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#

GSoC16: First coding week

1

Hey guys,

I won’t say yet again that it has been too long because it really was. I’ll try to keep my blog updated weekly concerning a program I’m doing with Google this summer.  It’s called the Google Summer of Code (GSoC). Basically, it’s meant for students to be able to contribute on an open source project with a community listed for the summer while being able to make a few bucks for the summer ($5500 USD).

Why am I doing this? Well, first, I want to expand on the knowledge I currently have. Being in computer science and software engineering, we can never stay in the same place for too long, we got to keep moving forward. By now, you should know that my background is in .NET. I completed three internships in .NET. Something that you may not know is that I completed the GSoC program last year. I had to help the Mono Project to update their code analysis and refactoring library which was using FxCop at the time. Being that I had experience with the Roslyn API, which is a compiler platform, enabling users to develop rich code analysis rules and code refactorings for .NET languages (C# & VB.NET).  So last summer,  what I had to do was to either find old code analysis rules done with FxCop and refactor them using Roslyn and also add a code fix provider matching that rule or implement new ideas that the project owners had in mind. A code fix provider is basically a fix to the “bad code” that was picked up by the code analyzer. For those interested to get to know more about the project or even use the library as an extension to their .NET solution, please take a look there.

Working on that project was a great opportunity as it lead me to my first remote job. Well actually, this is not a job, it’s considered as a student activity. We don’t have a steady wage. There are different phases and if the student passes a phase, he/she gets paid and is allowed to continue working on the project he/she was assigned. So basically, yeah, my first remote job experience. At first, it was difficult to be able to set time aside and focus on working on my project by own at my home or in coffee-house. After a while, it kicked in and I think I did pretty great since I was able to finish my work !

For this summer, I’m completely outside my comfort zone. I have to work with C++ in a Linux Ubuntu environment in order to develop a Telepathy Connection Manager for the Ring protocol. Basically, Telepathy is a real-time communication framework used by clients for instant messaging or video chats. Working with Telepathy and D-BUS, an Inter-process communication system,will be able to communicate with both phones and computers to enable two-way communication.

Right now, I have to do my proof of concept showing that we, at Savoir Faire Linux, are able to communicate by sending text messages back and forth. From that point, it’ll be easier to work on video chat which is far more complex!

Kevin out.

Why F#?

0

Didactic Code

If you’ve been following along with my posts over the past six months or so you can probably imagine that I’ve been asked some variation of this post’s title more than a few times. One question that I keep getting is why I chose F# over some other functional languages like Haskell, Erlang, or Scala. The problem with that question though is that it’s predicated on the assumption that I actually set out to learn a functional language. The truth is that moving to F# was more of a long but natural progression from C# rather than a conscious decision.

The story begins about two and a half years ago. I had pretty much burned out and was deep into what I can only begin to describe as a stagnation coma. I stopped attending user group meetings; I cut way back on reading; I pretty much stopped…

View original post 2,559 more words

Posted in F#

The Rebirth of the Phoenix

0

HEY !

This is Kevin here. This has been way too long since the last time I wrote something on the blog.
Usual excuse, I’ve been way TOO BUSY! But that’s going to change because I miss doing this on a regular basis.
I have so much content, fun content (don’t worry about it, there’s plenty for everyone). For now, there no tech discussion, but they are on their way !

Please stay tune 🙂

Kevin

My first hacking experiences

0

So lately I’m been off the blog and I apologize. I’m still an it engineer student, but sometimes, I feel that we learn much more on our own than just hitting some books and doing tutorials like making a simple UI. Don’t get me wrong, I love studying and what I do in school, but I see that I learn much better and retain the information for a longer period when I try to get it by my own.

What I’m been doing lately is hacking. Hacking is such a strange word for what I did. When I say hacking to people, they then start thinking of me, behind a computer, trying to get into a bank account or something like that. I did hacking in an hackathon which is, in a few words,  an event in which people collaborate to develop a software, this include people like programmers or sound designers. Hackathon can have a theme and teams must follow this theme while they’re creating their software and sometimes, it’s open.

Why do people go there ? It’s my personal opinion that there’s no better to upgrade your skills and validate your current set of skills. During an hackathon, you need to get your hands dirty, you need to get creative, you must be wired into your software and don’t let too many things distract you from your goal.  Usually, you’re never ready for the theme or the given subject, and that’s the fun in it. Why would we want to go there and not challenge ourselves? That’s exactly why I went there. To have some fun, but mostly, to challenge myself.

So yeah, I did challenge myself and you know what? I completely hit a wall. And it was really fun! Don’t get me wrong, I don’t like losing sleep for nothing because yeah, hackathons are not long usually and you must dedicate your entire time to make sure you meet the deadline. Exactly like the way pros would handle a client project when they’re getting closer from the delivery date.

For my first hackathon, I had to make a game based on the theme “What do we do?”. So, my team and I came up with this game where users (4) would have to eat to stay alive or otherwise they would die. Food are separated in two categories: Healthy and fast food. Fast food increases your life and score faster, but it makes you slower and vice versa with healthy food. That’s not the fun thing about our game. There’s this AI, a ninja which happens to be a bear (we found the idea funny and stuck with it) which can attack different kind of players in the game. Sometimes, the attack won’t occur. Most importantly, users have the ability to call him to attack another player if they get to a certain amount of points before the end of the game. This project was not completed on time, due to integration issues on the end, but was a fun project. We met up later and continued to work on it and it’s way to be completed,

My second project made me learn Android development under 24 hours, which was not particularly easy from the get go. Having prior experience with Java made it just a tiny bit easier, but I wish that I would have made my project which what I already knew (Windows Phone 8.1). But I went there to challenge myself and learn new things so I’m not going to complain.

What I want you to keep in mind is that hackathons are a fun thing to do, at least once. They give you a tremendous experience about what’s going on in the outside world.  You have to consume information really fast and perform to the best of your abilities and even beyond that to get things done. More than that, they help you to have a realistic vision of how you have to manage the development of a project under a minimal amount of time. Basically, you’re going to have to lay down core fundamental things that have to be there, be realistic with your set of skills and make sure everything that needs to be there there before you start adding unnecessary stuff.  For myself, hackathons opened my eyes on some things and mostly, on the way I work on my projects. What I remember from all this, my best work is not done when tired. I took a few days and went over my work to correct many mistakes that I made.

Kevin

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);
   }
 }

Book Review: F# for C# Developers

0

This book looks interesting enough to give it a try. I’ll order a copy today.

The Education of a Programmer (Me)

I recently read F# for C# Developers by Tao Liu. As usual, the disclaimer is that I received a copy of the book for free in return for the review. This one was a challenge. Not because of the programming paradigm shift from imperative driven programming in C# to functional programming in F#, but because the density of the book and my having read a different book on F# rather recently.

Mr Liu is most certainly an expert on F#, both from his work at Microsoft and this book. However there were times when I felt a little frustrated in reading the book. My favourite chapter of this book was Chapter 3 where he examines design patterns which can be found in C# and then applies these patterns to F# code. It remains dense reading, but it demonstrates those patterns very well. Mr Liu takes the notion, as I read…

View original post 295 more words

Posted in F#

Being a junior developer

0

Hi,

I stumbled on a really awesome article: What it really means to be a “junior” developer. Jonathan Barronville had some great insights on what it truly means to be a junior developer. For us, freshly out of college with our diplomas, after four years of hard work, we feel like we know everything. That is so wrong because we don’t nearly know enough !  Of course, we saw a lot of concepts and we had tons of practice, but some never had some real world experience.

Knowing a lot of concepts can help you at the beginning, but what really helps is to have real world experience. By having real world experience I mean to have projects when you have set backs at every turn or for some reasons, the project seems to fail and your team have a lot of work to in a little amount of time to deliver a fully functional project to your client(s). See, after writing that article, Scott Hanselman received Jonathan for an online interview. In this interview, he talked about something that we don’t truly value in our domain: failure. And that’s quite right. Who would go in an interview saying that I tried to take on 4 projects by myself right after college to get some experience, but I failed to deliver what was ask  on me on 2 of those projects and one that succeed had some serious memory leaks and I had to re-factor my code. Thing is, failure shapes us. By failing, we learn quite a lot of what should be done and what should not be.

As for myself, I’m still a student who has two more years to do before I can get my degree. Being a student and soon, a junior developer, means something else for me. It’s a world that moves really quickly, and I think (not sure) that it moves way quicker than it did in the past. So, I’m not trying to master everything because that’s impossible. There are things that interest me such as web and mobile applications. Being a student, I have all the time I need to get to know stuff.

I do have some major interest in C# because I’ve been trying a few things such as Java or Javascript. But having a lot of time gives me the freedom to try out new technologies and try to get know them. Knowing the options I can have to create a service or a software can truly help shape the architecture and the design I might take to program my application.

Even though I might know what senior developers or architects are talking about, there’s still a world of difference between “knowing” a technology and really it, inside and out. My definition of a junior developer would be a new programmer who’s still trying out new technologies. Some can’t wait to be seniors or architects. It might be fun to get those titles, but the real deal, it’s the journey that we took to get at this level and that’s what I’m really into !

Kevin

Mobile developer internship

4

Hi,

I’ve been out for a while like I said in this post… I got erased somehow and I decided to re-write it.

So basically, I was saying that I found this new internship as a mobile developer in a .NET company ! It is a third-party Microsoft company which delivers windows phone 8.1 and WinRT (Windows 8.1). More than just this, they do cross-platform development using Xamarin to create Android and iOS apps with C#. See, this is a great language ! I really do love it !

I’ve been busy from catching up with everything I have to get to know to be efficient at my new job. So I put aside my blog but I’m back and here to stay !

More than this, I mentioned in that post that I was currently working on y first windows phone application. During the development, I did a few mistakes, which is acceptable since it was the first time I was doing an app. But there are things that I learned along the road so those mistakes are less likely to happen again !  I’m going to create a blog post which will take us through the app (LearnYourWeather) which allows you to get the weather of a selected city !

Kevin

Software development challenge

0

Hi,

Yeah, it’s me again ! I’ve been missing writing here, so tonight, I’m going to write more than usual ! During the last few days, I’m been surfing the web and I found something quite fun to follow. There’s this woman, Jennifer Dewalt, which was an artist before. Well, it’s my belief that once you’re something, you can’t really say that you’re not anymore even though you don’t practice it. So let’s say she’s still an artist. That’s not the point. She was into programming but had no background. She decided that reading books or going to boot camps wasn’t her thing and did something else entirely.

She gave herself the challenge to program 180 web sites in 180 days. So basically, 1 web site per day. She started small, using HTML5 and CSS3 and then, as she got more comfortable, started using things like Ruby on Rails (Framework derived from the Ruby programming language) or Backbone.js (Framework derived from the javascript). You can read more about it her blog .

So, it got me thinking. Yeah, I do have some programming experiences, but I haven’t been around for that long and there is so much that I don’t know that I can wait to get to know! Basically, for the moment, I’m really into mobile and web application. I’ve thought about to do 100 days challenge in which I do one application per day in which I’m trying to get better with

  • WinRT & WIndows Phone 8.1 +Universal apps
  • Cross-platform development with Xamarin.Android
  • ASP.NET
  • AngularJS
  • Javascript + Backbone.js

I haven’t pick out the exact day when I’ll be doing this, but I will mention it soon (February maybe). For this challenge, what I am going to do is link every project in my GitHub acocunt. But, I won’t go through every project in this blog. Some, which I’ll try to pick out in order to make most out of the learning experience, will be explained.

Kevin

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

OOP: Do you object to this statement ?

0

Hi readers,

First of all, I’d like to wish you to have a wonderful holidays with your family, wherever you are at this moment. During the first lectures, we went over some of the basics of programming. Even though it might have seen like a lot, it was just the core fundamentals we needed to understand the basic logic in any given program. Don’t worry, we’ll cover some more later in the blog. Right now, with what we’ve seen so far, I thought it would be a good idea to get into the hype of object oriented programming.

Say what? Object oriented programming (OOP) ? Sounds funny huh? It is actually a really popular programming paradigm in the developer’s world. It is my belief that we ought all to know more about this. I don’t mean that we need to be expert in this particular field, but there’s so much to do with this paradigm that it would be a shame to not exploit what it gives us !

To begin, what is oriented object programming ? Wikipedia defines object oriented programming as the following: “a programming paradigm based on the concept of “objects”, which are data structures that contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods.”  I’m going to roughly summarize this as a programming paradigm which able a given programmer to place any form of data in an “object” which can be use at anytime for any given purposes such as interact with it.

That’s some heavy abstract notions that was written. In this blog, I’m going to cover as much on this paradigm as I possibly can. OOP has a lot of advantages such as making code more flexible and more maintainable. As much as I would like to tell you that oriented-object programming is the best way to do things that you’d like to do, it is not always the case. In fact, like anything else this world, OOP has some downsides that can be unappealing like the effort it takes. To be really good in this paradigm, it takes a lot a thinking and creativity to create efficient objects which will help you reach your goals. Don’t get me wrong, I like OOP. Even if it takes some time and creativity, you must keep in mind that in any given programming paradigm, coding is a craft that takes time, no matter what you do.

Let’s head back to what OOP actually is. We saw some core basics that we all ought to master if we want to be good, or should I say, great programmers, such as loops or conditional structures (ex: if-else).  With these, we can now move to the next level, in this matter, OOP. In OOP, we define virtual objects in our software. Most of the time, we try to represent real objects from the world such as a car or a an animal (ex: a dog). More than just saying this an animal, we give this object specific behaviors with the help of methods.  Finally, at any time, an object can have a state too, such as being awake or tired in the case of a dog. To wrap up, in order to create an object Dog, we would have to define what is called a class named Dog which would be define with different attributes like a weight (double), a name (string) and a number of legs (int). To interact with this dog, we would have to define the different behaviors we expect to find in this object such as: walking, barking or sleeping. You’ll be able to see below an image that I found on the web,  which sums up what I’ve said

OOP_Objects

In the previous paragraph, I have mentioned a specific keyword of oriented object programming : class. A class is a template in which we will store all the data we need in order to define the object we want to create. That’s all there is to it. When we use objects from this class, we call them instances of the class. When I say instances I mean that once you have created an object of a particular class, you actually are creating a reference which is pointing to the data of this specific class. In short, in your code, you can have multiple references to the same class (instances) but, that does not mean they will contain the same exact data. Let’s say that you’re creating a zoo application. In a zoo, there is more than one animal of the same kind, but they aren’t identical. In the same with objects. Some can be identical. for given purposes, but some are simply not.

While we’re diving in the oriented object programming paradigm, we’ll get to see what truly makes a programming language like C# OOP with the help of encapsulation, inheritance and polymorphism. Without those three core fundamentals, you cannot use OOP with a language. But more on this in a later post.

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.

Motion tracking : Leap motion

0

Hi,

Yesterday, I’ve just acquired some tech device which I’ve been looking forward for quite some time. It is a motion tracking device, called Leap motion.

.

download (4)

This device is quite powerful. By hooking up the device with your computer, you’ll be able to control your computer without the need of a mouse. It’s a tiny device with huge possibilities. The device can track both of your hands at an incredible speed. There are application in the app store for leap motion, with which you can can truly explore the device without needing to touch anything. You’ll see an example of an application in Airstore below :

tech_leap_motion

What really attracts me with the device is that I can develop my own application with it. There are several languages that are supported, but I focus on C# for the time being. But trying other technologies is part of our life as developers, so I’ll try to use other languages if possible.

When I’ll get more experienced with the device, I’ll start a mini series in which I’ll show you how to create your own first application with Leap motion. Just remember, the code won’t work without acquiring a device for yourself !

Kevin

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

Integrated Development Environment (IDE)

0

I can assure you, this is the last post I’m writting before you’ll finally be able to dive into programming. On the plus side, this post is meant to help you with coding. To be able to program any software, a programmer needs an integrated development environment (IDE).

Before, .NET applications were only able to be used on the Windows operating system. But since a great event that happened a few days ago, .NET became an open source project! Hearing this was a source of great joy for us, .NET developers. This means that now you’re not force to have the Windows operating system on your machine, you can now have it on either Linux or Mac OS X.

You have a great selection of IDE to create a software using .NET. Below, you’ll be able to find a small list of IDEs you could use.

  • Visual Studio
  • Xamarin
  • ReSharper
  • SharpDevelop

For my case, I’ll be mostly using Visual Studio, the Community Edition. Some IDEs can be expensive to buy, but this edition is not only free, but gives you the ability to create various kind of apps like :

  • Video games
  • Mobile application
  • Web application

You’ll be able to find the Visual Studio Community Edition here : http://www.visualstudio.com/news/vs2013-community-vs.  Now, we are all set to be able to create awesome stuff!

Kevin