Software Development: Returning Null and Null Checks

This past week I was looking over a number of merge requests and some of them had new methods declared with a return type of String (these are Java classes). With all of these methods if there is a logic issue or some unexpected behaviour then instead of returning an empty String object they all returned null. Personally this starts ringing alarm bells and waving red flags. Why is that you may ask?

If nulls are being returned, passed around to other methods, etc then the programmer will need to check before using that object (well they should anyway). There have been numerous times where I have seen programmers completely ignoring a null check for an object even though the method they used before to set that object could potentially return a null. With every one of these cases I politely leave a comment on the merge request, waiting until an update commit with the null checks are added before merging. Better safe than sorry.

Now am I being too cautious? I tend to lean towards the overly cautious side because it does not take much more lines of code and effort to ensure that the appropriate logging and checks are in place so that unexpected errors and problems with the software are not encountered by the user; plus it means that the software you are writing is safer. Let me know how you handle situations like this. Talking to some of the other programmers I know, they are split on the subject. Some don’t really care what is returned and don’t bother checking the object before use (those I call cowboy programmers), some don’t really care what is returned but do check before the object is used, and some care about what is returned and always check the object before use (I fall into this camp).

Potentially this problem is solved on a case by case basis. Is there a valid reason a null object should be returned? I’ll be doing some more reading about this to get a better understanding to ensure that I adhere to proper programming etiquette and safe programming.

Git: GitHub & SSH Keys Setup

I have generated an SSH key a number of times, either at work or on my personal PC for a number of accounts. Now that I am using my Surface Book 2 as my primary development device until I get a new SSD for my desktop PC, I thought that it might be worthwhile documenting how to generate an SSH key and add it to a GitHub account.

Now if you already have an existing SSH key then you can go ahead and use that but if you have never generated an SSH key before or you may have forgotten how to then hopefully you will find this guide useful.

Assumptions/Pre-Requisites

  1. You already have Git installed on your device.
  2. You will be using GitHub for your repositories.
  3. You are using a Windows environment.

Step 1 – Create a new SSH Key

Do not proceed with this step until you have the pre-requites met otherwise this guide will not work for you unfortunately.

  1. Open your Git Bash Terminal.
  2. Execute the following command replacing <github email address> with the email address you use for your GitHub account:
    ssh-keygen -t rsa -b 4096 -C <github email address>

    The parameters used in the above command are:
    -t rsa – the type of key to create. In this case an RSA Key.
    -b 4096 – the number of bits in the key.
    -C <github email address> – a comment or label for the key.
    For more information about the parameters that can be used click here.

  3. You will be prompted to provide a file location where to save the SSH Key. Press Enter. This will save the file in the default location. Using the default location is recommended in this case.
  4. You will be prompted to enter a secure passphrase. If you choose to provide a secure passphrase then it will secure your SSH Key, this is a recommended step.

Your SSH key should now be generated 🙂

Step 2 – Adding your new SSH Key to the ssh-agent

If you have successfully performed the step “Step 1 – Create a new SSH Key” or you already have an SSH key that you want to use then you can proceed with the following step.

  1. Open your Git Bash Terminal (if you have closed it).
  2. Execute the following command:
    eval $(ssh-agent -s)

    This will start the ssh-agent in the background.

  3. Execute the following command:
    ssh-add ~/.ssh/id_rsa

    Note: If your key is not in the file named “id_rsa” or is not in the same location then you will need to replace the value id_rsa in the command with the name of the private key file and/or the location of where the file is store. The above example is for the default name and location.

Step 3 – Adding your SSH Key to your GitHub Account

The hard work is now all done. The next part is super easy even though there are more steps.

  1. Open your Gut Bash Terminal (if you have closed it).
  2. Execute the following command:
    clip < ~/.ssh/id_rsa.pub

    This will copy the content of your public key file ready to be pasted into GitHub. It is important to not add or remove any spaces or newlines to the content.

  3. Log into GitHub.
  4. Navigate to the “Settings” page.
  5. Under “Personal Settings” select “SSH and GPG keys”.
  6. Click “New SSH key”.
  7. Add a Title to your key. In this case for me it was generated from my Surface Book 2 so I made sure that it was referenced in the Title.
  8. Paste your key in the “Key” field.
  9. Click “Add SSH key”.

