Potential React Bloatiness

React can become bloaty. Or for that matter, every project that uses javascript (e.g. npm/nodejs projects).

I recently wanted to add a search feature to a website. The natural thing is to want to debounce the user’s input before passing the search string to the server. So, obviously, one doesn’t have to implement a debounce function – you can take it from lodash. But then the question arises – how would one integrate that debouncing into a react project? Or worse yet, an asp.net core + react + redux + typescript project?

Well, here’s a nice little SO thread:
https://stackoverflow.com/questions/23123138/perform-debounce-in-react-js

It’s top answer has almost 900 upvotes, it spans tons of text, with a yearly history. It also suggests using three different code sources to get the thing to work. That’s bananas!

So how did I go about solving this?

Actually, a far less popular SO thread also caught my eye: https://stackoverflow.com/questions/43709356/debounce-textarea-input-with-react-redux

This was much much better! It’s a classic SO answer – no history lesson needed, no need to take a ton of dependencies. It even has an inline working code sample – superb!

The solution is actually very simple – the textarea’s callback should do two things – update the local text, and invoke the debounce function. Not a single dependecy added. Well, almost, since the debounce function is taken from lodash. But I have to admit – taking a lodash dependecy when just single function is required? Why not just take a debounce function from somewhere?

Well, that’s what I did. I took one from here, and adjusted it to compile: https://gist.github.com/ca0v/73a31f57b397606c9813472f7493a940

My final code looked like this:

export const debounce = <T extends (...args: any[]) => any>(
    callback: T,
    waitFor: number
) => {
    let theTimeout: any = 0;
    return (...args: Parameters<T>): ReturnType<T> => {
        let result: any;
        clearTimeout(theTimeout);
        theTimeout = setTimeout(() => {
            result = callback(...args);
        }, waitFor);
        return result;
    };
};

To summarize, imo, there’s a big difference between taking a single function to taking four dependencies. It’s one of those sad cases where SO isn’t accurate, or optimized in any way. Something to keep in mind when browsing SO. 🙂

Guiding junior developers

Haven’t written in this blog in quite some time. I hope I’ve learned some things since then. 🙂

Let’s dive right in to some thoughts about guiding junior developers. Perhaps in another post I’ll exand on my recent career years, and personal path.


I love guiding developers, and a recent guiding session had left me with some ideas.
A “fresh out of the uni” graduate came to me for advice, on a not very urgent matter. He was seeing some things that did not make sense to him. To be more specific – some speed test he was running was giving varying results, in a manner he did not expect.

After guiding him, I was left with some guidelines as to how I’d prefer to instruct:

  1. Do not flat out provide a solution
  2. Solve the issue together
  3. Encourage and teach. The technical know-how is important, but it is much more important for the junior developer to learn problem solving tools, rather than a problem’s solution.

It seemed to me that the developer did not have to proper tools, or framework, to handle the issue he was tackling.

So here are some steps I use with technical challenges:

  1. Open a brand new tab in your favorite text editor
  2. Write a single sentence describing the problem
  3. Dump everything known about the problem
  4. Write down 2-3 ideas on how to solve the problem
  5. Compare the ideas on several parameters:
  • likelyhood to solve the issue
  • time to test/implement
  • consider any other parameter, e.g.: whether this solution would be a good fix, or relevant only as a temporary solution

If complexity is high – it may be useful to open a spreadsheet and compare the ideas in a table.

Once we sat together and compared the ideas and their parameters, the suitable steps were clear.

I guess that my personal discovery is that problem solving shold be methodical, rather than erratic. I think that both in code, in work, and in problem solving it is very fun to be erratic, scattered, and asosciative. For light-weight problems it is perfectly nice to go with you gut, and play while working. For the heavy duty issues, the kind that may take way too long to solve, it is best to take a cool headedness approach. It may be a little less playful, but it has the benefits of being methodcal and organized.


A note about the “hardness” of a software bug.

I recall reading on an internet thread some years ago someone describing a bug as hard because it required multiple breakpoints. But I thought that if the issue you are trying to solve is solvable within an IDE and breakpoints then the issue is not that complex – put in the time and you’ll find it.

