Hack hack hack...

An open journal-- some of it written for you, but most of it is for me.

Patterns of Enterprise Application Architecture

Introduction:

“Architecture” is a term that lots of people try to define, with little agree- ment. There are two common elements: One is the highest-level breakdown of a system into its parts; the other, decisions that are hard to change. It’s also increasingly realized that there isn’t just one way to state a system’s architec- ture; rather, there are multiple architectures in a system, and the view of what is architecturally significant is one that can change over a system’s lifetime. p. 1.

The subjectivity comes in here as well because, if you find that something is easier to change than you once thought, then it’s no longer architectural. In the end architecture boils down to the important stuff—whatever that is. p. 2

Responsiveness is about how quickly the system acknowledges a request as opposed to processing it. This is important in many systems because users may become frustrated if a system has low responsiveness, even if its response time is good. If your system waits during the whole request, then your responsiveness and response time are the same. However, if you indicate that you’ve received the request before you complete, then your responsiveness is better. Providing a progress bar during a file copy improves the responsiveness of your user inter- face, even though it doesn’t improve response time. p. 7

Patterns

There’s no generally accepted definition of a pattern, but perhaps the best place to start is Christopher Alexander, an inspiration for many pattern enthusi- asts: “Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice” [Alexander et al.]. Alexander is an architect, so he was talking about buildings, but the definition works pretty nicely for software as well. The focus of the pattern is a particular solution, one that’s both com- mon and effective in dealing with one or more recurring problems. Another way of looking at it is that a pattern is a chunk of advice and the art of creating patterns is to divide up many pieces of advice into relatively independent chunks so that you can refer to them and discuss them more or less separately. p. 9

Making a choice

Growing Object-Oriented Software, Guided by Tests

Object-Oriented Style

We value code that is easy to maintain over code that is easy to write. Implementing a feature in the most direct way can damage the maintainability of the system, for example by making the code difficult to understand or by introducing hidden dependencies between components. Balancing immediate and longer-term concerns is often tricky, but we’ve seen too many teams that can no longer deliver because their system is too brittle. p. 47

Encapsulation and Information Hiding We want to be careful with the distinction between “encapsulation” and “information hiding.” The terms are often used interchangeably but actually refer to two separate, and largely orthogonal, qualities: Encapsulation Ensures that the behavior of an object can only be affected through its API.It lets us control how much a change to one object will impact other parts of the system by ensuring that there are no unexpected dependencies between unrelated components.

Information hiding Conceals how an object implements its functionality behind the abstraction of its API. It lets us work with higher abstractions by ignoring lower-level details that are unrelated to the task at hand. p. 49

Our heuristic is that we should be able to describe what an object does without using any conjunctions (“and,” “or”). If we find ourselves adding clauses to the description, then the object probably should be broken up into collaborating objects, usually one for each clause. p. 52

Context Independence

While the “composite simpler than the sum of its parts” rule helps us decide whether an object hides enough information, the “context independence” rule helps us decide whether an object hides too much or hides the wrong information. p.54

Achieving Object-Oriented Design

Interface and Protocol Steve heard this useful distinction in a conference talk: an interface describes whether two components will fit together, while a protocol describes whether they will work together. p. 58

Kernighan and Plauger attribute the idea of pipes to Douglas McIlroy, who wrote a memo in 1964 suggesting the metaphor of data passing through a segmented garden hose. It’s currently available at http://plan9.bell-labs.com/who/dmr/mdmpipe.pdf. p. 66

The Sniper Makes a Bid

Defer Decisions There’s a technique we’ve used a couple of times now, which is to introduce a null implementation of a method (or even a type) to get us through the next step. This helps us focus on the immediate task without getting dragged into thinking about the next significant chunk of functionality. The null Auction, for example, allowed us to plug in a new relationship we’d discovered in a unit test without getting pulled into messaging issues. That, in turn, meant we could stop and think about the dependencies between our objects without the pressure of having a broken compilation. p. 136

When the facts change, I change my mind. What do you do, sir? —John Maynard Keynes p. 172

Computer Science According to Spencer

What is it

Big O

  • used to classify algorithms by changes to the inputs
  • O(1) - constant time - kilometers to millimeters
  • O(log n) - opposite of exponential growth, searching binary tree
  • O(n) - iterating over an array
  • O(n log n) - good sorting algorithms
  • O(n2) - bubble sort (bad algoritms)
  • O(2n) - the chess board, example doubling something

