-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
596 lines (411 loc) · 33.5 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
<!DOCTYPE html>
<!--[if IEMobile 7 ]><html class="no-js iem7"><![endif]-->
<!--[if lt IE 9]><html class="no-js lte-ie8"><![endif]-->
<!--[if (gt IE 8)|(gt IEMobile 7)|!(IEMobile)|!(IE)]><!--><html class="no-js" lang="en"><!--<![endif]-->
<head>
<meta charset="utf-8">
<title>Kinjal Chakraborty</title>
<meta name="author" content="Kinjal Chakraborty">
<meta name="description" content="I was working on a project and came across a situation where three different classes share some common functionalities. On the first attempt, all the …">
<!-- http://t.co/dKP3o1e -->
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="canonical" href="http://www.kinjalc.com/">
<link href="/favicon.ico" rel="icon">
<link href="/stylesheets/screen.css" media="screen, projection" rel="stylesheet" type="text/css">
<script src="/javascripts/modernizr-2.0.js"></script>
<script src="/javascripts/ender.js"></script>
<script src="/javascripts/octopress.js" type="text/javascript"></script>
<link href="/atom.xml" rel="alternate" title="Kinjal Chakraborty" type="application/atom+xml">
<!--Fonts from Google"s Web font directory at http://google.com/webfonts -->
<link href="http://fonts.googleapis.com/css?family=PT+Serif:regular,italic,bold,bolditalic" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=PT+Sans:regular,italic,bold,bolditalic" rel="stylesheet" type="text/css">
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-37294066-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body class="collapse-sidebar sidebar-footer" >
<header role="banner"><hgroup>
<h1><a href="/" style="font-size:35px;">Kinjal Chakraborty</a></h1>
</hgroup>
</header>
<nav role="navigation"><ul class="subscription" data-subscription="rss">
<li><a href="/atom.xml" rel="subscribe-rss" title="subscribe via RSS">RSS</a></li>
</ul>
<form action="http://google.com/search" method="get">
<fieldset role="search">
<input type="hidden" name="q" value="site:www.kinjalc.com" />
<input class="search" type="text" name="q" results="0" placeholder="Search"/>
</fieldset>
</form>
<ul class="main-navigation">
<li><a href="/">Blog</a></li>
<li><a href="/blog/archives">Archives</a></li>
<li><a href="/about">About</a></li>
</ul>
</nav>
<div id="main">
<div id="content">
<div class="blog-index">
<article>
<header>
<h1 class="entry-title"><a href="/blog/javascript-inheritance/">Javascript Inheritance</a></h1>
</header>
<div class="entry-content"><p>I was working on a project and came across a situation where three different classes share some common functionalities.</p>
<p>On the first attempt, all the classes I created contained common functions. And it was code duplicate acrosss all the functions. I thought of grouping common functionalities in a separate function and use this common function
everywhere I needed.</p>
<p>But that was not the exact structure I wanted to implement. It would have been better if some of the common fucntionlities were
overridden. Later I tried to understand how inhertiance works in javascript.</p>
<p><a href="http://www.amazon.com/JavaScript-Design-Patterns-Recipes-Problem-Solution/dp/159059908X">Pro JavaScript Design Patterns</a> has a nice
explanation of achieving inheritance in javascript. I thought of sharing this concept with a simple example.</p>
<p>The implementation of inheritance in javascript is completely different than how it is done in other object oriented languages.</p>
<p>Let’s define the case. There are two classes - A and B. A is parent class and B is child. In OO language languae it is like -</p>
<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="kd">class</span> <span class="nc">A</span> <span class="o">{</span>
</span><span class='line'>
</span><span class='line'><span class="o">}</span>
</span><span class='line'>
</span><span class='line'><span class="kd">class</span> <span class="nc">B</span> <span class="kd">extends</span> <span class="n">A</span> <span class="o">{</span>
</span><span class='line'>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>
<p>Now, create this classes in javascript.</p>
<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">function</span> <span class="nx">A</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="kd">function</span> <span class="nx">B</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>
<p>Javascript doesn’t have a “class” concept like other OO language. It works on prototype model. Let’s add some code to the above js classes.</p>
<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">function</span> <span class="nx">A</span><span class="p">(</span><span class="nx">name</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'> <span class="k">this</span><span class="p">.</span><span class="nx">name</span> <span class="o">=</span> <span class="nx">name</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="nx">A</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">getName</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'> <span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="nx">name</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="kd">function</span> <span class="nx">B</span><span class="p">(</span><span class="nx">color</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'> <span class="k">this</span><span class="p">.</span><span class="nx">color</span> <span class="o">=</span> <span class="nx">color</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="nx">B</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">getColor</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'> <span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="nx">color</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>
<p>The question how does B inherits properties from A ?
There is no <code>extend</code> in javascript.</p>
<p>Object relationship is acieved by prototype chain.</p>
<p>What is it ? Every object in javascript has an attribute <code>prototype</code>. When a memeber of an object is accessed, javascript looks for the memeber in prototype if it doesn’t find in
current object. This searching continues through each object’s prototype untill the memeber is found or null.</p>
<p>Now make a relation between A and B. To do this add an empty object <code>new A()</code> to B“’s prototype. And reset the constructor attribute of B.</p>
<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="nx">B</span><span class="p">.</span><span class="nx">prototype</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">A</span><span class="p">();</span>
</span><span class='line'><span class="nx">B</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">constructor</span> <span class="o">=</span> <span class="nx">B</span><span class="p">;</span>
</span><span class='line'><span class="nx">B</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">getColor</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'> <span class="k">this</span><span class="p">.</span><span class="nx">color</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>
<p>One more thing remaining that is add a call to <code>A</code>’s constructor in <code>B</code>.</p>
<p>Modifying the child class <code>B</code></p>
<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">function</span> <span class="nx">B</span><span class="p">(</span><span class="nx">color</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'> <span class="nx">A</span><span class="p">.</span><span class="nx">call</span><span class="p">(</span><span class="k">this</span><span class="p">,</span> <span class="nx">name</span><span class="p">);</span>
</span><span class='line'> <span class="k">this</span><span class="p">.</span><span class="nx">color</span> <span class="o">=</span> <span class="nx">color</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>
<p>So the relation of parent-child is done. Now let’s examine the output.</p>
<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="nx">b</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">B</span><span class="p">(</span><span class="s2">"I am b"</span><span class="p">,</span> <span class="s1">'white'</span><span class="p">);</span>
</span><span class='line'><span class="nx">b</span><span class="p">.</span><span class="nx">getName</span><span class="p">();</span> <span class="c1">// output: "I am b"</span>
</span></code></pre></td></tr></table></div></figure>
<p><code>b.getName()</code> will first search at <code>B</code>’s prototype. It will continue on searching since
getName() doesn’t exist here. <code>B</code> holds a prototype relationship with <code>A</code>.
And <code>getName()</code> exists there. So it outputs result.</p>
<p>This is somewhat similar to the concept of <em>classical inheritance</em>. There is one more way of doing it.</p>
<p>Instead of deifning the structure thgrough a class, we can just deifne a object and this object is used by others.</p>
<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">var</span> <span class="nx">A</span> <span class="o">=</span> <span class="p">{</span>
</span><span class='line'> <span class="nx">name</span><span class="o">:</span> <span class="s2">"I am A"</span><span class="p">,</span>
</span><span class='line'> <span class="nx">getName</span><span class="o">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'> <span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="nx">name</span><span class="p">;</span>
</span><span class='line'> <span class="p">}</span>
</span><span class='line'><span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>
<p>Now this <code>A</code> object can be cloned and used in other objects. <a href="http://www.amazon.com/JavaScript-Design-Patterns-Recipes-Problem-Solution/dp/159059908X">It</a> has a helper function to clone a object efficiently.</p>
<p>The clone function is -</p>
<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">function</span> <span class="nx">clone</span><span class="p">(</span><span class="nx">object</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'> <span class="nx">fucntion</span> <span class="nx">F</span><span class="p">()</span> <span class="p">{}</span>
</span><span class='line'> <span class="nx">F</span><span class="p">.</span><span class="nx">prototype</span> <span class="o">=</span> <span class="nx">object</span><span class="p">;</span>
</span><span class='line'> <span class="k">return</span> <span class="k">new</span> <span class="nx">F</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>
<p>It creates a empty function and the prototype object is added to empty function’s prototype attribute. And it return a new object of
the empty function (it only has the prototype object).</p>
<p>Now use this <code>clone</code> function to clone the object <code>A</code></p>
<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">var</span> <span class="nx">B</span> <span class="o">=</span> <span class="nx">clone</span><span class="p">(</span><span class="nx">A</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>
<p>So <code>b.getName()</code> will link to <code>A</code>’s <code>getName()</code>.</p>
<p>This is called <em>prototypal inheritance</em>. It is clean, memory efficient. But actually it’s underlying concept is complex than classical
inheritance.</p>
<p>There is another concept in javascript to share common functionalities. It is <a href="http://en.wikipedia.org/wiki/Mixin">Mixin</a>.</p>
<p>Let’s define the Mixin class.</p>
<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">var</span> <span class="nx">Mixin</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{};</span>
</span><span class='line'><span class="nx">Mixin</span><span class="p">.</span><span class="nx">prototype</span> <span class="o">=</span> <span class="p">{</span>
</span><span class='line'> <span class="nx">getSomeObject</span><span class="o">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'> <span class="k">return</span> <span class="s2">"something"</span><span class="p">;</span>
</span><span class='line'> <span class="p">}</span>
</span><span class='line'><span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>
<p>Now the idea is to reuse this <code>getSomeObject()</code> function in other objects. The helper function described <a href="http://www.amazon.com/JavaScript-Design-Patterns-Recipes-Problem-Solution/dp/159059908X">here</a> does the job making this relation.</p>
<p>This is the function -</p>
<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="kd">function</span> <span class="nx">augment</span><span class="p">(</span><span class="nx">receivingClass</span><span class="p">,</span> <span class="nx">givingClass</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'> <span class="k">for</span><span class="p">(</span><span class="nx">methodName</span> <span class="k">in</span> <span class="nx">givingClass</span><span class="p">.</span><span class="nx">prototype</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'> <span class="k">if</span><span class="p">(</span><span class="o">!</span><span class="nx">receivingClass</span><span class="p">.</span><span class="nx">prototype</span><span class="p">[</span><span class="nx">methodName</span><span class="p">])</span> <span class="p">{</span>
</span><span class='line'> <span class="nx">receivingClass</span><span class="p">.</span><span class="nx">prototype</span><span class="p">[</span><span class="nx">methodName</span><span class="p">]</span> <span class="o">=</span> <span class="nx">givingClass</span><span class="p">.</span><span class="nx">prototype</span><span class="p">[</span><span class="nx">methodName</span><span class="p">];</span>
</span><span class='line'> <span class="p">}</span>
</span><span class='line'> <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>
<p>Let’s use this function so that <code>B</code> can use it -</p>
<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="nx">augment</span><span class="p">(</span><span class="nx">B</span><span class="p">,</span> <span class="nx">Mixin</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>
<p>Mixin can be used when we want to share some common properties among dissimilar classes.</p>
<p>See also <br />
<a href="http://www.amazon.com/JavaScript-Design-Patterns-Recipes-Problem-Solution/dp/159059908X">Pro JavaScript Design Patterns</a></p>
</div>
</article>
<article>
<header>
<h1 class="entry-title"><a href="/blog/closure/">Power of Closure</a></h1>
</header>
<div class="entry-content"><p>To begin with closure, let’s take a quick look at scope.</p>
<p>What is Scope ? It deifnes the environemnt or area where variables or functions are available. Suppose we have a method <code>foo()</code>
and we create a variable <code>x</code> inside <code>foo()</code> . <br />
So it is clear that the variable <code>x</code> is only available inside <code>foo()</code> (unless explicitly defined as global).
Now let’s think, there is another function that wants to use this local variable <code>x</code> or the other way let me say the other function wants to use the state of function <code>foo()</code>.</p>
<p>How to do this ?</p>
<p>Look at this image.<br />
<a href="http://s1290.beta.photobucket.com/user/skypya/media/Blog/closure_zps340b5344.jpg.html" target="_blank"><img src="http://i1290.photobucket.com/albums/b521/skypya/Blog/closure_zps340b5344.jpg" border="0" alt="Photobucket"/></a></p>
<p>Let me explain the image with a small example in lisp.</p>
<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>(defun foo(x)
</span><span class='line'> (defun bar(n) (+ n x)))</span></code></pre></td></tr></table></div></figure>
<p>In the code <code>foo()</code> points to the outer region in the image and <code>bar()</code> is the inner region. Notice <code>x</code> is actually in the scope of <code>foo()</code>. However the inner method <code>bar()</code> has access to the variable <code>x</code>. This is closure. <em>The inner region is associated with an
environment that is the outer region</em>.<br />
The vairable <code>x</code> is a free varible and accessible to <code>foo()</code> and <code>bar()</code>. Interesting fact is that there will be no problem to acccess the free variable <code>x</code> inside the method <code>bar()</code> even though the outher method <code>foo()</code> is returned.</p>
<p>Converting the above code to use an annonymous function.</p>
<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>(defun foo(x)
</span><span class='line'> #' (lambda (x) (+ x 10)))</span></code></pre></td></tr></table></div></figure>
<p>Both of the above codes are creating closure - one with named function and the other with
annonymous function. Note that we frequently use annonymous function but that doesn’t mean it is creating a closure. The function must require an environment to form a closure
same as the way a named function does.</p>
<p>There are different languages which support closure, for example, Lisp, Javascirpt, pyhton. And there are languages which do not support Closure, examples are C, C++, Java.</p>
<p>Let me write a small code in pyhton that has closure.</p>
<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>def outer(num1, num2):
</span><span class='line'> def inner(num):
</span><span class='line'> return num + num1 + num2
</span><span class='line'> return inner</span></code></pre></td></tr></table></div></figure>
<p>If we call the above function <code>outer(2, 3)(10)</code>, it will output <code>15</code>.</p>
<p>Now, Let’s output the same result using a <em>callback</em> function.</p>
<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>def foo(num1, num2, callback):
</span><span class='line'> n = num1 + num2
</span><span class='line'> return callback(n)</span></code></pre></td></tr></table></div></figure>
<p>Calling the function <code>foo()</code> with the arguments <code>num1</code>, <code>num2</code> and a callback function
using <em>lambda</em>.</p>
<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>foo(2, 3, lambda x : x + 10)</span></code></pre></td></tr></table></div></figure>
<p>The outout is <code>15</code>.</p>
<p>So here is the question. How is closure different from a callback function?
If we generalize the question, it would be - <em>how is closure different from the
similar techniques available in other languages which do not support closure, for
example, function pointer in C, annonymous inner class in java</em>?</p>
<p>The main difference is, in the above example the method <code>inner</code> knows that it came from the method <code>outer</code>, that is, <code>inner</code> has idea of it’s environment. But callback is not. It is just a <em>block of executable code which can be passed as an argument to other function</em>.</p>
<p>See also <br />
1. <a href="http://martinfowler.com/bliki/Closure.html">Closure</a> <br />
2. <a href="http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html">Closure and inner class</a></p>
</div>
</article>
<article>
<header>
<h1 class="entry-title"><a href="/blog/singleton-pattern/">Singleton Pattern</a></h1>
</header>
<div class="entry-content"><p>This post is about brief explanation of singleton pattern. it’s structure, usage and implementations in different languages - java, javascript and python.</p>
<blockquote><p>In mathematics the term singleton defines a set exactly having one element.</p></blockquote>
<p>So an example is <code>{a}</code> since it has one element.
In design patterns, as per <a href="http://en.wikipedia.org/wiki/Gang_of_Four_(software)">GOF</a> the intent of singleton pattern is to ensure that a class has one instance and provide a global point of access to it.</p>
<h6>Implementation -</h6>
<ul>
<li>The class is designed in such a way that only once instance can ever be created.</li>
<li>Operation of creating the instance is hidden by declaring it private member of the class. Also make it static so the object is read only.</li>
</ul>
<p>Let’s look at a java basic non thread safe singleton implementation</p>
<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="kd">class</span> <span class="nc">MySingleton</span> <span class="o">{</span>
</span><span class='line'> <span class="kd">private</span> <span class="kd">static</span> <span class="kd">final</span> <span class="n">MySingleton</span> <span class="n">instance</span> <span class="o">=</span> <span class="k">new</span> <span class="n">MySingleton</span><span class="o">();</span>
</span><span class='line'>
</span><span class='line'> <span class="kd">public</span> <span class="kd">static</span> <span class="n">MySingleton</span> <span class="nf">getInstance</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'> <span class="k">return</span> <span class="n">instance</span><span class="o">;</span>
</span><span class='line'> <span class="o">}</span>
</span><span class='line'>
</span><span class='line'> <span class="kd">private</span> <span class="nf">MySingleton</span><span class="o">()</span> <span class="o">{</span> <span class="o">}</span> <span class="c1">// prevents new MySingleton()</span>
</span><span class='line'>
</span><span class='line'> <span class="kd">public</span> <span class="n">String</span> <span class="nf">getX</span><span class="o">()</span> <span class="o">{</span> <span class="k">return</span> <span class="s">"X"</span><span class="o">;</span> <span class="o">}</span>
</span><span class='line'>
</span><span class='line'> <span class="kd">public</span> <span class="n">String</span> <span class="nf">getY</span><span class="o">()</span> <span class="o">{</span> <span class="k">return</span> <span class="s">"Y"</span><span class="o">;</span> <span class="o">}</span>
</span><span class='line'>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>
<p>Notice that the constructor is private. It will throw error if a client direcrly wants to initialize the object. It makes sure that there will be only one instance of the class.</p>
<h6>How to use this class?</h6>
<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="n">MySingleton</span><span class="o">.</span><span class="na">getInstance</span><span class="o">().</span><span class="na">getX</span><span class="o">();</span>
</span><span class='line'><span class="n">MySingleton</span><span class="o">.</span><span class="na">getInstance</span><span class="o">().</span><span class="na">getY</span><span class="o">();</span>
</span></code></pre></td></tr></table></div></figure>
<h6>Wrong approach to initialize it-</h6>
<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="n">MySingleton</span> <span class="n">mySingleton</span> <span class="o">=</span> <span class="k">new</span> <span class="n">MySingleton</span><span class="o">();</span>
</span><span class='line'><span class="n">mySingleton</span><span class="o">.</span><span class="na">getX</span><span class="o">();</span>
</span></code></pre></td></tr></table></div></figure>
<h6>How is singleton different from a static class? <br /></h6>
<p>Singleton, is a pattern whose instance is created only once and can be treated just like an normal instance. But static class allows only static methods. It is more of a procedural approach.</p>
<h6>Usage</h6>
<p>There are lot of bad reputation about singleton pattern. Singleton is like <em>creating a global variable and access it like you are creating a new instance of the class</em>. And it is always <em>good to avoid global</em>. However good example of using singleton is creating config class of an application or reading/writting a log file.</p>
</div>
<footer>
<a rel="full-article" href="/blog/singleton-pattern/">Read on →</a>
</footer>
</article>
<div class="pagination">
<a href="/blog/archives">Blog Archives</a>
</div>
</div>
<aside class="sidebar">
</aside>
</div>
</div>
<footer role="contentinfo"><p>
Copyright © 2013 - Kinjal Chakraborty -
<span class="credit">Powered by <a href="http://octopress.org">Octopress</a></span>
</p>
</footer>
<script type="text/javascript">
var disqus_shortname = 'notes11';
var disqus_script = 'count.js';
(function () {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/' + disqus_script;
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
}());
</script>
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#appId=212934732101925&xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<script type="text/javascript">
(function(){
var twitterWidgets = document.createElement('script');
twitterWidgets.type = 'text/javascript';
twitterWidgets.async = true;
twitterWidgets.src = 'http://platform.twitter.com/widgets.js';
document.getElementsByTagName('head')[0].appendChild(twitterWidgets);
})();
</script>
</body>
</html>