You should now see a new SSH Key added to your GitHub profile.

For more information generating your SSH Key, adding your SSH Key to your GitHub account, and other SSH connection information take a look at the GitHub Help Page. I have tried to simplify the process by combining the information that was scattered across two to three pages from the GitHub Help Pages into one page. The GitHub team have done a fantastic job in documenting the entire process however and the above link should be used if my steps are not sufficient or confusing in any way.

Returning to C and C++

Since the start of my third year of my Computer Science degree I have not really done much C or C++ programming. My primary programming language at the moment is Java and on the side I am doing some C# work. C++ was the very first programming language that I learnt by myself and during my bachelor’s degree it was the first language along with C that I was taught. There is some stuff that I really like and there is some stuff *cough* pointers *cough* that really annoy me.

With a fairly new laptop (my Surface Book 2), I thought it might be worthwhile to get back into some C and C++ programming. Java and C# are great programming languages but sometimes it is good to go back to your roots and program in a language that is significantly more low level. The attention to detail and level of understanding is significantly higher in C and C++, than Java and C#. If I ever start to feel lazy while programming in Java or C# I think back to how difficult it was to implement some things in C or C++.

I have Visual Studio 2017 installed on my Surface Book 2, but what I really want to do in C and C++ does not require the overhead for the projects that come with using Visual Studio. So instead I am going to use Cygwin (gcc and g++) instead. If you want to use Visual Studio then that is fine but to help others I am going to go into detail about setting up Cygwin so that you can run the gcc and g++ commands to compile and build your C and C++ programs.

Cygwin

Just like on the Cygwin web page “Get that Linux feeling – on Windows“, installing, configuring and using Cygwin is super easy. You can download the 32 or b4 bit versions of Cygwin at the following location. I am going to go over the installation and customization so that you can easily compile and build your C and C++ applications.

Installation Wizard

Once you have downloaded the relevant executable for your OS, run your executable. You should be presented with an installation wizard. Just follow the installation wizard. I used the default settings for the installation. I didn’t change anything and I suggest that you don’t either unless there is a specific reason to. All the paths and command line information presented below assumes the default information.

Note: When you are presented with the following screen on the installation wizard, ignore selecting any package and just press the Next > button. We will be using command prompt to get the necessary gcc and g++ packages.

Cygwin Installation Wizard Select Packages

Continue with the installation wizard and let the dependency download commence. Depending on your download speeds it may take some time to download all the necessary dependencies.

Package Installation

Now one of the very most important components for getting a compiler working outside of using an IDE like Visual Studio is making sure that you have the necessary packages. Open Command Prompt and enter the following in the command line:

setup-x86_64.exe -q -P wget -P gcc-g++ -P make -P diffutils -P libmpfr-devel -P libgmp-devel -P libmpc-devel

Note: The location of the executable was placed in my Download folder and the command was executed from that directory after I navigated to it.

After you have executed the command, the Cygwin setup should relaunch and it should proceed with the download and installation of the packages that were listed in the command line.

Verification

That is it 🙂

The compiler is installed and you can verify this by launching the Cygwin Terminal and entering in the command:

gcc --version

or

g++ --version

You should see the following displayed on the terminal. The versions of the compilers may be different depending when you install Cygwin and/or if you manually update to an even later version of the compiler (this has not been done here).

Cygwin Terminal Compi;er Versions

To test the compiler out (I’ll be testing the C++ compiler here) we can create a very simple C++ application and use the g++ compiler. The very first C++ program that I ever wrote was a simple Hello World program. What better way to test the installation of the g++ compiler than to use that simple C++ program. Below is the sample code in case you want to start learning C++ and/or you just want to quickly test your compiler but not actually write any code yourself.

