Tuesday, September 17, 2013

Javascript Named Function Expressions

BLUF: unless you are working in a controlled environment (intranet) where supported browsers only expose the identity of Named Function Expressions to the inner scope of the function (for recursive calls) they should be avoided.

In reading Test Driven Javascript Development there was discussion around using named functions to improve debugging. To provide some context lets look at this example.
Which produces the following stack trace

Those anonymous functions are hard to track down.

If we use named function expressions instead, then we can improve this stack trace.






Only problem is now we have to deal with browser quirks associated with named function expressions.

Here are a couple of great reads on the topic. 1, 2

Ideally the name would only be available to the inner scope (for the purpose of calling itself recursively) and then the rest of the issues would go away. Until then the issues outweigh the benefits. Fortunately Function Declarations will give us the same debugging benefit and won't create a new function every call.

This is hard to follow, though not significantly harder to read than before. To fix that I would recommend using promises (off topic).

The biggest issue is actually not apparent in the example, and that is that the scope context has changed. While our closure used to have access to parameters of our parent function,  it no longer does (in other words, Third could access variables from First and Second.

The simplest recommendation - and that from the books author, is to use a function declaration inside the closure.

Another option albeit off topic is to pass those variables into the function making them more explicit. Again this is where promises can help as each function can add / modify the model. (Or return different objects, etc.)



In summary, unless you are working in a controlled environment (intranet) where supported browsers only expose the identity of Named Function Expressions to the inner scope of the function (for recursive calls) they should be avoided.  

Javascript Function Constructors

BLUF: using Function constructors gives you greater control of the scope context and enables you to create dynamic functions but should be reserved for optimizations only as they are unintuitive to most developers and will rarely be worth it. 

In  reading Test Driven Javascript Development I discovered that you can create functions using the Function constructor.

This is in contrast to Function Declarations.

and Function expressions
So for an example, notice the Function below (log is just a supporting function)
Notice:

  1. I had to pass log in by reference. We are used to this being added the the scope context automatically and in the case of Function that isn't the case.  
  2. The last string argument is the function body. 
  3. The first string argument contains multiple parameters separated by commas
  4. You can also pass in as separate arguments as shown by p4. 
I expect that this would rarely be used as it adds complexity and instead should be considered a tool for optimization because you have greater control over scope context / closure. 

It also could be used to dynamically build functions but IMO most of the time you will be able to achieve this with normal syntax and so this should be reserved for improving performance. 

Sunday, September 30, 2012

SQL Table for Work Days

I was recently working on some reports using SQL and SSRS to find the velocity of my team. I found that the standard DATEDIFF(d, start, end) which includes weekends just wasn’t going to cut it.

So… I created my own table…

 

   1:  DECLARE @Result TABLE (CalendarDate DATETIME, WorkDay BIT)
   2:   DECLARE @startDate DATE = '2012-1-1'
   3:   DECLARE @endDate DATE = '2015-12-31'
   4:   Declare @CurrentDate datetime
   5:   DECLARE @workday BIT 
   6:    Set @CurrentDate=DATEADD(day, -1,@StartDate)
   7:    While @CurrentDate<=@EndDate
   8:    Begin
   9:      Select @CurrentDate= DateAdd(dd,1,@CurrentDate)
  10:      SELECT @workday = CASE WHEN datename(dw,@CurrentDate) IN('Saturday','Sunday') THEN 0 ELSE 1 END;
  11:      Insert Into @Result Values (@CurrentDate, @workday)
  12:    End
  13:    
  14:    SELECT *
  15:    INTO mwg.Calendar
  16:    FROM @result
  17:    
  18:  SELECT * FROM mwg.Calendar



 


And then I created my own DIFF function


   1:  CREATE FUNCTION [mwg].[WorkdaysDiff](@date1 DateTime, @date2 DATeTIme) RETURNS INT 
   2:  AS 
   3:   
   4:  BEGIN 
   5:  DECLARE @result INT;
   6:  --DECLARE @date1 DATE = '2012-09-24';
   7:  --DECLARE @date2 DATE = '2012-10-12';
   8:   
   9:  SELECT @result = COALESCE(SUM(CASE WHEN WorkDay = 1 THEN 1 ELSE 0 END), 0) FROM mwg.Calendar
  10:  WHERE CalendarDate >= @date1
  11:      AND CalendarDate <= @date2
  12:      
  13:      RETURN @result
  14:  END    
  15:   
  16:  GO



So now I can query a velocity that excludes weekends. I can also toggle off holidays if I choose to.

Saturday, August 25, 2012

SSRS Continuous Line

I have ran into issues with SSRS drawing a continuous line before. What do I mean by continuous line…

image

The yellow line actually has a point at 8/20 and so there should be yellow going from the left edge to the right. Also note that we want it to connect the dots on the blue line where there is a gap.

Lots of googling led me to start playing with EmptyPoint and EmptyPointValue.

image

But the result isn’t really what I was looking for.

image

First notice the blue line shot off to the right. That is not what I want because those dates haven’t happened yet. I want the blue line to just stop. Also note that the color is black. Getting the color to match the series would require custom code…. really.

Then I happened to stumble across something.

From this view everything looked fine…

image

But Series Properties revealed a different perspective.

image

No Category Field. So I set the CategoryField to TimeStamp and re-render the report…

image

Ah much better.

Hopefully this will save someone else the headache I went through. If nothing else – I can circle back to this next time I try and solve this problem.

Saturday, May 19, 2012

Visual Studio allows seeing whitespace

Did you know that you can make whitespace visible in Visual Studio.

Ctrl+R, Ctrl+W

I discovered this from here.

It looks like this

image

Sunday, April 22, 2012

Specifications in Javascript

I have learned to love the concept of specifications, derived from the Specification Pattern. While the way that I have used them is really just a subset of the actual pattern – I have found it very easy to introduce into my existing code.

Basically, we want to separate boolean based logic from the domain object so that it can be used by others, and changed independently.  For example given a Person object,

image

We may have business rules about their name like hasName and isAge.

image

these examples show how we can easily reuse the logic behind hasName and isAge. Here is what the functions actually look like.

image

It is worth noting that hasName doesn’t actually have to return a function – because the specification itself doesn’t have any arguments (isAge does). For consistency, I decided that all specifications should wrap a function. The actual specification takes the arguments, and the inner function takes the object to be tested.

This actually only gets us to the point that we can do things like this

image

not things like

image

if we have gone through all the effort to create the specification, we might as well make it available right on the domain object. In a dynamic language like javascript that is relatively easy and highly reusable.

image

Sweet!!

I am debating moving specifications into the prototype stack. They aren’t very usable in the typical context of prototype (inheritance), but it would eliminate the need for passing specifications to SpecificationInjector because it would just look for it on the object that was passed to it.

MVVM and Dependencies

I am still learning Model-View-ViewModel via KnockoutJS. One concern I find myself continually coming back to is handling dependency. Let me illustrate with a simple example.

   1:  function PersonViewModel(personModel){
   2:      this.Name = ko.observable(personModel.Name);
   3:  }

Here we have created a simple view model for a person – not concerned with dependencies just yet… but now we want to be able to save a person – so we end up with…


   1:  function PersonViewModel(personModel){
   2:      this.Name = ko.observable(personModel.Name);
   3:      this.save = function(){
   4:          $.ajax(...);
   5:      };
   6:  }



This is a point of contention. My sniffer goes off about Single Responsibility, it is very possible that at some point we may change how we access the server for Person, and Person should be unaffected (ie. url change, moving some arguments into the url/ query string, switching from rest to node.js, or not hit the server at all, like local storage). So lets get some separation of concerns in here.


   1:  function PersonViewModel(personModel, personDataAccessObject){
   2:      var self = this;
   3:      self.Name = ko.observable(personModel.Name);
   4:      self.save = function(){
   5:          personDataAccessObject.save(self);
   6:      };
   7:  }



Alright, so this is looking good… until we start using it…


   1:  function ContactManagerViewModel(){
   2:      var self = this;
   3:      self.contacts = ko.observableArray([]);
   4:      self.createContact = function(){
   5:          self.contacts.push(new PersonViewModel({
   6:              Name: 'Sally'
   7:          }));
   8:      };
   9:  }



This is what we would like to see – note the simple call to construct a PersonViewModel – but this is going to fail miserably when we try to save (b/c we never passed in the personDataAccessObject). Surely we could just pass it in, but the coupling can get out of control as everything it needs, we need in our constructor, and we have to pass to it, and anytime its constructor changes so do we. Been there, done that, ain’t going back.


Options



  1. Global Namespace we can put personDataAccessObject in the global namespace so that any other class can get to it, it also provides a way for a consumer to change that dependency without effecting other code. What I don’ like is that because it is global – if there were multiple instances of our contactManager, it would be very difficult to allow them to use different implementations of personDataAccessObject because they are both pointing to the same global reference. (Note while on the surface personDataAccesssObject might not seem like a good example, imagine one instance is for preview and you don’t want to actually save data)

  2. Closure this style is going to be harder to explain, but basically the entire app (all the ViewModels, etc.) live in one closure so that they can share variables. This giant closure would have one public method exposed which returns the namespace so that you could put it wherever you want. Then you could have two of these namespaces, and can override the implementation of personDataAccessObject for just one of them. I prefer to keep my js classes encapsulated to one js file as this keeps me honest in terms of coupling. The equivalent of this in C# would be to use inner classes – which is rarely the right solution.

  3. Coupling to Parent  for our PersonViewModel, instead of taking a personDataAccessObject, we would take a ContactManagerViewModel and would reference it as parent. ContactManagerViewModel would have the responsibility of having a way for us to save. I don’t feel like this really solves anything. We still have coupling between the two and we still need to pass in extra stuff to PersonViewModel. Where I guess would buy us something is when PersonViewModel requires 5 dependencies, it could be just one.

  4. Factory Pattern in forcing myself to think about how I would solve this if I wasn’t in the UI – I land at Factory Pattern. The idea is that we would have one or more factories that are responsible for depdencies. They would encapsulate any instantiation logic so that there is one place that knows how to properly instantiate things, and would expose methods for things like personDataAccessObject.

Ironically, Factory Pattern is a little of the other 3 (but arguably the right little). Its constructor would live in the global namespace so that anyone can create one. It will have its own closure maintaining instances, etc. that is is not global like #2. And we will have to pass it to our children, but arguably only it, like #3.


So here is the factory


   1:  function ContactManagerFactory(){
   2:      this.getPersonDataAccessObject = function(){
   3:          return {
   4:              save : function(person){
   5:                  $.ajax(...);
   6:              }
   7:          };
   8:      }
   9:  }



we can new one up and override things at will (have as many separate instances as we want).


   1:   
   2:  var factory = new ContactManagerFactory();
   3:  factory.getPersonDataAccessObject = function(){
   4:      return {
   5:          save : function(){
   6:              // do nothing - this is  a preview
   7:          }
   8:      };
   9:  }




we can then pass it around like so


   1:  function ContactManagerViewModel(factory){
   2:      var self = this;
   3:      self.contacts = ko.observableArray([]);
   4:      self.createContact = function(){
   5:          self.contacts.push(factory.newPerson({
   6:              Name: 'Sally'
   7:          });
   8:      };
   9:  }



notice the need for a newPerson method (which needs to pass a factory to PersonViewModel and so happens to be a factory – see where this is going…)


   1:  function ContactManagerFactory(){
   2:      var self = this;
   3:      self.getPersonDataAccessObject = function(){
   4:          return {
   5:              save : function(person){
   6:                  $.ajax(...);
   7:              }
   8:          };
   9:      };
  10:   
  11:      self.newPerson = function(personModel){
  12:          return new PersonViewModel(personModel, self);
  13:      }
  14:  }



Lastly,


   1:  function PersonViewModel(personModel, factory){
   2:      var self = this;
   3:      self.Name = ko.observable(personModel.Name);
   4:      self.save = function(){
   5:          factory.getGersonDataAccessObject().save(self);
   6:      };
   7:  }



In closing, there are things I don’t like – (super factory object) but it’s the closest I was able to come up with, and the only thing I could come up with that I could stomach.