Thursday, July 27, 2017

Factory Pattern

Much has been written about the Factory-pattern, I assume. Here's my viewpoint on it.

I was puzzled a bit when I first read about it. Why?  Because I was mostly programming in Smalltalk at the time. In Smalltalk the ONLY way you can create objects is by using the Factory Pattern. You create new objects by calling the class-method 'new'. So if you always follow a pattern, it's not really a pattern any more, is it? It's like fish in the water. What is this thing "water" they keep talking about?

I take it a bit further. For a Smalltalker the Factory-pattern is like air. Without it they would be dead. Without it they couldn't create any objects and thus couldn't write any Smalltalk programs and thus couldn't make a living as a Smalltalker.

But it is easy to see the benefits of using Factory (as opposed to not using it) in languages like C++ and Java and JavaScript. You create object-instances  by calling (typically static) methods, not by calling constructors directly. This means you can have more than one such method per class. And you can have more than one class implementing a factory-method of the same name.

In Smalltalk in contrast there are no "constructors". You don't need them _because_  every Smalltalk-class implements the Factory pattern, because the class-method 'new' is inherited to every class, from the root-class Object.

What the Factory pattern does is it abstracts away from the IMPLEMENTATION of the results of the class- (or "static") methods used to produce  the objects. Think about the proverbial  Sausage Factory. You don't really need to know what goes on inside the factory. You only care that you get a Hot Dog when you order one, and you get a Bratwurst when you order that.

Depending on the class upon which you call the (same) class-method the result can be an instance of any number of different classes. You need not care which exact class it is, as long as it behaves like you expect.  And depending on the (different) class-method you call on any of the classes the result can be an instance of a different classes, giving it different properties.

Above may sounds like a complicated descriptions, but it's just trying to express the two main properties, two main features of Factory-pattern:  

1. A Factory can produce multiple different products, depending on what you order
2. There can be multiple factories  which return their own different product even though you make the exact same "order" to each of them .

This separates the implementation = the way a factory manufactures its products, from their specification = what their products are. And it gives you flexibility in deciding whether you create one factory with many products, or many factories each producing just one or a few products.

Factory Method Pattern (Wikipedia)


Copyright © 2017 Panu Viljamaa. All rights reserved 

Thursday, April 20, 2017

ES6 Structuring and Destructuring

JavaScript ES6 contains a great new feature called  "Destructuring Assignment". It is great because among other things it allows you to do things like:

  [a, b] = [b, a];

In other words it allows you to swap the values of two variables without the help of any extra temporary variable!

More typically and usefully Destructuring Assignment can be used to de-struct an object saving values of its chosen properties into individual variables:

  var {a, b} = {a: 1, b: 2}
  // a -> 1, b -> 2


Another great ES6 feature is called "Shorthand property name". That allows you to create objects out of variables so that the  name of the variable  becomes the property-key and  value of the variable becomes the value (of the property). Like this:

  var ding = 55;
  var myOb = {ding};
  ok (myOb.ding === 55);


What may not be immediately obvious is that Destructuring Assignment and Shorthand Property Name are two sides of the same coin.  In fact I think Shorthand Property Name could and should be called simply "Structuring".

Here's an example of how structuring followed by destructuring gives us back the original (like flipping a coin):

  var ding           = {};
  var originalDing   = ding;
  var myOb           = {ding};   // STRUCTURING
  ding = "forget about it";
  ok  (ding !== originalDing);
  var {ding}         = myOb ;    // DE-STRUCTURING
  ok  (ding === originalDing);


(Note, "ok()" is my simple assertion utility-function)

LINKS:


Copyright © 2017 Panu Viljamaa. All rights reserved 

Thursday, April 13, 2017

Why Prototypical Languages (like ES6) need Classes

In "prototypical languages" like JavaScript you can use object-instances to do much anything. Typically you do this  by defining "constructors" to specify the DEFAULT properties of the group of objects created by that constructor.

After the constructor gives you the new instance you can  re-assign its properties including methods  any way  you like. Then, and this is the big draw of  Prototypical Programming,  you can use that modified object as the prototype for further objects. Any object can serve as the prototype for any number of further objects ... which can serve as the prototype of yet further objects and so on. Convenient.


So why does ECMAScript 2015 need "classes"?