#include <iostream>

using namespace std;

int main() {
    cout << "Hello World!" << endl;
    cin.get();
    return 0;
}

Save the above code as HelloWorld.cpp or use your own piece of C++ code and place it in the location of your Cygwin home user directory. By default it should be under C drive, ie. C:\cygwin64\home\<username>.

To compile the C++ code all you need to do is run the following command in the Cygwin Terminal:

g++ HelloWorld.cpp -o HelloWorld

What this will do is create an executable that is called “HelloWorld.exe” that you can then run from either the terminal or straight from the Windows Explorer. If you run the above piece of code in the Cygwin Terminal then the output should match exactly what is shown below; note that the program is waiting on user input before it terminates.

Cpp HelloWorld Terminal Compile And Run

There you go. You now have a Linux like C and C++ compiler installed on Windows and you do not need to have an IDE to compile and build your C or C++ projects. Hopefully this little guide and my desire to go back to C/C++ has fueled your own fire. Enjoy!

Software Development: Crunch

Nearly everyone in their working life will experience at some point a very tight deadline, significantly increased pressure to complete a specific task, and/or an insanely amount of extra hours that are expected of you to do. In the software industry (could also be used in other industries not too sure) this is referred to as “crunch“. There are many articles out there about crunch, especially in the video game industry. It is a time where you rarely see your family and friends, you eat and drink way too much junk food, your regular exercise regime is thrown completely out the window, and you may even dream about the code you had written (and not in a good way).

Currently during my software engineering career I have only ever experienced this crunch period twice. I wouldn’t consider the first time really crunch though. I did have to work towards a really tight deadline, longer hours, but it was only for a very short time. The second crunch I experienced was recently and it was for a longer period with an insanely tight deadline, a significant amount of work, and very long hours both during the normal work week and weekend. Personally I think crunch every so often, but not too frequently is a good thing. A little stress and hard work can be beneficial. In saying that though, working in an environment where you are in crunch mode every couple of weeks is probably not great for your well-being and highlights a potential problem with the operations of your organisation.

During my crunch I had to unfortunately stop attending my BJJ classes, working on my side projects, playing video games and even going out with friends and having a couple of beers. After my crunch period ended, I was exhausted but I made a commitment to myself to go back to my BJJ classes and attend my usual social gatherings at the minimum. With the software engineers that I worked with during this crunch period, I asked them how did they cope with all the stress, what techniques they used to mitigate feeling like garbage, and do they have any tips or tricks to make crunch not feel like a massive drain? All of them essentially came back with the same or similar responses:

  1. Breathe and take everything one step at a time:
    • Don’t panic as panicking will only make things worse.
    • Rushing or not paying attention to what you are doing will only cause you to make more mistakes and then cause you to panic even more.
  2. Switch off after your day is done:
    • You most likely won’t work for 24 hours so when you are done for the day and have worked close to 20 hours, clock off.
    • Focus on something you enjoy and do not bring your work home with you.
    • Be with your family and/or friends, or enjoy what little sleep you can get.
  3. Communicate and do it early:
    • There is nothing worse than needing help and not asking for it, you will only then fall further behind, rush and make mistakes and/or panic.
    • Others may be able to help you solve the problem faster and you will less likely panic if you know that others are here to help.

Along with all of these handy little tips and tricks I remembered some of the useful information that was presented in “The Clean Coder: A Code of Conduct for Professional Programmers” Chapter 11 – Pressure. That chapter essentially had the same information as what my colleagues had said to me.

Come the next crunch (which I know will happen at some point in the future) I will be better prepared mentally and will ensure that when I do get some time to myself\ I spend it making sure my body gets the rest it deserves or spend it with the people I enjoy being around. Keep my mind and body sane and happy 🙂

Java Deprecation Annotation