Exercises

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
  1.
  int rectangle_area(height, width) {
    int area = 0; // 1

    for(int i = 0; i < height; i++) { // 2*height + 1
      for(int j = 0; j < width; i++) { // 2*height*width + height
        area++; // height*width
      }
    }

    return area; // 1
  }

  complexity: 3*height*width + 2*height + 3
  order: O(height*width)


  2.

  Constant time. O(1).

  3.
  int halves(n) {
    int count = 0; // 1

    if(n % 2 == 1) { // n
      n = n - 1; // n
    }

    for(int i = n; i > 1; i = i / 2;) { // n + n + n
      count++; // n
    }

    return count; // 1
  }

  Complexity: 6n + 2
  Order O(log n)

  4.
  int bacteria_generation(days) {
    int total_population = 1; // 1
    int current_population = total_population; // 1

    for(int i = 0; i < days; i++) { // 1 + days - 1 + days - 1
      current_population = total_population; // days - 1

      for(int j = 0; j < current_population; j++) {
        total_population++;
      }
    }

    return total_population;
  }

  Order: O(2n)

  5.
  int max(array) {
    int max = array[0]; // 1

    for(int i = 1; i < array.length; i++) { //n + 1, [cost of determining array length](http://stackoverflow.com/questions/5872570/is-fixed-array-size-on-or-o1-in-space)
      if(array[i] > max) { // n
        max = array[i]; // potential n
      }
    }

    return max; // 1
  }

  [3n + 3 complexity]

  OR

  int max(array) {
    int temp; // 1

    // sort the array in ascending order
    for(int i = 0; i < array.length; i++) { // n + 1
      for(int j = 0; j < array.length - 1; j++) { // (n + 1)(n + 1) -> n^2 + 2n + 2
        if( array[j] > array[j+1]) { // potentially n(n + 1) -> n^2 + 2n + 2
          temp = array[j+1]; // 1(n + 1)
          array[j+1] = array[j]; // potentially n(n + 1) -> n^2 + 2
          array[j] = temp; // 1(n + 1)
        }
      }
    }

    return array[array.length-1]; // 1
  }

  [3n^2 + 7n + 9 complexity]

  The first is more efficient.

  6. Which algorithm, foo or bar, is faster when when n is 10? 100? 1000?

  int foo(n) {
    int sum = 0

    for(int i = 0; i < n + 500; i++) { // 510, 600, 1500 operations
      sum++;
    }

    return sum;
  }

  foo(10) = 130,305
  foo(100) = 180,300
  foo(1000) = 1,125,750

  int bar(n) {
    int sum = 0

    for(int i = 0; i < n; i++) { // 10
      for(int j = 0; j < n; j++) { // 10
        sum++; // 1
      }
    }

    return sum;
  }

  100, 10,000, 1,000,000

  bar is less work at 10, foo for the others

Optical Distortion, Inc. HBS Case Study

ODI Discussion/Analysis Questions

1)

  • What characteristics of the ODI lens are likely to make it appealing/unappealing to farmers?
    • Appealing

      • debeaking causes problems of their own in terms of the trauma it causes hurts short term production (for a full week, only 1 egg lost by 5 months) and in the long term in feed is wasted. Debeaking is not an exact science but reduced cannibalism to 9% from 25%.
      • for $2.50/hour could debeak approximately 220 birds per hour.
      • actually modifies behavior as opposed to reducing the weapon. Reduces cannibalsim to 4.5% (1/2 of debeaking)
        • 225 birds an hour to put in lense
      • reduces feed costs from 24.46 pounds to 23.68 lbs per 100 birds
        • 20,000 bird flock could save 156 pounds of feed per day ($12.324/day)
        • $158 per ton - $.079/lbs
    • unappealing

      • more upfront cost
      • can cause eye infection/fall out of place
      • change from current practice.

2)

  • What is the value to famers of lenses over debeaking? Can you quantify it? (Hint: Think about savings from cannibalization, egg reduction, feed, and labor)
    • $.00073 a bird for the debeaking process (which would be unneccessary).
    • $.22 per bird feed savings over a hen’s lifetime
    • $.108 in reduction in replacement cost of of $.21 since lenses reduces cannibolism by 1/2.
    • $.224 of added production in egg production. Hen lays 22 dozen eggs a year. If they lose a week of production from debeaking that is .423 dozen a week (which is 5 eggs a week) and if you assume that is $.53 a dozen that is $.224 cents of lost egg production per bird.

    • adds up to ~$.33 in added value per bird over their lifetime -> for large farms (50,000 birds) that $17,500 in added revenue a year (though it is annual cashflow of $12 million). For a small farm (10k) is it $3,500.