In the prototypical paradigm any object can be a "version" of any other object. This may sound like a great idea at first, a great extension, instances can act as "classes" too.  Why not!  More power to you. Why artificially limit the ability to use any object as a "prototype" from which new objects similar to it are derived?

The short answer is:  Classes are  constraints. Classes are contracts . Classes are invariants. Those make your program's behavior  easier to reason about.

Classes describe the properties of all their instances, so when you see an instance, and you know its class, you know what properties, especially, what methods it has.  If you know the class you also know what those methods do, or are supposed to do.

Now if any object can have its own set of methods, which is possible in the prototypical paradigm, it becomes harder to know what properties and methods any instance has, what are its methods and what can you expect from their behavior. That  makes it harder to UNDERSTAND such a program, whether written by you or someone else.

Why understandability is the most important property of Software?

Understanding what software does, is THE great big challenge of Software Engineering. If you don't understand how a program works you can't modify it because any small change in one place could have big effects in other parts of the program, possibly crashing it under some conditions. If you can't modify it you can't improve it.  Therefore, if you have to modify it you do it very carefully. Which  means you can only improve it very slowly. And each improvement is getting more expensive (assuming each improvement is as difficult to understand as the previous ones).

If you can understand your program, you can improve any other property of it. If you can't, you can't.

A class is a declaration of the properties and behavior of the set of objects created by that class. It means you know much about any object simply by knowing its class. That makes it much easier to  understand  what your program does, as a whole.

If it walks like a Duck it may be a Duck. But it may bark like a Dog. It might. You just don't know.

If it IS a Duck, it will  not  bark like a Dog. If it is an instance of a class, it will behave as instances of that class do in all the ways prescribed by that class. That's why we need classes.

LINKS:



Copyright © 2017 Panu Viljamaa. All rights reserved 



Tuesday, April 4, 2017

Technical Debt Increases Agility

You might think that "Agility" is a good thing, and "Technical Debt" is bad. Right?
Well it depends.

Of course it's great to have no debt. But if you had taken that loan last year you could have invested in the stock-market and become rich and it would be even greater than just "having no debt".

When you're working on a programming project you might spend most of your time refactoring your code, to avoid technical debt. Or you could spend your time getting the software out to the users, no matter how much technical debt it carries.

Making sure your software has "no technical debt" will help you in the FUTURE when you need to change and adapt and maintain your software. But using resources now to get rid of technical debt decreases your CURRENT AGILITY, your ability to produce value to the users right now. If you can't help users fast you're not very agile.

There's no clear-cur rule as to how much debt a business should carry, or how much technical debt a given software project should have. Debt is not a bad thing if it helps you be agile, right now.

https://twitter.com/panulogic/status/849331316218896385


Copyright © 2017 Panu Viljamaa. All rights reserved 


Saturday, March 25, 2017

Misssing Pattern in Model-View-Controller

MVC confusion must largely stem from the fact that the original MVC pattern was implemented in Smalltalk and in Smalltalk everything is an Object. With the Web this is not so. You have HTML, you have web-server, you have browser and you have database. It gets confusing trying to fit it all into "MVC".  Understanding Model-View-Controller is an example of a great explanation of Model-View-Controller for the Web. Still I think it misses one crucial part of MVC as originally envisioned, and implemented in Smalltalk.

What is the main point  of Smalltalk MVC  seldom included in descriptions  of "Web-MVC"?  It is not  that Model View and Controller are "separate". It is pretty obvious they should be. No spaghetti-code please. The main point is  what makes M V and C capable of working together EVEN THOUGH they are "separate"...

The original MVC solution for connecting the parts is the Observer-pattern.  A View subscribes to events broadcast by the model which are of relevance to that particular View. This means the model is unaware of the existence of the view, yet it is able to notify the view(s) when specific aspects of it change. Yes "aspect" is a key term in early descriptions of MVC.

The Model "broadcasts" events about changes happening to it. But implementation-wise the "system" must take care those events are propagated to the proper recipients. This  invisible part of MVC, its  event-delivery sub-system goes largely missing in most explanations of  "Web-MVC".

So, MVC is more than M + V + C.  It is M + V + C + event-delivery sub-system that allows M V and C to communicate with each other by event subscription, thus remaining minimally dependent on each other.