An annotation that is near and dear to my heart; as someone who constantly evolves their classes it is vital that if I cannot remove some old methods and/or fields at a single moment, I correctly identify that they should no longer be used and a new method or field should be used instead. I have also been seeing it more and more the last couple of days on the open source projects that I am viewing (which is strange as this is not the first time I am thinking about a certain concept and then it appears everywhere).

The reason why I really appreciate the @Deprecated and @deprecated Java annotations are because as your classes evolve you sometimes have to signal to the developers working on the project that “hey this should no longer be used, it has been superseded by another method and you should use that one instead”. Both these annotations do just that.

@Deprecated vs @deprecated

If you take a quick look at the annotations then you may not see the difference. But having a capital letter ‘D’ instead of a lower case letter ‘d’ is important.

The @Deprecated annotation is to let the compiler know to generate a warning whenever your program is using the class, method or field that has the annotation.

The @deprecated annotation is specifically used for the Javadoc and notifies to the developer to not use the class, method or field and use the appropriate superseded one.

Generally I use both. @Deprecated to actually deprecate the class, method or field and then the @deprecated annotation in a comment to highlight which superseded class, method or field to use instead, and also very importantly note why the class, method or field was deprecated.

I have seen plenty of times only @Deprecated is used with no information as to what to use instead, which is slightly frustrating. It is always worth spending a small amount of time to correctly document why something has been deprecated and what to use instead, it makes everything much easier for you and everyone else.

Using @Deprecated

It is very simple to use the annotation.

To deprecate a class:

@Deprecated
public class Person { ... }

To deprecate a method:

public class Person {
	...
	@Deprecated
	public String getName() { ... }
	...
}

To deprecate a field:

public class Person {
	....
	@Deprecated
	private String name;
	...
}

Using @deprecated

Just as important as deprecating a class, method or field I believe in documenting what to use instead and why the original class, method or field has become deprecated. This annotation is sometimes missed by many developers from the open source projects that I have looked at.

To document a deprecated class, method or field:

/**
 * @deprecated
 * Replaced by {@link #Entity}
 * No longer valid as a Person objects are replaced by Entity objects.
 */
@Deprecated
public class Person { ... }

Official Documentation

For more information about the two annotations then take a look at the official Oracle documentation, here.

Software Development: Try Catch Finally

I have been meaning to write another software development blog post for a little while now, but had struggled to come up with something that is really worth writing about. After browsing StackOverflow and various programming forums and blogs I finally decided that it may be time to visit the “Try Catch Finally” code block. At work recently I have been using it more frequently due to the functionality that I am needing to implement (reading from files/streams, and writing to files/streams).

I’m not going to go into too much detail but just cover two of the areas where I feel plenty of developers either fall short or forget certain concepts about the “Try Catch Finally” block. One of these is hopefully blatantly obvious while the other may not be so clear.

Not a Logic Workflow

Your “Try Catch Finally” block should not be used as a means to control your logical flow of your application. I have read a number of times on StackOverflow where there have been contributions/answers that say something along the lines “Use the ‘Try Catch Finally’ instead of ‘If Else’ to control the flow of your application”. To other contributors credit these contributions/answers get down voted and commented heavily saying that this is wrong, not good practice and is not the reason to be using a “Try Catch Finally” block in the first place.

This thinking is wrong (using a “Try Catch Finally” for logical workflow), in that the “If Else” block is a means of controlling the logical flow of your application and the “Try Catch Finally” block is a means of handling thrown exceptions from your application. I always try to check for nulls, the correct format and instances of objects before using them (where ever possible), but I also always encase my methods with an appropriate “Try Catch Finally” block. Not only is this good programming practice but it helps ensure that your application is bullet proof, everything is logged and nothing unexpected happens.

For example if I am reading or writing to a file/stream there is always a chance that an IO exception will be thrown. By encasing my logic in the “Try Catch Finally” block I can correctly handle this exception, log it and then in the “finally” part close the file or stream if it is still open after the exception.

Remember this if you are to take something away from this post:

  1. “If Else” statements control your logical flow of your application.
  2. “Try Catch Finally” statements handle your exceptions thrown by your application.

