Thursday, December 31, 2015

Lambda, Lambda, Lambda - How To Use a Lambda Expression

Many programming languages use lambda expressions: Python, Ruby, C#, JavaScript, and GO to name a few modern examples. Lambdas can be extremely expressive and save several lines of code when you just need a function without the need for reuse. I and others use Lambdas to create greater readability. On the flip side, if you don't understand how they work l, the syntax can be confusing and the code will be impossible to understand. My goal in this post is to help you understand what Lambdas are all about so you can understand them next time you see one and even add Lambdas to your tool set to improve your ability to be more expressive.


Here are some examples of adding 1 to x using Lambdas in various languages:

Python:
lambda x: x + 1;

Ruby:
lambda { |x| x + 1 }

C#:
x => x + 1;

js (ES6):
x => x + 1;

GO and js (<ES6):
This is where it gets interesting. These languages treat functions as first class and so a function can be passed as an argument to a function, which is really the point of lambda. This works the same way in PHP too. The syntax really doesn't matter in terms of understanding what a lambda is. Syntax is just to make things cleaner and gives you a way to declare the Lambda inline.

Let me explain by example:


Lets say we have a js function that expects a function:


function foo(bar){
    return bar();
}


This is a root form of the lambda.


In a strongly typed language like C#, it will look something like this:


int Foo(Func<int> bar)
{
    return bar():
}