Another misconception must be that there is a Model, a View and a Controller. In the original Smalltalk  MVC a major emphasis was on the idea that there were MULTIPLE  VIEWS for each model, each displaying a different "aspect" of it, and having its own controller. Models are often composed of parts which tmelselves are models too. It is really more like Models-Views-Controllers. In Web-MVC the web-page is typically the one and only "view" presenting some underlying something, vaguely referred to as "model".

There is value in categorizing parts of any application into a Model, View and Controller. But that is not close to being the same as the MVC-pattern in Smalltalk.

A pattern is in the eye of the beholder. The pattern I see in Smalltalk called MVC is multiple Views presenting different aspects of the model, communicating with it via event-subscription, driven by user-interaction events produced by multiple Controllers, of different classes.  Controller modifies the model, model broadcasts information about changes to its different aspects, views that are "tuned in" to the specific channel for that aspect  receive notifications of changes to it, so they can update their state, their "looks" by asking the view for the current value or state of the "aspect" in question.

The essence of MVC is not that there is M, V and C. It is how the M and V and C communicate, with each other.

Links:
Understanding model-view-controller
Model-View-Controller
Observer-pattern

Copyright © 2017 Panu Viljamaa. All rights reserved 
https://twitter.com/panulogic


Thursday, February 2, 2017

How to explain Threads

People new to programming might have hard time  understanding what are "threads". How are they different from "programs"?  There's a simple metaphor you can use to explain  the concept of "threads":

Your  program is like a labyrinth.  You can't walk "through it", you must follow the paths that exist. There are many branches in those paths you can take. You can go forwards and you can reverse your direction to return to an earlier point. You can pick things up to carry with you while inside the labyrinth, maybe just some information, maybe take photographs.

The program has run its course when you return back to the entry-point and exit. You still have the things you picked along the route, the photographs you took etc. Those are your output. What you took with you into the labyrinth was your input, say a map which guided your choice of turns at the branch-points.

The above  is single-threading. You moving inside the labyrinth is like the program-counter in your program's execution environment pointing to different locations in the program being "run". (Yes you can run in a labyrinth too, you must if a Minotaur is chasing).


Now leash multiple visitors into the same labyrinth, more or less at the same time, concurrently . They will choose their own paths according to their own maps. They might communicate with each other by leaving notes on the walls for others to read. Some visitors might overwrite notes written by others, probably not a very good practice but certainly possible. This is multi-threading: Multiple visitors in the labyrinth at the same time. Each visitor walking inside the labyrinth is one thread.

Why are  they called "threads"?  I can think of one reason. In the Minotaur-myth Theseus entered the labyrinth with a  ball of thread.  He tied the start of the thread to the entry point of the labyrinth. Then he unwound the thread as he moved deep into the Labyrinth. After he found the Minotaur and killed it he needed a way to find his way back out. He simply followed the unwound thread.





__________________________________
Copyright © 2017 Panu Viljamaa. All rights reserved 
https://twitter.com/panulogic

Monday, January 30, 2017

Function.prototype.map IV

The previous episodes  Function.prototype.mapFunction.prototype.map II,  Function.prototype.map III describe how to use Function.prototype.map with three argument-types: Array, Object and Function.  These extensions to Function.prototype provide support for and take advantage of Functional Programming (a.k.a "FP") in JavaScript.

It is kind of fitting that additional support for Functional Programming in JavaScript should be provided as additional methods of the JavaScript class Function. Don't you think?

This blog-post describes some additional features not previously covered and the fpmap() -library as a whole. The described features are now implemented in the "fpmp" download available from npm and GitHub, see links below.


1.  WHERE DID IT ALL COME FROM?

JavaScript standard Array.prototype.map() can be used to execute a given function once once for each of the array-elements and get back an array containing the results of each such call:

  var arr = [1,2,3];
  var a2  = arr.map (double);  // -> [2, 4, 6] 

Above "double" is a function which returns its argument times two.  Writing such code I occurred to me  to ask did I write it correctly. Or should I have instead written:

  var a3 = double.map (arr);  // ???

Luckily I had it correct no problem. I usually don't' make errors like that I congratulated myself. But then I started thinking, is there any rule-of-thumb I could use to easily remember the correct order? Is there perhaps something obviously wrong in the "wrong order" ?