3)

  • What Pricing policy should ODI adopt and why? What is the savings per bird for farmers at these prices?
    • need market acceptance
    • somewhere around $.35 per bird in added value, which would easily cover the $.07 price increase.

    • Skimming Price

      • For products that represent a drastic departure from accepted ways of performing a service, a policy of relatively high prices coupled with heavy promotional expenditures in the early stages of market development (and lower prices at later stages) has proved successful for many products.
    • Penetration pricing
      • This policy is the reverse of the skimming policy in which the price is lowered only as short-run competition forces it.

    Pricibg Strategies

4)

  • Can ODI turn a profit at these prices?
    • sell at $0.08 per pair
    • cost $0.032 per pair + 12k (for first 15 million pairs)
    • cost $592,000 to operate
    • .048 per pair in profit
    • 592,000 / .048 = 12,333,333 lens to break even meaning they need .1% market penetration.

5)

  • How would you focus ODI’s marketing efforts? How would you segment the customer base?
    • 345 farms have 20% of america’s chickens. If they closed 4 of those farms they would be able to able to turn an operating profit.
      • crowded farms would benefit most from this change and the sales process would be easiest.

Passion Without Anger

I am fiery. That’s euphemistic for being a little man with a short fuse. I’ve never been the type that can fall asleep in the middle of a movie. If I’m into it then I’m into it. I’m intense. And boy, do I love what I do. I like being a multiplier. My coding skills are middling at best. I wouldn’t hire me for my team. Not enough raw talent. I like that I can impact the lives of the people on my team on a daily basis. That I can keep them motivated, engaged, fulfilled and happy. I feel like a mechanic that tunes highly customized and specialized machines. I once interviewed with the Yankees as a sports psychologist. Years later I feel like I have a similar, but better job. All that is to say, I take my responsibility to my people very seriously.

My team is filled with a bunch of beginners. More than half of our 12 person team has less than a year of professional coding experience. Everyday I’m humbled by how much they can get done. How fast they develop their skills. Their grit. How they rise to the challenges set in front of them. They find a way time after time.

And so, it is in this setting that I hurt so deeply when others don’t do their part. I get upset. I’ve always been impatient by nature. I have extremely (maybe unreasonably) high expectations of others. Given I don’t often feel that way about my reports, does this mean these emotions are only surfaced when I’m not in control? Is it trust? What are the limiting factors that enable me to be this understanding, mature, best version of myself?

When someone wrongs me or my people, my blood boils. I can feel my face flush. My chest constricts and breathing shallows. I hope it doesn’t look as bad as it feels, but I’m sure it must. Superiors, peers, low level employees. I’m indiscriminate. Forgiveness and empathy exit likely along with a balanced perspective and moderation. When it’s my engineers or a fellow soldier I fight alongside in the trenches, I can see how their misses happened. I can guide them to a better path. A screw up from others is a different story. It triggers a frustration and if done repeatedly, a resentment. How can they hold up their end of the bargain? Do they just not care? My frustration has more than once been interpreted as anger, which is about a worst case scenario. A short angry man in a director role in charge of a 12 person engineering team. How more cliche could I be?

What isn’t clear to me is how I can extend the patience and understanding to others? Empathy, compassion, calmness. I can clearly sort out the problems of my people. Advise them on clear steps forward. And it isn’t like I don’t understand the perspectives of non-technical folks. I’ve only been doing this for three years.

I recently heard that meditation can cause you to change your perspective to see problem situations as less catastrophic events. I think that would be very healthy for me. I tend to obsess on the problems. It tortures me in my sleep. Lack of sleep then alters my mood. Day to day, I shut down around “problem people.” I don’t act myself. I am quiet and withdrawn. This can’t make it better.

So the way forward has to begin with an altered perspective. Working to see the world in a more balanced way. I still want to let my love for what I do bleed through. I think it is my most valuable asset and I believe I have been rewarded for it. But wild swings of mood has never been in high demand and so my path forward is to find a way to take a calm breath and recalibrate when presented with these moments in the future. Maybe it is better self control or maybe given that I keep referring to them as “my people” I can expand who I count in that circle. What I do know is that writing about this early in the morning feeling centered is easy enough. But the real challenge begins as I attempt to self-correct next time the rubber hits the road.

Java Basics

Some basics

  • Here’s a basic method signature public static void main(String args[])
  • The void keyword allows us to create methods which do not return a value. Otherwise in java you need to specific what type the return value must be.
  • public is a Java keyword which declares a member’s access as public. Public members are visible to all other classes. This means that any other class can access a public field or method. Further, other classes can modify public fields unless the field is declared as final.

    • A best practice is to give fields private access and reserve public access to only the set of methods and final fields that define the class’ public constants. This helps with encapsulation and information hiding, since it allows you to change the implementation of a class without affecting the consumers who use only the public API of the class.
  • In Java, you need to have a method named main() in at least one class. This method must appear within a class, but it can be any class.

  • ints don’t evaluate to true