Notice how the input is a Func? A Func is an anonymous method that returns a value (specified by the type in angled brackets <int>. There's also an Action which expects void.

Here is a more useful example:


public int OperateOnX(Func<int, int> expression)
{
    return expression(this._x);
}

and we call the method like this:


var a = intance.OperateOnX(x => x+1);
//or
var b = instance.OperateOnX((x) => x*x);


or if we use the C# Linq library:


var c = list.Where(x => x > 3);


In this example, the Func returns int and expects int as the first argument. Mulitple arguments can be specified as Func<int, int, string> (Action<int> expects one int argument, and Action<int, string> expects an int and a string argument):

var b = instance.OperateOnXY((x, y) => x*y); //Func<long, int, int>


The Where extension method iterates over the list and passes each item to your Lambda and returns items for which the expressions evaluates to true. The Lambda Expression is a filter.

For more advanced operations, you can encapsulate like this:



var c = list.Select(x => 
{
    var y = x.Name;
    if(y == "")
    {
        x.Name = "Phil";
    }
    return x;
});


Lambdas can take multiple arguments, after all they should behave just like a regular method or function. In fact you can pass a method to a Linq Where like this:


var d = list.Where(Filters.GreatFilter);


so long as GreatFilter matches the expected delegate type - its signature should look like this:


bool GreatFilter(ListItem item);


Since Where is an extension method in C# Linq (it Extends IEnumerable<T>) the input argument to the generic function will be T, or in this case whatever type "list" items are.


Hopefully, you understand what Lambdas are all about by now, if not feel free to ask and I will do my best to explain a bit further.


Wednesday, December 30, 2015

Extension Methods in C#

If you've ever used Extension methods in C# but don't really understand what they are about this post will hopefully help you understand them a bit and even how to create your own. If you haven't used them this should serve as a good foray into expanding your toolset.



Here's what I've learned:

Make a static class and add a static method (this is the extension method).

The extension method takes in the object it is extending as the first argument in the following format:

public static class BakerExtensions
{
    public static Cake MakeCake(this Baker baker)
    {
        //make that cake
    }
}

If we have a baker instance we would call the extension method as if it belonged to the Baker class.

Baker baker = new Baker();
Cake mmmCake = baker.MakeCake();

I recommend keeping your extension classes at a 1:1 ratio to the classes they are extending. If you have a Baker and a CandleStickMaker you should have a BakerExtensions and a CandleStickMakerExtensions class. This is not required, but it will help with organization.

You may also want to namespace your extension classes the same as the classes they extend, but if you do remember that the extensions will automatically be brought in with the class if it is in the same namespace. You could go with <original namespace>.Extensions if you want more control over when to bring them in and when not to, but it may end up adding confusion in the end.

So why on earth would you want to use extension methods? Why not create subclasses and just add the methods to those?

Ok, so let's say you have some existing code with the Baker class all over the place. You might have some subclasses already and you don't want to change the base class OR you want to add functionality to built-in types like string or int.

public static class StringExtensions
{
    public static string Shuffle(this string inputString)
    {
         //shuffle that string
    }
}


var shuffled = "something".Shuffle();

//shuffled  == "emogsinht"

It's a pretty neat way to keep in line with the Open/Closed Principle if you don't need to access instance members.

Word of caution: be careful about side effects when it comes to extensions. Side effects are a code smell in any case. Thogh it may be tempting to have them in extension methods, you should treat them just like you would if they we a normal class method.

There are a couple of drawbacks - You wouldn't get access to internal members of the class; and your extension methods won't be called if they have the same name and signature of a class method.

Here's an msdn article on the topic for more detail: https://msdn.microsoft.com/en-us/library/bb383977.aspx

Tuesday, December 29, 2015

How To: Run a Program in Administrator Mode

Often I need to run a program in administrator mode when using Windows. There are several ways to run a program in administrator mode on Windows 7. The way I've found to be the mode efficient is to pin it to the taskbar and set that pinned shortcut to always run as administrator. When you do this, it's a 2-click process - one click to launch it and another to accept the dialog.

Here's how to do that once you've pinned the program, this example is using Visual Studio 2015 since often it needs to run in admin mode to debug against local IIS.

Right-click any shortcut and click Properties. Here I am right-clicking the shortcut that is in the pinned program in the Taskbar. You can access these properties from any shortcut - on the desktop, or the start menu/screen to name a few.
In the Properties dialog, click Advanced*.
This dialog should appear and all you have to do is check the box and click "ok" and "ok" again and you are all set to run in admin every time.
*If you are right-clicking an icon for an exe you will find run as admin in the Compatibility tab of the Properties dialog.

Monday, December 28, 2015

Leadership: Gateway to a new YOU!

Lately, I've spent a lot of time reading up on leadership. I've been discussing the topic at length with friends, family, mentors and colleagues as well. It seems there is a few common threads that run through it all. And if you want to really be successful and happy in your life, you'd be better off to get this right.


Live by a core value system. Communicate with empathy. Build trust and by doing do so grow influence. Work together with others and delegate to maximize results.

Friday, December 18, 2015

Analyze, Trust, or Buy-In?


Do I really have to question everything? So I'm waiting at a train depot and of course there is a sign that advertises how much greener it is to ride the train than to drive a car on a daily commute. I'm going over-analytically submit a usual "it depends" sort of answer.


What might it depend on? Well...how much energy and what sources of energy are consumed with daily operations of the rail system? What is the waste of maintaining and building tracks vs roads? What is the total waste of producing and maintaining trains vs autos? What distance are you travelling? What additional energy and waste do you consume in your commute?


If we really want to prove the statement, we would have to analyze the data. Or we can just trust that the train company did this. Or perhaps some trusted analysis entity can verify the facts for us. I guess if I want to verify it I would either have to find a trusted authority (who knows if they really did a proper analysis), find data and do my own analysis (can I trust the data?), or just buy in.

Wednesday, December 16, 2015

The Importance of Understanding Expectations

A recent acquisition of a set of new chairs shed some light on how a solution can meet requirements while at the same time fall short of expectations. This caused that sudden realization to solidify in my gray matter. The upshot is that meeting requirements is a science while meeting expectations is an art. A friend, mentor and colleague has repeated so many times that software development is as much art as it is science - the majority of the chorus being sung in regards to choices of patterns and styles when coding. I want to come back to that though, but for now let me share a bit of the story of the chairs.


We were in the process of getting a new office space and one thing that came into play was the choice of new chairs for a communal/meeting/lounging area. The idea was that the chairs could be circled up to facilitate discussions. The first option had feet with pads, a bucket design, and a little desk top attached. Well, it would have been nice to have wheels and if the desk was removable so that it wouldn't be in the way if not needed. This feedback was given and the next sample chair that arrived with casters and a removable tray.


A few days later a sample arrived that fit those requirements. At first sight was a bulky eyesore of a white leather chair, with dirty handprints all over the back to boot. Then I rolled it around and the casters felt as if they would fall off. The removable tray was on the left - only on the left. It was nearly useless as it was genuinely too far away for comfort given the size of the chair and it was generally too small to support a laptop comfortably.


What is the lesson here? You get what you ask for! But seriously, think about how those requirements created solutioning constraints. What we needed was a modular place to gather comfortably and talk face-to-face for short durations. We needed the space to be able to double as a viewing space for presenting ideas, plans, apps, whatever. This is the art - understand the users needs, environment, and their expectations. Once you understand the users in this way, then you should have a better understanding of what solution to provide.


Now lets return to the code for a minute. Choosing design and style of architecture and code is an art. In order to deliver to the needs and the expectations, we must first understand the users of the code and deployment. Sometimes, you are the user and sometimes other developers. Ops teams could be users. What goals will users have in the future? There will be a need to change the code - its code of course so it is always changeable. The code will have to be changed in ways so that unexpected things do not happen. Other developers will want to understand the code, and without a whole lot of pain. You and others may want to be able to write unit tests against the code, or other forms of automated tests. Sure you could obfuscate everything and keep the code as compact as possible, keep it super-efficient, keep it obscure so that only the mightiest of developers can understand it. var a=g();a++;if((b===x&&y!==l)||(z|1)&&((((((m())+5/c)&3)|(l-5)))){return g===h?(6*f)>=9?'v'::''.....
but why would you put future you through that? It's like looking at a Jackson Pollack piece, except that someone will have to change it someday. Imagine what kind of mess you'd end up with if over time several other painters of varying skill level changed one of those paintings...it would probably end up a muddy looking mess before you know it! Instead its a nice clean mess.


Sometimes we inherit a Pollack. And sometimes we are asked to change a Pollack. Oh where to begin! In this way, the art of software can be lost in the science. The art of software is more like a mural on an endless wall...you can add on without destroying the original, especially if the original lends itself to extension and to change. Picture a mural on a wall that begins to the left and continues endlessly to the right. If the first part has lines that lead the eye to the right, we have something to build on. If it has white-space we can add to it by filling in the space. As our mural is continued over time to grow to the right, we may decide to change a part somewhere to the left of the current one. Themes can be continued, but maybe some offensive part will be changed or something later causes an earlier work to be inadequate and that part would need to be revitalized lest it bring the whole down.


When applied to software, we must think of the art of it as well as the science and leave our designs and styles open to change and before that to be understood.

Tuesday, December 8, 2015

Javascript Constructor Pattern to Ensure new is Called

Here is a pattern that will ensure "new" is called when defining an object constructor. When calling a JavaScript constructor function, if "new" is not used, then the variable being assigned will be undefined unless the constructor function returns something else.


function Griffen(name){
  this.name = name;
  if(this instanceof Griffen){
    return;
  }
  return new Griffen(name)
}
console.log(Griffen("Pete"));

Wednesday, December 2, 2015

JavaScript Constructors

I learned a lot about creation patterns from this http://shichuan.github.io/javascript-patterns/ today. I was even inspired to do my own experiments on some creation patterns not shown there.

JS Bin on jsbin.com
go there