I couldn't find anything obviously wrong with it. So I started thinking, why does it have to matter which way I put it? If both ways would produce the same result then I could more easily remember the simplest rule: Order doesn't matter!  If something seems good either way, we shouldn't have to think much about which way to do it.

So, went to work and implemented the function "fpmap()".  Calling it to first install Function.prototpe.map(),  it now allows me to write:

  var a3 = double.map (arr); // -> [2,4,6] 


2. AN INSIGHT AND A REVELATION

This made me feel almost like I had discovered complex numbers!  Why?  Because it seemed the possible ways of using the same operation, with different types of arguments had now greatly expanded. It was almost like jumping out of line to the plane around it! Let me explain...

With [1,2,3].map(double) the "recipient" must always be an Array, and it seems argument-type must be Function, to make it useful in general. Regardless of what type the Array elements are, you can then always put in as argument some function that accepts those array-elements as argument.

With double.map([1,2,3]) it came obvious to ask a follow-up question: What if I use something else as argument, perhaps an Object like:  "double.map({x: 1, y: 2})" ?  Is there something useful such an expression could do?  YES OF COURSE. It can iterate over the fields of the argument-object, like  {x:1, y:2}.

You could't really do such an expansion with Array.prototype.map(), unless you start adding the method "map()" to all built-in prototypes in JavaScript. That is a possibility but there's no need for that if we can make Function.prototype.map treat different types of arguments in different ways. The area of the standard library that needs to be extended this way stays smaller, and you choose and alternative method-name to use as desired. You can install it as  Function . prototype . map9() if you wish to use a more unique name

With this re-arrangement there  seems to be no reason why the argument could not be a non-Array "object". Which leads to the further question: What else?  What are the argument-types that could be passed to Function .prototype .map, to accomplish something useful, some economies of the amount of code you must write, read, and understand?  What should be  the behavior of 'map' with such possible argument-types?


3. THE USEFUL ARGUMENT-TYPES OF Function.prototype.map 

The previous blog-posts described  three argument-types so far: Array, (non-Array) Object, Function. Yes. Function.prototype.map() can also take a function as its argument, the result being the "composition" of the two functions. And you can compose a whole series, a "pipeline" if you will:  funkA . map(funkB) . map(funkC) ;

But turns out there are still a few more argument-types with different, useful  behavior. In the end, currently "fpmap" now supports the following behaviors on the following six (6) argument-types:

A) Array

Like standard Array.prototype.map() but with recipient and the argument-types switched.

B) Object

Similar to Arrays but iterates over named properties of the object rather than array indexes.

C) Function

Implements function-composition. Like:  var result =  funkA . map(funkB) . map(funkC) ;

D) RegExp

Returns a function which can be used to Iterate over all matches of a given Regular Expression for any string-argument.

E) Number

Returns a function which when given an initial argument will call the source-function with it, then call it again with the results and so on N times, where N is the number that was given as argument to fmap(N). Naturally requires that the source-function result-type is the same as its argument type. Useful for creating numeric series like Fibonacci's but also for building arbitrary recursive data-structures.

F) String

Iterates by repeatedly calling a function that incrementally consumes parts of the argument string, in effect parsing it according to the language specified by the recipient-function.



4. WHAT UNITES THEM ALL

What unites the different argument types described above is they are all used in the same manner, as argument to Function.prototype.map. So it's kind of easy to remember how to use them, if not exactly what each of them exactly does.  But that you can look up from documentation.

For detailed documentation of the above and other features of fpmap() see the unit-tests-file fpmap_test.js. Tests don't lie. The code of  the tests serve as examples of how to use fpmap() with different arguments, and what to expects as result. There's also explanatory comments. The README.md of course is a good source for documentation  as well.

Could there  still be other additional, useful argument-types besides the above? Possibly. But the above is a good start.



5. LINKS

GitHuh:   https://github.com/panulogic/fpmap
Npm:      https://www.npmjs.com/package/fpmap
Twitter:   https://twitter.com/panulogic

_____________________________________________________________
Copyright © 2017 Panu Viljamaa. All rights reserved unless otherwise noted.
Reuse of source-code in this blog-post is allowed under the terms of 
Creative Commons Attribution 4.0 International (CC BY 4.0) -license