interfaces

  • An interface declaration consists of modifiers, the keyword interface, the interface name, a comma-separated list of parent interfaces (if any), and the interface body.
  • Interface programming is an architectural pattern for implementing modular programming at the component level in an object-oriented programming language which does not have a module system.
  • Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.

  • inheritance

    • A java class cannot extend more than one class at a time so it won’t provide support for multiple inheritance in classes, but it can extend more than one interface at a time so we java can support multiple inheritances with regard to interfaces.

HAS-A relationship

  • HAS-A means an instance of one class “has a” reference to an instance of another class or another instance of same class.
  • It is also known as “composition” or “aggregation”.
  • There is no specific keyword to implement HAS-A relationship but mostly we are depended upon “new” keyword.
  • Composition:
    • Without existence of container object, if there is no chance of existence of contained objects then container and contained objects are said to be strongly associated and this strong association is known as composition.
    • Eg: A “university” has several “departments”. Without existence of “university” there is no chance for the “departments” to exist. Hence “university” and “departments” are strongly associated and this strong association is known as composition.

IS-A Relationship:

  • This refers to inheritance or implementation.
  • Expressed using keyword “extends”.
  • Main advantage is code reusability.

Gang of Four - Observer and Mediator Pattern

Observer

  • subject is a logical place to keep track of the collection of the observers
    • the upside is the observers needing to check with the subject via something like long-polling versus the subject notifying the owners
  • ActiveRecord before_actions and after_actions are a ruby implementation of the observer pattern
  • How does JS does this?
    • functions are first class object, easy to pass around

Mediator

  • what’s the difference between mediator and observer
    • Define an object that encapsulates how a set of objects interact.
    • Mediator is a little more specific, it avoids having classes communicate directly but instead through a mediator. This helps the Single Responsibility principle by allowing communication to be offloaded to a class that just handles that.
  • replaces many to many interactions with one to many interactions.

React

What is it?

  • beefed up view layer
  • one way data binding -> if state changes the view changes
  • creates a virtual DOM
  • doesn’t provide any data management systems like backbone, Alt.js, Redux
  • no ajax, use JQuery
  • no routing capabilities
  • does not work well with JQuery DOM manipulation
  • can re-render a lot because of the virtual DOM manipulation

Setup

  • Babel
  • Gulp - task runner like rake
  • Webpack - processes through Babel interpreter and make it useable code

Quirks

  • class becomes className since it is a reserved word
  • typeSetting

Going forwards

  • flux
    • alt.js

Gang of Four: Proxy and Adapter Pattern

Proxy

  • reverse proxies
  • virtual proxy: creates expensive objects on demand. the worker box maybe?
    • infinite scroll or pagination (these objects exist in Octokit, where there are objects as placeholders but it hasn’t acutally fetched the data)
    • memoization example in the ruby boook
    • collection proxy

Adapter (aka wrapper)

  • Fog: cloud storage
  • ActiveRecord
  • OctokitWrapper is more of a decorator because it adds additional implementation on top of Octokit
  • Gateway pattern is an adapter specifically created to talk to external services
  • HierarchyBuilder is the adapter
  • The key difference between bridge and apater lies in their intents.
    • Adapter focuses on resolving incompatibilities between two existing interfaces. Bridge, on the other hand, bridges an abstraction and its (potentially numerous) implementations.

Gang of Four: Builder Pattern and Singletons

Builder

  • Concrete builders: html to markdown and html to json?
  • Could we think of a complex cart like this? Like line items of a educational program might compose a composite object by the cart which is the director.
    • doesn’t quite match up with subbing in different builders
  • like strategy pattern, but the way it differs is that it creates a composite object at the end
  • but this book is more about the abstract factory, the way this differs is that it the director gives you finer control of the order.
  • separating out how the object is built

  • e.g. Creating enrollments with one time purchases vs recurring subscriptions

    • client == browser
    • director == model ShoppingCart
    • builder1 == JobGuaranteeSubscription
    • builder2 == NonJobGuaranteeSubscription
    • result == subscription

    • Build part: slack group, google group, batch

Singleton

  • there is only one instance and so if another part of the code changes it, then you will have shot yourself in the foot
  • publishers, which are all singletons, don’t need more than one, but they could have been classes instead
  • dependency injection makes tests way easier