Execution of Finally

This got me at first when I was learning about the “Try Catch Finally” code block. In nearly all circumstances the “finally” component will always get called, even if there is no exception thrown in your “try” component and you are returning. Originally I did not believe this but when I tried it out for myself, I was so surprised; I was not lied to by my lecturer, the textbook and the website I was referring to. If all three sources all said the same thing then I probably should have believed them I guess 😛

Here is an example where you may think that the “finally” component will not get called.

public String getStringValue(String value) {
	...
	try {
		if ("None".equals(value)) {
			return "Nothing";
		} else {
			return "Found at least one.";
		}
	} catch (Exception e) {
		logger.error(e.message());
		// Do more stuff.
	} finally {
		Console.WriteLine("I was still called.");
		// Do more stuff.
	}
	...
}

Why might you think that the “finally” component is not called? Well in the “try” component there is a return statement. If the method in the “try” does not throw an exception then we should drop out of this “getStringValue(int value)” method. However, as we have a “finally” statement, before we drop out of this method we will always write to the console “I was still called.”, and do any other stuff that is not shown in this code snippet.

To all the developers out there, if you use add a “finally” component in your “Try Catch” statement then be aware that it will always be called.

UWP: Localized String UI XAML Properties

I was messing around in Visual Studio today and decided to spruce up my UWP apps a little bit. Originally what I was doing for all my string UI XAML properties on every project was hard coding them in the XAML code like this:

<PivotItem Header="Item 1">
    ...
</PivotItem>
<PivotItem Header="Item 2">
 ...
</PivotItem>

However there are several major flaws with this:

  1. Your strings are hard coded in the XAML code and if you were to make any modifications it would need to be done programmatically which could get messy.
  2. There is no consideration for other languages other than the one you have hard coded; a big oversight if you plan on releasing your app worldwide.
  3. It is not very flexible and easy to manage; if you need to change your strings it would have be done across a number of XAML files and it could take a long time to change everything.

Nearly every tutorial or blog post when they are writing string UI XAML properties they  always do this ‘hard coded’ method. Even Microsoft does this on their official page when outlining the different Controls and Patterns, see the Tabs and Pivot example here. Really though, I don’t blame them as it is really simple and gets the picture across nicely for beginners and the focus is really on the Controls and Patterns. However if you are going to be making a commercially viable product that will be used across different continents, supporting a number of languages is critical.

Eventually to solve this problem you have to do some Googling or Binging (not sure if that is the Bing equivalent), or if you use the new extension/tool called the ‘Windows Template Studio’ to help build your new app it sets everything up nicely for you. This is all well and good if you use the extension/tool but if you are not, then Microsoft again has a convenient page to look at, see here. I used this page to solve this very same problem and it should help you as well.

The solution to this problem can be broken down into several steps:

  1. Set a Default Language on your Package.appxmanifest (outlined in red).
    Package.appxmanifest Default Language Setting
  2. Create a ‘Strings’ folder in your root project solution.
  3. Create a subfolder that matched the Default Language you have set.
  4. Create a Resources.resw file under the subfolder.
    Default Language Strings Folder Structure
  5. Add all your string UI XAML properties in the Resources.resw file where:
    1. Name: The XAML property you are referencing including the XAML object.
    2. Value: The value for the XAML property, what you want shown.
    3. Comment: A simple comment to help identify and describe what the property and value is for.

The Microsoft page listed above outlines a very simple example and how to test your application, so I am not going to go into further detail here and I suggest you look at their example and testing method. If you are starting out doing some UWP app development then you might not be aware of what the best practices are (I still don’t), so hopefully you find this information useful and you can create commercial grade UWP apps for the Microsoft Store.

UWP: Loving the Windows Template Studio Extension

I subscribe to a number of development blogs and articles, and I have been meaning to play around with the new Visual Studio extension that got announced at Build 2017 for a while now. What better time to use it than when I am about to complete the transition from “proof of concept” to fully fledged Universal Windows Store application?

