What if the worst happens?

I see a lot of companies rush, rush, rush and push, push, push to get things in fast. They want to deliver new features every second if they could. However this has big risk and future problems they keep coming. I always say Prepare for the Worst and Hope for the Best!

This I find is the best saying to use, whenever you think ‘should I just do this little thing or not’. If you ever look at a problem and think something could go wrong here then put in a worst case solver.

Some of the trip ups I have see have been to do with logging, which can either be to little or even to much. You can always do with logging to save you in the live environment. When issues start happening you need to diagnose what the issue is straight away, but you can’t get the details without some logging as to what is going on.

However you should only log the things that could fail, but of course shouldn’t be. An example is, I have created a method that actions dynamic changes on multiple elements, but if one element is removed I don’t need to know about it. I just need the method to continue running, so I could put a try catch round it and then let it go with no logging. This prepares for the worst and then lets the best happen. However If I have built a method that the application needs all elements to be present, then I want to log the error for reporting so it can be fixed as soon as it is seen.

There has been sometimes that someone has added masses of logging at every section, then the server starts throwing warnings up or just falls over. So your best is that the program works as you need, but your worst preparation is you have logging to review any errors. You then also have the best prepared with as much useful logging for review as you need and also the worst is you don’t put in unnecessary logging. There is always a balance between too much and too little that needs to be looked at.

Something logging and other attributes can do is take up memory. This can then build up and take down servers, as I have recently also found. I deployed a nice new OSB service and added one new log that would be fired each time someone submitted the form. This to me didn’t seem much as it was a small file, but then once it was live there was a report about the logging from the support team. Although it was a lot of logging that could build up over time, it was also not helped that the server was full 95%. This means it could fill up at any point.

If you are going to have a well organised and dynamic server, then there should be scripts run daily or monthly that clear up the files. This could either delete the logs older than X number of days or even just package them and send to another locations. It is super risky to be running a server at 95% full and expect nothing to tip it over the edge. Regular maintenance and checks should be carried out so that this is caught at the first site.

One that all developers should be using is a good old Try Catch. If you are not sure what one is, without being too patronizing, it looks like this in JavaScript for example:

try {
//Code attempted
}
catch(ex){
//Exception caught
}

You should use these anywhere there could a potential break even if you want something to react to it or not. For example you would put one round a submission from a form. This would then catch if it failed and for what reason, then from this you could display a notice informing the user what to do next. You could also do it for example if you are dynamically loading content in a loop, you could put one round the code within the loop. If one of the calls to get content fails it could trip over the Try Catch, but then continue getting the rest of the content. The user then need not know that something went wrong and then you can either send an error message to support or just let it continue.

These can be really helpful to stop your application from breaking in unwanted ways like with server errors, but again you don’t want to over use them and you want to be sure they errors are being picked up.