The more challenging issues I’ve seen were inherently hard to debug or solve, e.g.:

  • Hard to reproduce
  • Concurrent issues – where one cannot just set breakpoints to debug the issue
  • Distributed issues
  • Time related issues
  • Shader code – things which may or may not be visible, but are definitely not unit testable

Functional Decorator (C#)

Well, it’s been a while since I’ve written. Let’s get to it! 🙂

For quite some time now I’ve been writing in C# and javascript. The functional nature of javascript has put me into a functional programming mindset without me even being aware of it. I tend to think that C# is also very functional, given anonymous methods and lambda expressions.

Today I talked with the guys in the office about the decorator pattern and I had some functional insights.

So basically the decorator pattern is a way to add functionality to an existing class without subclassing it. Instead, the pattern instructs us to use composition. This is preferable to inheritance in the case that you have several optional extensions to a given functionality. If you were to use subclassing you’d have an exponential number of classes, which is obviously undesirable.

Concrete examples are of course available in wikipedia:
http://en.wikipedia.org/wiki/Decorator_pattern

But I’d like to discuss my functional approach to the same problem:
instead of class composition, we could use functional composition. This can be easily determined in a list of functions. The benefits are clear – much shorter code.

Code Snippet
Func<string, string> windowFunction = str => str + "window drawing"; // the window drawing
Func<string, string> vScrollbar = str => str + ", v scrollbar"; // the vertical scrollbar
Func<string, string> hScrollbar = str => str + ", h scrollbar"; // the horizontal scrollbar

List<Func<string, string>> functions = new List<Func<string, string>> {windowFunction, vScrollbar, hScrollbar};

string s = null;
foreach (Func<string, string> function in functions)
{
    s = function(s);
}

Console.WriteLine(s);

I’ve also given some thought to the Window example in wikipedia, and came up with an intermediate solution (which includes classes, but skips composing them):

Code Snippet
public class DrawingContext
{
    public string Content;
}

public abstract class AbstractWindow
{
    public abstract void Draw(DrawingContext drawingContext, AbstractWindow abstractWindow);
}

public class Window : AbstractWindow
{
    public override void Draw(DrawingContext drawingContext, AbstractWindow abstractWindow)
    {
        drawingContext.Content = "window";
    }
}

public class ScrollbarWindow : AbstractWindow
{
    public override void Draw(DrawingContext drawingContext, AbstractWindow abstractWindow)
    {
        drawingContext.Content += " scrollbar";
    }
}

public class MainClass
{
    public static void WindowExample()
    {
        Window window = new Window();
        ScrollbarWindow scrollbarWindow = new ScrollbarWindow();
        List<AbstractWindow> list = new List<AbstractWindow> { window, scrollbarWindow };

        DrawingContext drawingContext = new DrawingContext();

        AbstractWindow prevWindow = null;
        foreach (AbstractWindow abstractWindow in list)
        {
            abstractWindow.Draw(drawingContext, prevWindow);
            prevWindow = abstractWindow;
        }

        Console.WriteLine(drawingContext.Content);
    }
}

Note: depending on the implementation, it is possible that the ScrollbarWindow’s Draw method may require something from Window. That’s why it’s added as a parameter to the Draw method. It is a way of skipping over the pattern’s constructor injection.

Hope you like it. 🙂

Adding SSL support to an ASP.Net website

I had to add SSL support for an asp.net website. It means two things, when developing:
1. Install a self signed certificate. That takes a couple of seconds with IIS7.
2. Prefix all absolute paths with “https” (instead “http”).

A few other circumstances were at play:
1. The site is quite complex when it comes to URLs (it uses absolute paths for CDN and for a plethora of links from external sources).
2. I had to do it FAST.

It was a scary task, until I thought of a compromise, in the form of a not-so-perfect solution – replacing all occurrences of “http:” with “https:” AFTER the response is complete. It’s a little blasphemous and some may say dirty, but is solves most of the problem, most of the time, and very quickly. Definitely not the ideal solution though.

I did not go for the “safer” form of “http://&#8221; to “https://&#8221; since the slashes may be escaped in a javascript string like so: “http:\/\/www.google.com”. This solution also leaves out encoded URLs, which would require another replace – “http%3A” -> “https%3A”.

Since the site is hosted in Amazon and uses a load balancer (LB), the actual certificate was only installed on the LB. The LB gets the request in SSL, but asks for the page from the web servers in standard http. In order to detect these and support them I’ve queried the appropriate fields in the request. I also added support to a direct SSL request, which is comfortable for debugging purposes. I used an extension method for reusability and niceability.

One thing I’m not certain about is the performance of converting a byte array to a string in order to perform the replace operation. I found a matching question in stackoverflow, but it wasn’t answered. Implementing the KMP algorithm for a byte array crossed my mind, and then I gave it up – I had to do it FAST.

The filter:

Code Snippet
using System.IO;
using System.Text;

namespace TechTaunt
{
    /// <summary>
    /// this filter class replaces all occurences of the string "http:" with "https:".
    /// as an HttpResponse filter this can add support for https, though with some margin for error.
    /// </summary>
    public class HttpsFilter : Stream
    {
        private readonly Stream _sink;

        public HttpsFilter(Stream sink)
        {
            _sink = sink;
        }

        // The following members of Stream must be overriden.
        public override bool CanRead
        {
            get { return true; }
        }

        public override bool CanSeek
        {
            get { return true; }
        }

        public override bool CanWrite
        {
            get { return true; }
        }

        public override long Length
        {
            get { return 0; }
        }

        public override long Position { get; set; }

        public override long Seek(long offset, SeekOrigin direction)
        {
            return _sink.Seek(offset, direction);
        }

        public override void SetLength(long length)
        {
            _sink.SetLength(length);
        }

        public override void Close()
        {
            _sink.Close();
        }

        public override void Flush()
        {
            _sink.Flush();
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            return _sink.Read(buffer, offset, count);
        }

        // The Write method actually does the filtering.
        public override void Write(byte[] buffer, int offset, int count)
        {
            var sb = new StringBuilder(Encoding.UTF8.GetString(buffer));
            sb.Replace("http:", "https:");

            var buffer2 = Encoding.UTF8.GetBytes(sb.ToString());
            _sink.Write(buffer2, 0, buffer2.Length);
        }
    }
}

The extension method:

Code Snippet
        /// <summary>
        /// true if this request is to ssl, or if it was forwarded from ssl. this is useful when a load balancer is in place
        /// </summary>
        public static bool IsSsl(this HttpRequest request)
        {
            return (request.IsSecureConnection ||
                    (request.ServerVariables["HTTP_X_FORWARDED_PROTO"] == "https" &&
                        request.ServerVariables["HTTP_X_FORWARDED_PORT"] == "443"));
        }

Adding the filter (in global.asax):

Code Snippet
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            if (Request.IsSsl())
                Response.Filter = new HttpsFilter(Response.Filter);
        }