Installing the Windows Template Studio Extension

Microsoft has made it super simple for anyone with Visual Studio to install this new extension. If you have Visual Studio 2017 (I have not personally tried it on an earlier version of Visual Studio), navigate to Tools – Extensions and Updates…

Once the new Extensions and Updates window appears, on the left hand side navigation pane select Online and then Visual Studio Marketplace. On the top right hand side there is a search bar, enter “windows template studio” and press the Enter key on the keyboard. You should see Windows Template Studio now appear in the list of tools and extensions. Click Install after selecting the Windows Template Studio extension; to start and complete the installation you will need to close Visual Studio.

After the installation process completes and you restart Visual Studio, you should see the extension Windows Template Studio with a green check mark. A screenshot of a successfully installed extension/tool is shown below.

WindowsTemplateStudioInstallation

Using the Windows Template Studio Extension

With the installation complete we can start using the new extension. I was super excited to see first hand how the extension could simplify the process of creating a new UWP application. If you haven’t opened Visual Studio, open the application. Create a new Project (default shortcut key is Ctrl + Shift + N). Open the Windows Universal Visual C# Template on the left hand side pane and select Windows Template Studio. Fill in your solution/project details as you see fit and click Ok.

UsingWindowsTemplateStudio

The Windows Template Studio wizard will launch and right off the bat it offers some templates and frameworks to get you started on the right foot; a good first sign. First you get to choose a Project Type; and you get three options (I guess the options they give are ones that most developers will use when developing their apps). You also get to choose a Framework, one of which is based on a third party; it looks like Microsoft isn’t playing any favourites here and is offering what they feel is best for developers (this goes to show how much Microsoft has changed and how much they really care about developers). Click Next once you have chosen a Project Type and Framework.

WindowsTemplateStudioWizard1

If you have never developed for the Universal Windows Platform then already having a Project Type and Framework setup for you makes things much easier for you in the future. But now is where the true customization and helpfulness really begins; in this part of the wizard you get to add the Pages and Features you want to your application. To make the next couple of choices easier for you, it would be beneficial if you nailed down how you would want your application to look and how many Pages you want (but you could always manually add more at a later date).

You first get to add Pages to your application. I found this part of the wizard extremely useful as it provides some common Page Types such as Settings, Map, etc. A bonus is that you can add as many as you want 🙂

WindowsTemplateStudioWizard2

Microsoft went above and beyond for the Features part I believe, kudos Microsoft. You get a plethora of Features to choose for your project. They are some of the most common when working on your application such as a First Run Prompt, Live Tiles, and Suspend and Resume. I really appreciate how Microsoft broke them all down them into easily recognizable Features, and on top of that if you are not sure what the Features do, there is a little information button you can click to learn more. Once you have selected all the Features you want click the Create button

WindowsTemplateStudioWizard3

If you look in your Solution Explorer, you will find all the Pages and Features that you selected ready for you to work on, just like magic. It could not be any simpler. If you want to start developing for the Windows platform and you choose UWP, then it would be foolish to not use this extension. It is easy to use, offers all the basics and groundwork to get started quickly. When I start working on any new UWP project, I’ll be using this extension going forward unless I can add all the necessary features faster myself (but most likely not). Overall I am very impressed with the options that you could choose to quick start your development.

For more information about the Windows Template Studio Extension have a look here and here.

UWP: Dynamic UI 1/2

If you are new to C#/UWP programming then one of the furthest things that may have crossed your mind is a UI that is dynamic and fluid based on the screen size or the device form factor your application is running on. However this concept is very important and is super easy to implement. So I thought I might do a little write up about this and help some people out. I know I may not have all the information presented here but I would like this to be a starting point that others can build on and hopefully this post is useful to some.