Another method to get around the errors cropping up is putting default values. I stepped into this one when someone create a switch statement, but with no default case (C#) and the variable that was being set inside was set to null at the beginning. This was working fine for some time as the cases that were there met the demand, but further down the line the content editable variable that was being checked in the switch had changed. This meant that the variable being returned was null and breaking the application.

To get around this you should first try to make the check dynamic or dynamically changeable, so when a new value is added then the new result can also be generated. The other thing that should always be done with Switch statements or any other kind of statement that provides the option, is put a Default. Example:

Switch (Number){
Case 1:
//Do thing
Break;
Case 2:
//Do this
Break;
Default:
//Or else do this then
Break;
}

It just means that there is a result from the statement no matter what. At best, unlike this scenario, if you are setting a variable in the statement you should always return a valid result and then handle the result. For this instance an empty string could have been returned and all would have worked fine.

These are some of the ways developers can prepare for the worst and stop stupid mistakes. If you have seen any silly things happen that could be avoided then comment below with what, why and most importantly how to fix it.

 

Good, Bad and the Ugly Commenting

I feel that it is important to comment your code and make sure that the next developer that uses the project knows what the hell you have done. However I have seen over the time I have been developing a lot of different ways people comment, so here are some of the dos and do nots with comments. This will give the final answer as to what people think is the best method to comment and why?

As you would know reading this there are many languages and methods to commenting. Some are particular to the coding language itself like ASP.NET. In C# ASP.NET you can /// above a method to attach comments about what it does, uses and delivers. However in JavaScript you don’t get this ability, so to say the best method is the C# ASP.NET method is wrong. Instead it is more about the fails I feel people make in general, for which I will use particular languages as examples.

I have seen when people give a massive explanation into what and why this method is here. This is should be an example to the developer the code is to complex. Change the method so you don’t need that many comments.

Adding your life story:

// This is a big file I thought would be very good to have
//You might have to look at the middle or the top.
//It will help to look at this file.
//Don't forget to save it

The below is a bit over the top, but then again you do find some that find the need and the time to construct this. However I do see the creative kind that make the comment contained in a nice box with tables etc. This is not just a waste of space, but also of bits of data. I know it is small space it is taking, but it adds up if you are trying to make it as fast as possible.

The designer:

/*
(_.-/'-'\-._)(_.-/'-'\-._)(_.-/'-'\-._)(_.-/'-'\-._)(_.-/'-'\-._)
|| M ||      || O ||      || N ||      || K ||      || E ||      || Y ||
(_.-/'-'\-._)(_.-/'-'\-._)(_.-/'-'\-._)(_.-/'-'\-._)(_.-/'-'\-._)

-It’s Monkey Business Time! (Version 1.5)
*/

There are the developers that feel the file should contain there version control and bio of the file. If you are using version control like Git or Team Foundation Server, then you shouldn’t need this. It is a bit like above, waste of space and data but at least it is somewhat useful.

Comments version control:

' method name: FooBar (included for the sake of redundancy)
' created: Feb 18, 2009 11:33PM
' Author: Johny
' Revisions: Sue (2/19/2009) - Lengthened monkey's arms
'            Johny (2/20/2014) - Solved drooling issue
'

A simple thing people do not understand is to comment in HTML it is only two dashes. I have seen some developers try to separate their whole code like break points with this. The example below will fail W3C Validation, which is then not good for you site.

Over usage:

<!--------------------------------------------------------------------New sections -------------------------------------------------------------------->

Another example of what developers do is comment everything, which I find slightly insecure as these comments are visible to the people view the sites source code unlike backend code like C#. I have seen things like this…

Security Risk:

<!-- will get injected with content by table Passwords_Table -->

So how can we make better comments? Well My preferences are simple but effective.

I have a key to how I do different titles for sections like in CSS:

/* == MAJOR SECTION HEADING ==*/

/* — Minor Section Heading —*/

I would make sure that I don’t over bloat my code with comments and name classes/ids relevant like in HTML:

< div>
<!-- Top Part -->
< div class="top_part">
< /div>

<!– Middle Part –>
< div class=”middle_part”>
< /div>

<!– BottomPart –>
< div class=”bottom_part”>
< /div>
< /div>
< /div>

A good source I found for valid HTML comments for the different html versions is at mozilla.

In ASP.NET, as mentioned before, you also have the ability to create a method summary. To do this you do the comment character 3 times above the method. This then automatically add the summary tag and all the parameter tags. Not only does this give a brief comment about the method, but when you use it in various other places it will have a tooltip with the information in. This then means you don’t have to hunt down what, why, when of the method you are about to use.

/// <summary>
/// This Method opens a door
/// </summary>
/// <param name="key"> key opens the door </param>
/// <param name="code"> code is the code for the door </param>
private void OpenDoor(string key, string code) {}

As I said before I believe in simple meaningful comments, instead of a paragraph. If you are doing any of the above fails, then I think you need to rethink your comments or maybe even your code. It is meant to be readable by any other developer, so the key feature is does it make sense.

I reached out to some fellow developers on my Google+ Network and they had the same idea.

Eric Fischer
Good code is nearly self-explainable. Name your variables that they describe what they are used for. If you write a lot of methods: a little explaination in form of a small JavaDoc above the method could be useful. Too much commenting reduces the readability. Use comments for lines of code in your method if they are complicated to read or to understand.
From https://plus.google.com/u/0/115759722116880665817

Here are all the other comments and thought on Programming Community and Web Development Community.

I would be very interested to know how you comment and what techniques you find work best for your coding language of choose. Comment below your thoughts.

 

MS Word special characters Regex

That pesky Microsoft! They have to be different and mess us developers around don’t they. Have you ever noticed that Microsoft Word’s symbols look a bit different or act a little odd? Well it’s because they are not the standard char characters. This can be a pain for Regex and other things. So how do you get them…

The reason they are so difficult is they use Windows-1252 character encoding set which are not represented in ASCII or ISO-8859-1. This is what just about everyone doesn’t do of course. These characters include:

  • … ellipsis
  • ‘smart’ “quotes”
  • en – dash and em — dash
  • dagger † and double dagger ‡

There are few more of course, but these are the most common few that come up. You can find more of Microsoft Word Windows-1252 character encoding here.

 

Symbol Encoding
single quotes and apostrophe \u2018\u2019\u201A
double quotes \u201C\u201D\u201E
ellipsis \u2026
dashes \u2013\u2014
circumflex \u02C6
open angle bracket \u2039
close angle bracket \u203A
spaces \u02DC\u00A0

 

Here is a pre-built method for JavaScript and C# to combat these.

 

JavaScript Clean String

var wordClean = function(text) {
var cleanStr = text;

// smart single quotes and apostrophe
cleanStr = cleanStr.replace(/[\u2018\u2019\u201A]/g, “\'”);

// smart double quotes
cleanStr = cleanStr.replace(/[\u201C\u201D\u201E]/g, “\””);

// ellipsis
cleanStr = cleanStr.replace(/\u2026/g, “…”);

// dashes
cleanStr = cleanStr.replace(/[\u2013\u2014]/g, “-“);

// circumflex
cleanStr = cleanStr.replace(/\u02C6/g, “^”);

// open angle bracket
cleanStr = cleanStr.replace(/\u2039/g, “<“);

// close angle bracket
cleanStr = cleanStr.replace(/\u203A/g, “>”);

// spaces
cleanStr = cleanStr.replace(/[\u02DC\u00A0]/g, ” “);

return cleanStr ;
}


C# Clean String

public string wordClean (string text){
var cleanStr  = text;

// smart single quotes and apostrophe
cleanStr  = Regex.Replace(s, “[\u2018\u2019\u201A]”, “‘”);

// smart double quotes
cleanStr  = Regex.Replace(s, “[\u201C\u201D\u201E]”, “\””);

// ellipsis
cleanStr  = Regex.Replace(s, “\u2026”, “…”);

// dashes
cleanStr  = Regex.Replace(s, “[\u2013\u2014]”, “-“);

// circumflex
cleanStr  = Regex.Replace(s, “\u02C6”, “^”);

// open angle bracket
cleanStr  = Regex.Replace(s, “\u2039”, “<“);

// close angle bracket
cleanStr  = Regex.Replace(s, “\u203A”, “>”);

// spaces
cleanStr  = Regex.Replace(s, “[\u02DC\u00A0]”, ” “);

return cleanStr ;
}


If you are doing some validation using Regex, here is also how you can check these characters.

JavaScript Regex

function containsWordChar(text) {
var contains;

switch (text) {

case (text.match(/^[\u2018\u2019\u201A]$/)):
contains += “single quotes and apostrophe, “;

case (text.match(/^[\u201C\u201D\u201E]$/)):
contains += “double quotes, “;

case (text.match(/^[\u2026]$/)):
contains += “ellipsis, “;

case (text.match(/^[\u2013\u2014]$/)):
contains += “dashes, “;

case (text.match(/^[\u02C6]$/)):
contains += “circumflex, “;

case (text.match(/^[\u2039]$/)):
contains += “open angle bracket, “;

case (text.match(/^[\u203A]$/)):
contains += “close angle bracket, “;

case (text.match(/^[\u02DC\u00A0]$/)):
contains += “spaces, “;

default:
contains += “double quotes”;

}

return contains;
}


C# Regex (MVC)

[RegularExpression("^[\u2018\u2019\u201A\u201C\u201D\u201E\u2026\u2013\u2014\u02C6\u2039\u203A\u02DC\u00A0]+$", ErrorMessage = "Your content contain some Microsoft Word Windows-1252 character encoding.")]


C# Regex

Public string containsWordChar(text) {
String contains;

switch (text) {

case (text.IsMatch(@”^[\u2018\u2019\u201A]$”)):
contains += “single quotes and apostrophe, “;

case (text.IsMatch(@”^[\u201C\u201D\u201E]$”)):
contains += “double quotes, “;

case (text.IsMatch(@”^[\u2026]$”)):
contains += “ellipsis, “;

case (text.IsMatch(@”^[\u2013\u2014]$”)):
contains += “dashes, “;

case (text.IsMatch(@”^[\u02C6]$”)):
contains += “circumflex, “;

case (text.IsMatch(@”^[\u2039]$”)):
contains += “open angle bracket, “;

case (text.IsMatch(@”^[\u203A]$”)):
contains += “close angle bracket, “;

case (text.IsMatch(@”^[\u02DC\u00A0]$”)):
contains += “spaces, “;

default:
contains += “double quotes”;

}

return contains;
}

 

Sticky Menu Bar code and example

This is a bit of a feature a lot of websites use and love, which is the Sticky Menu Bar. This could also be used for things like a cookie policy bar as well, but what ever the use it is a good feature. However I see some people add these with some terrible code and methods, because they don’t understand how it would work. I will explain my method and why I think it is better.

Although it is all done via JavaScript and JQuery, we will start with the HTML. This is sort of simple that you can have what ever you like, but you need the navigation wrapped in a container. For my example I have the HTML5 ‘nav’ element as my container and then the actual navigation as an Unordered List.

<nav >
<ul >


<!--ul>

This will be explained further on, but the reason for this is so your content does jump.

For the CSS it is pretty much just standard styling more for the benefit of the visual of the navigation, not for the functionality. The ‘nav’ has colour, the ‘ul’ removes the bullet points and then the final styling to bring the link containers inline.

nav {
background-color: #0073AA;
}

ul {
list-style: none;
}

li {
display: inline-block;
color: white;
padding: 10px 0;
}

Then is the JavaScript/JQuery that I have done in a prototype, so that it can be added once then used however many times. The basics to set this up is the initialisation method and the defaults object added to the prototype.

The ‘defaults’ contain 3 parameters that are the ‘itemClass’ the class given to the navigation controller for my example the ‘ul’, the ‘itemParent’ the class given to the parent of the navigation the ‘nav’ and finally the ‘stickyClass’ which is the class given to the item once it has stuck to the top of the screen. This is so if you want to style it different once it has stuck. The defaults, mean if you don’t want your own classes then there are back up classes instead.

StickyBar.prototype = {
defaults: {
itemClass: "sticky_item",
itemParent: "sticky_parent",
stickyClass: "sticky_class"
},
init: function() {
}
}

You also have a ‘init’ method attached. This is where we action the method to run the functionally of the navigation. This is below and starts off with putting the object into a scope called ‘base’. This give the ‘this’ the scope of the method.

We then have the on scroll attribute of JQuery to read each time the user scrolls, you can tell where they are. Next I have put in the ‘each’ attribute so if you have multiple sticky bars with the same class, they are all picked up and checked. You can have multiple sticky bars, as the position of these are done in the CSS, so as long as you have a different class on each for their direction then you can have more than one.

Within here is the real thinking. With the if command we check if the scroll position of the window is further down the page then the navigation. This is the reason we have the navigation container, as once you have stuck the navigation to the page it moves with the page and therefore the window will never scroll back over it. With the container you can stick the content inside and then use the container as the reference point.

If it is to be stuck then we add some inline CSS to position fix it to the window and add the sticky class to the navigation. If it is not to be stuck then it does the opposite. There is also a bit of functionality to give the parent element some height, because once you stick the navigation it is not relative on the page so all the content will shift up. Instead we add the height on as a placeholder. I have added it here, so that if your item change for instance a drop down menu or you also have multiple stick bars, then it works for all.

startScroll: function() {
var base = this;
$(window).scroll(function() {
$(base.itemClass).each(function() {
if ($(window).scrollTop() >= $(this).parent(base.itemParent).offset().top) {
$(this).css({
'position': 'fixed'
})
$(this).addClass("stickyClass");
$(this).parent(base.itemParent).css({
'height': $(this).height()
});
} else {
$(this).css({
'position': 'relative'
});
$(this).removeClass("stickyClass");
$(this).parent(base.itemParent).css({
'height':'auto'
});
}
})
})
}

Once last thing we need to do is add it to the ‘init’ method and it is complete. Please also notice the object StickyBar that sets the each sticky bar and the IFFY around everything to run this on load.

All you then need to do to initialize each instance is call the object and add in the optional parameters, which again I have put in an IFFY to have it load straight away.

//New Sticky
(function() {
var stickyBar = new StickyBar({
itemClass: '.nav_bar',
itemParent: '.nav_bar_parent',
stickyClass: 'nav_bar_stuck'
});
})();

Please see the full code and an example on CodePen

How to detect JQuery UI collision position

Some may not know, but you can use the JQuery method position to pass an object with a lot of functionality. This properties of the position object can control where the item sits in the HTML, plus also the collision. This is where it collides with another DOM or the window of the page and then reacts to it. The question is how do you know what it hits and how it reacts.

First lets talk about the default functionality you can use. There are 6 properties that come with this object and they can all help control what happens with the element you are controlling.


my: (TypeOf String , Default ‘center’)

Defines which position on the element being positioned to align with the target element: “horizontal vertical” alignment. You can use any of these values ‘right’, ‘left’, ‘top’, ‘bottom’ or the default ‘center’. These act use like the position attribute in CSS. You can also use two the same time to affect the vertical and horizontal elements of the DOM item. Additionally you can add pixels to this as well to add padding, for example ‘right+20 top+10’. This is handy if you are doing a tool tip that has a speech arrow on the side. You don’t want the item to be flush, so this can give it padding on the side.


at: (TypeOf String , Default ‘center’)

Defines which position on the target element to align the positioned element against: “horizontal vertical” alignment. The values for this properties is the same as above,  ‘right’, ‘left’, ‘top’, ‘bottom’ or the default ‘center’. Which you can also use in tandem together with pixels added on.


of: (TypeOf Selector, Element, jQuery or Event , Default null)

You can pass into this an element to position next to. This can work well for the tool tip example as you can the position it right next to the element you wish the tool tip to be on. If you provide an elements ID or Class that there is multiple of, it will choose the first it comes across to affect.


collision: (TypeOf String, Default ‘flip’)

When the element hits the boundaries of the window, or the element given in the below, it will then react according to the value put in. These are the accepted values “flip”, “fit”, “fit flip”, “fit none”.


within: (TypeOf String, Default window)

Pass into this the ID or Class of the containing boundaries. If you want the selected element to collide with the boundaries of it containing element instead of the window.


using: (TypeOf function(), Default null)

When specified, the actual property setting is delegated to this callback. You will get given two parameters, the first is a hash of top and left values for the position. The second is the information about the position and dimension of the elements, plus their relative positions.

For more information about these parameters, you can read more on the JQuery UI.


But How…

Now for how you detect the position of the element on it collision. I have create the example below to add a class to tell which side it is on.

The second parameter ‘info’ gives you the information on which side the element is, you need just query the parameters properties ‘vertical’ and ‘horizontal’ to find out. However I also found that they were opposite for my tool tip. I think because the element hung down it was detecting the top was in the top and when it switched the top was in the bottom. Therefore it seemed on the opposite sides. You will have to play about to see which yours is.

 
$( "#tooltip" ).position({

my: "left top",
at: "right top",
of: context,
collision: "flip",
within: 'int-container',
using: function(obj, info){

//if top side add class item_top and remove class item_bottom, then visa versa
var item_top = (info.vertical!= "top"? "top" : "bottom");
$(this).addClass("item_" +  item_top);
$(this).removeClass("item_" + (item_top == "top"? "bottom" : "top"));

//if left side add class item_left and remove class item_right, then visa versa
var item_side = (info.horizontal != "left"? "left" : "right");
$(this).addClass("tooltip_" + tooltip_side);
$(this).removeClass("tooltip_" + (tooltip_side == "left"? "right" : "left"));

}});