Javascript Debugging

Here’s an issue for you:
I got a client side (i.e javascript) bug report. The bug occurred sometimes on a page load, but not always. I wanted like to recreate the bug, but… how? Well, being able to recognize in javascript when the bug occured (or more importantly – where it doesn’t occur) I was able to write some javascript code that refreshes the page only when the bug doesn’t occur. This enabled me to successfully recreate the bug without having to press F5 for an unknown number of times.

Distributed Mutex/Locking

Web servers – we use a bunch of them, and it makes sense. A lot of users means you need a lot of servers, in one word – scalability. But what about system wide processes? The scenario is simple and familiar: at a certain time or event you want something to occur, but only once in the system. You would also probably like to avoid the simple solutions that infect your system with a single point of failure. How would you go about implementing that?
There are two approaches:
1. Leader election.
2. Distributed mutex.

Specifically in the environment I’m working on nowadays we add and remove servers dynamically (cyclically). It means that no server remains alive for a long time. I preferred not to use leader election since I know for certain that every leader will be shut down in a matter of a day or so.

What about a distributed mutex? Well, I found this post (http://bluxte.net/musings/2009/10/28/simple-distributed-lock-memcached), that basically says you can use the memcached “add” operation to implement a distributed lock. The “add” operation is atomic, and only returns “true” if the key does not exist. I liked the idea since I had already written code utilizing memcached.

But wait, memcached uses an LRU mechanism, which means your lock may disappear at times – not a very desirable feature for a mutex. Fortunately our system is using membase, which is like memcached with disk persistence (a no-sql db if you will). Using membase as the provider for the mutex makes the solution whole, and is in our production environment. 🙂

Querystring to JSON

Here’s some javascript to convert a querystring to json and vice versa.

Motivation:

  • Querystring to json – quite obviously – parse the url.
  • Json to querystring – useful when building a url (when redirecting the user or reporting to google analytics via fake pageviews)

Some notes:

  • I intentionally avoided using jQuery for portability reasons.
  • In order to run the example you’ll have to add querystring values and look at the console (e.g Firebug)
  • I assumed a flat json object, like an average querystring. This function will not work for nested json objects (and though it’s possible to implement it’d require a different solution).

 

Code Snippet
<html>
<script type='text/javascript'>
util = {
    qsToObject: function (qs) {
        var o = {};
        qs.replace(
            new RegExp("([^?=&]+)(=([^&]*))?", "g"),
            function ($0, $1, $2, $3) { o[$1] = $3; }
            );
        return o;
    },

    objectToQs: function (o) {
        var str = [];
        for (var k in o)
            str.push(k + "=" + o[k]);
        return str.join("&");
    }
}

var qsAsObject = util.qsToObject(window.location.search)
var objectAsQs = util.objectToQs(qsAsObject);
console.log(qsAsObject);
console.log(objectAsQs);
</script>
</html>

Autohotkey Scripts

Autohotkey is awesome. I love it because it’s scriptable, making it bend to my will. Not having to touch the mouse (or saving some keystrokes) on common tasks is very stisfying with Autohotkey. Here are my concoctions:

; ctrl+alt+c -> opens c:\

^!c:: Run c:\

; winkey+z -> opens notepad (extremely comfortable, since these two keys are so close, and notepad is so lightweight and useful)

#z::Run Notepad

; winkey+s -> this is amusing – when I want to perform a select command just to get the columns and a few rows I type the table’s name hit winkey+s – and I’m done 🙂

#s::

Send, {Home}SELECT * FROM {End} LIMIT 15

return

; flushing the cache in membase, on my station (probably not useful for most people, but a nice examle on how to automate the basic telnet that comes with windows)

#q::

Send, {LWINDOWN}r{LWINUP}

Send, telnet{SPACE}localhost{SPACE}11211{ENTER}

WinWait, Telnet localhost,

IfWinNotActive, Telnet localhost, , WinActivate, Telnet localhost,

WinWaitActive, Telnet localhost,

Send, flush{SHIFTDOWN}-{SHIFTUP}all{ENTER}quit{ENTER}

return

; ctrl+alt+f -> takes the currently focused window and the previously focused window and displays them side by side, a funky idea indeed (only in windows7, and assuming the windows are not maximized)

^!f::

Send, {LWINDOWN}{Left}{LWINUP}

Sleep, 50

Send, {ALTDOWN}{TAB}{ALTUP}

Sleep, 50

Send, {LWINDOWN}{Right}{LWINUP}

return

Factory pattern with reflection (C#)

Today I thought about implementing the factory pattern on a base class with five derived classes. I started with a basic switch-case statement but after a few lines I noticed the redundancy: case “x” instantiate X, case “y” instantiate Y, etc. I wondered what it would look like done with reflection and here’s the result (in a simplified example):

Code Snippet
public interface Shape
{
    void Draw();
}

public class Square : Shape
{
    public void Draw()
    {
        Console.WriteLine(" _ \n|_|");
    }
}

public class Circle : Shape
{
    public void Draw()
    {
        Console.WriteLine("O");
    }
}

public static class ShapeFactory
{
    public static Shape GetShape(string shapeName)
    {
        Assembly currentAssembly = Assembly.GetExecutingAssembly();
        var currentType = currentAssembly.GetTypes().SingleOrDefault(t => t.Name == shapeName);
        return (Shape)Activator.CreateInstance(currentType);
    }
}

There are a two advantages in this approach:
1. The code is shorter.
2. The code doesn’t require a change even if we add new classes that derive shape.