When I first started working on developing UWP applications I tried to have the core functionality working for a desktop PC, i.e. anything from a 12” screen sized device and up; and I did not really consider other form factors like mobile devices or the HoloLens. But the more I work on UWP applications and how simple it is to implement this functionality I ask myself, why not consider it up front? Microsoft actually has some really useful information and even provides a worthwhile example, see here. Plus there are numerous StackOverflow questions with answers and blogs/articles that discuss this exact topic. So now when I work on any UWP application I consider what UI elements need to be placed where for the various form factors and screen sizes.

If you use the link provided above then it will already place you to the correct spot in the article that outlines how to modify the UI layout based on screen sizes/form factors. The method to have your UI change based on your form factor or screen size I will be discussing is the use of Setters, StateTriggers, and AdaptiveTriggers.

Setters, StateTriggers and AdaptiveTriggers

Some of the advantages of using the new Setters designed for Windows 10 over the Storyboards that you would have had to previously use are:

  1. No more GoToState method call in your code: there is no C# code that needs to be written when using the new Setters; your application will dynamically change layouts when the state condition is met.
  2. Cleaner XAML Code: syntactically the XAML for using the Setters is cleaner and easier to read. The Storyboard objects could sometimes get very complex and large I found.
  3. No empty DefaultState: the properties in your XAML outside the Setters appear as your default properties and the Setter values will not be triggered until the state condition is met. You do not need to define an empty DefaultState.

Using the Setters, StateTriggers, and AdaptiveTriggers are extremely easy as well. The Microsoft article provides a solid example but I am going to provide two more for reference. In the first example I will showcase the change in font size when the screen changes size, and the second example will showcase rearranging of TextBlock objects when changing screen sizes and on a small form factor device like a mobile.

Example 1: TextBlock Font Size Change

This was actually one of my very first attempts to have the UI dynamically change with a changing screen size and form factor. Below is the XAML code that I wrote to get the font size to change for a TextBlock object that is displayed to the user; some of the unnecessary XAML code has been omitted.

<Page>
  <ScrollViewer>
    <VisualStateManager.VisualStateGroup>
      <VisualStateGroup>
        <VisualState>
          <VisualState.StateTriggers>
            <AdaptiveTrigger MinWindowWidth="720"/>
          </VisualState.StateTriggers>
          <VisualState.Setters>
            <Setter Target="TitleTextBlock.FontSize" Value="24"/>
          <VisualState.Setters>        
        <VisualState>
      </VisualStateGroup>
    </VisualStateManager.VisualStateGroup>
  </ScrollViewer>
  <Grid>
    ...
    <TextBlock Name="TitleTextBlock" Text="Bill" FontSize="12"/>
    ...
  </Grid>
</Page>

As you can see the amount of XAML that needs to actually be written is fairly minimal. How does the StateTrigger actually work? The AdaptiveTrigger object defined specifies that if the screen size is more than 720 pixels (that is the state condition) then the TextBlock object will have the font size set to 24; however if the screen size is less than 720 pixels the TextBlock object will have the font size set to 12. This can be seen working below (using the exact XAML code above).

DynamicUIFontSizeChange
Example 1: Dynamic UI TextBlock Font Size Change

My next example will be in a follow up blog post, so stay tuned for another post real soon about Dynamic UI. That one I feel is more important and relevant as it moves UI objects around to ensure an optimal layout for a change in screen size and what it looks like on a mobile device.

Software Development: Reducing Technical Debt

Another topic that has peaked my interest recently and I have started to pay particularly close attention to as I started to really work hard and ensure that I am following best programming practices and reduce any introduction of “code smell” into any code repository that I contribute to, is how to reduce the amount of technical debt a project’s code repository has and to not further increase said debt (sometimes this is not an easy task).

What exactly though is “technical debt”? The definition that Technopedia provides sums it up pretty good in my opinion [1].

“Technical debt is a concept in programming that reflects the extra development work that arises when code that is easy to implement in the short run is used instead of applying the best overall solution.”

Some of the causes of technical debt that Wikipedia also provides are also very good and I have worked on projects that have code base’s with technical debt that range from extremely high to very little. Below are several that I personally feel are major contributors when working on projects of any size [2]:

  • Insufficient front up design (just take the extra time to think about the implementation, it will help in the long run)
  • Business pressures (unavoidable, especially when you have obligations to meet, etc.)
  • Tightly coupled components (most likely the cause of bad design to begin with, so design and plan ahead first)
  • Lack of a test suite (all too common in most code repositories, test driven development not utilized or unit and integration test harnesses are missing entirely)
  • Lack of documentation (again, all too common; not enough time to write up the necessary documentation to not only help you at a later stage but others working on the project too)
  • Lack of alignment to standards (sometimes developers feel the need to re-invent the wheel and re-write already publically available libraries, frameworks and APIs causing a major headache down the line)

Now that we have highlighted what technical debt is and some of the causes, it is just as important to try and reduce this technical debt over the lifetime of the project. However sometimes this is just not possible due to a number of uncontrollable factors. Other times however it is squarely in the developer’s hands to reduce as much technical debt as possible while not increasing it as bug fixes, features and improvements are added.

One way that has really helped me is with the use of third party tools and plugins. On most repositories that I work on now, to limit the introduction of “code smell” and ensuring that the technical debt is not increasing, the Git repositories have SonarQube [3] installed on them. Not only does it highlight bad programming practices when there are merge requests but it also analyses the health of the code repository. So there is now no excuse when someone merges in poorly written code when there is an external and impartial tool also looking at the merge request and not just the assignee/assignees who will merge the code; humans can miss some of the obvious things, machines with the correct setup can spot the faults instantly.

Along with the Git code repository monitored, I use a plugin called SonarLint [4] for IntelliJ that highlights poor programming practice and bad code before you even submit your merge request. With the use of this tool, not only does it ensure that I do not contribute to the technical debt, but it encourages me to design, plan and think what I am implementing. Before I was using the plugin, I generally thought that I was writing some good code. However when I started using the plugin it kept flagging my code and letting me know that it was not good code (slightly depressing really); but it taught me that there is still so much more I need to learn to ensure that I write good code. Now that I have been using it for a little while now, I have been getting flagged less and less (so that’s good to know that I am learning and getting better at writing clean code).

Another way that I try and ensure that the technical debt is reduced is whenever I submit a merge request to resolve a bug, or implement a new feature; I try and ensure that the class, method or module that I worked on is in a much better shape than when I found it. Sometimes it will involve doing some light refactoring, other times it will involve re-writing a small chunk of the class or method. However I only ever do this if I know exactly what I am doing, and have experience with the class, method or module. I never try and do this on code that I have very little experience with or don’t know what exactly the code is supposed to do because I could end up leaving the project in an even worse state. People I have talked to about this practice fall into several camps:

  1. If you are not directly working on that component don’t touch it. Just do your part and that’s it.
  2. Why are you refactoring something if you don’t need to? Leave it someone else will refactor or fix it later.
  3. Good show of initiative and desire to clean up the repository, I might end up doing the same. Every little bit helps.

The fantastic thing I have seen is that there are far more developers in camp 3 than in camps 1 and 2. I can see where developers from camp 1 are coming from; making changes to code that directly does not impact your change could pose a great risk, but if you know what it is doing and how to clean up or optimize the code, then why not try and make the repository a little better for all? If there is a TODO or FIX ME comment, then why not fix it while you’re poking around anyway? Camp 2 to me seemed a little odd. Why wait for someone else to fix something if you are already in there fixing or adding something anyway? Could this just be a lazy developer doing the bare minimum? Perhaps. Camp 2 had the least amount of people in it, but I was surprised that was even a response from some developers.

What camp do you fall in? Is there another camp out there? Let me know some of the techniques you use to reduce the technical debt and limit the amount of “code smell”.

[1] – https://www.techopedia.com/definition/27913/technical-debt

[2] – https://en.wikipedia.org/wiki/Technical_debt

[3] – https://www.sonarqube.org/

[4] – http://www.sonarlint.org/intellij/index.html

%d bloggers like this: