Guides – BetterExplained https://betterexplained.com Math lessons that click Sat, 13 Aug 2022 16:44:33 +0000 en-US hourly 1 Learning math? Think like a cartoonist. https://betterexplained.com/articles/math-cartoonist/ https://betterexplained.com/articles/math-cartoonist/#comments Thu, 24 Jul 2014 19:47:19 +0000 http://betterexplained.com/?p=4593 What’s the essential skill of a cartoonist? Drawing ability? Humor? A deep well of childhood trauma?

I’d say it’s an eye for simplification, capturing the essence of an idea.

For example, let’s say we want to understand Ed O’Neill:

ed oneill original

A literal-minded artist might portray him like this:

realistic image

While the technical skill is impressive, does it really capture the essence of the man? Look at his eyes in particular.

A cartoonist might draw this:

cartoon image

Wow! The cartoonist recognizes:

  • The unique shape of his head. Technically, his head is an oval, like yours. But somehow, making his jaw wider than the rest of his head is perfect.

  • The wide-eyed bewilderment. The whites of his eyes, the raised brows, the pursed lips – the cartoonist saw and amplified the emotion inside.

So, who really “gets it”? It seems the technical artist worries more about the shading of his eyes than the message they contain.

Numbers Began With Cartoons

Think about the first numbers, the tally system:

I, II, III, IIII …

Those are… drawings! Cartoons! Caricatures of an idea!

They capture the essence of “existing” or “having something” without the specifics of what it represents.

Og the Cavemen Accountant might have tried drawing individual stick figures, buffalos, trees, and so on. Eventually he might realize a shortcut: draw a line and call it a buffalo. This captures the essence of “something is there” and our imaginations do the rest.

Math is an ongoing process of simplifying ideas to their cartoon essence. Even the beloved equals sign (=) started as a drawing of two identical lines, and now we can write “3 + 5 = 8” instead of “three plus five is equal to eight”. Much better, right?

So let’s be cartoonists, seeing an idea — really capturing it — without getting trapped in technical mimicry. Perfect reproductions come in after we’ve seen the essence.

Technically Correct: The Worst Kind Of Correct

We agree that multiplication makes things bigger, right?

Ok. Pick your favorite number. Now, multiply it by a random number. What happens?

  • If that random number is negative, your number goes negative
  • If that random number is between 0 and 1, your number is destroyed or gets smaller
  • If that random number is greater than 1, your number will get larger

Hrm. It seems multiplication is more likely to reduce a number. Maybe we should teach kids “Multiplication generally reduces the original number.” It’ll save them from making mistakes later.

No! It’s a technically correct and real-life-ily horrible way to teach, and will confuse them more. If the technically correct behavior of multiplication is misleading, can you imagine what happens when we study the formal definitions of more advanced math?

There’s a fear that without every detail up front, people get the wrong impression. I’d argue people get the wrong impression because you provide every detail up front.

As George Box wrote, “All models are wrong, but some are useful.”

A knowingly-limited understanding (“Multiplication makes things bigger”) is the foothold to reach a more nuanced understanding. (“People generally multiply positive numbers greater than 1, so multiplication makes things larger. Let’s practice. Later, we’ll explore what happens if numbers are negative, or less than one.”)

Takeaways

I wrap my head around math concepts by reducing them to their simplified essence:

  • Imaginary numbers let us rotate numbers. Don’t start by defining i as the square root of -1. Show how if negative numbers represent a 180-degree rotation, imaginary numbers represent a 90-degree one.

  • The number e is a little machine that grows as fast as it can. Don’t start with some arcane technical definition based on limits. Show what happens when we compound interest with increasing frequency.

  • The Pythagorean Theorem explains how all shapes behave (not just triangles). Don’t whip out a geometric proof specific to triangles. See what circles, squares, and triangles have in common, and show that the idea works for any shape.

  • Euler’s Formula makes a circular path. Don’t start by analyzing sine and cosine. See how exponents and imaginary numbers create “continuous rotation”, i.e. a circle.

Avoid the trap of the guilty expert, pushed to describe every detail with photorealism. Be the cartoonist who seeks the exaggerated, oversimplified, and yet accurate truth of the idea.

Happy math.

PS. Here’s my cheatsheet full of “cartoonified” descriptions of math ideas.

]]>
https://betterexplained.com/articles/math-cartoonist/feed/ 55
How To Learn Trigonometry Intuitively https://betterexplained.com/articles/intuitive-trigonometry/ https://betterexplained.com/articles/intuitive-trigonometry/#comments Mon, 24 Feb 2014 16:30:11 +0000 http://betterexplained.com/?p=3844 Trig mnemonics like SOH-CAH-TOA focus on computations, not concepts:

body proportions

TOA explains the tangent about as well as $x^2 + y^2 = r^2$ describes a circle. Sure, if you’re a math robot, an equation is enough. The rest of us, with organic brains half-dedicated to vision processing, seem to enjoy imagery. And “TOA” evokes the stunning beauty of an abstract ratio.

I think you deserve better, and here’s what made trig click for me.

  • Visualize a dome, a wall, and a ceiling
  • Trig functions are percentages to the three shapes

Motivation: Trig Is Anatomy

Imagine Bob The Alien visits Earth to study our species.

Without new words, humans are hard to describe: “There’s a sphere at the top, which gets scratched occasionally” or “Two elongated cylinders appear to provide locomotion”.

After creating specific terms for anatomy, Bob might jot down typical body proportions:

  • The armspan (fingertip to fingertip) is approximately the height
  • A head is 5 eye-widths wide
  • Adults are 8 head-heights tall

body proportions trig analogy

How is this helpful?

Well, when Bob finds a jacket, he can pick it up, stretch out the arms, and estimate the owner’s height. And head size. And eye width. One fact is linked to a variety of conclusions.

Even better, human biology explains human thinking. Tables have legs, organizations have heads, crime bosses have muscle. Our biology offers ready-made analogies that appear in man-made creations.

Now the plot twist: you are Bob the alien, studying creatures in math-land!

Generic words like “triangle” aren’t overly useful. But labeling sine, cosine, and hypotenuse helps us notice deeper connections. And scholars might study haversine, exsecant and gamsin, like biologists who find a link between your tibia and clavicle.

And because triangles show up in circles…

circular path

…and circles appear in cycles, our triangle terminology helps describe repeating patterns!

Trig is the anatomy book for “math-made” objects. If we can find a metaphorical triangle, we’ll get an armada of conclusions for free.

Sine/Cosine: The Dome

Instead of staring at triangles by themselves, like a caveman frozen in ice, imagine them in a scenario, hunting that mammoth.

Pretend you’re in the middle of your dome, about to hang up a movie screen. You point to some angle “x”, and that’s where the screen will hang.

Trig dome analogy

The angle you point at determines:

  • sine(x) = sin(x) = height of the screen, hanging like a sign
  • cosine(x) = cos(x) = distance to the screen along the ground [“cos” ~ how “close”]
  • the hypotenuse, the distance to the top of the screen, is always the same

Want the biggest screen possible? Point straight up. It’s at the center, on top of your head, but it’s big dagnabbit.

Want the screen the furthest away? Sure. Point straight across, 0 degrees. The screen has “0 height” at this position, and it’s far away, like you asked.

The height and distance move in opposite directions: bring the screen closer, and it gets taller.

Tip: Trig Values Are Percentages

Nobody ever told me in my years of schooling: sine and cosine are percentages. They vary from +100% to 0 to -100%, or max positive to nothing to max negative.

Let’s say I paid \$14 in tax. You have no idea if that’s expensive. But if I say I paid 95% in tax, you know I’m getting ripped off.

An absolute height isn’t helpful, but if your sine value is .95, I know you’re almost at the top of your dome. Pretty soon you’ll hit the max, then start coming down again.

How do we compute the percentage? Simple: divide the current value by the maximum possible (the radius of the dome, aka the hypotenuse).

That’s why we’re told “Sine = Opposite / Hypotenuse”. It’s to get a percentage! A better wording is “Sine is your height, as a percentage of the hypotenuse”. (Sine becomes negative if your angle points “underground”. Cosine becomes negative when your angle points backwards.)

Let’s simplify the calculation by assuming we’re on the unit circle (radius 1). Now we can skip the division by 1 and just say sine = height.

Every circle is really the unit circle, scaled up or down to a different size. So work out the connections on the unit circle and apply the results to your particular scenario.

Try it out: plug in an angle and see what percent of the height and width it reaches:

The growth pattern of sine isn’t an even line. The first 45 degrees cover 70% of the height, and the final 10 degrees (from 80 to 90) only cover 2%.

This should make sense: at 0 degrees, you’re moving nearly vertical, but as you get to the top of the dome, your height changes level off.

Tangent/Secant: The Wall

One day your neighbor puts up a wall right next to your dome. Ack, your view! Your resale value!

But can we make the best of a bad situation?

trig wall analogy

Sure. What if we hang our movie screen on the wall? You point at an angle (x) and figure out:

  • tangent(x) = tan(x) = height of screen on the wall
  • distance to screen: 1 (the screen is always the same distance along the ground, right?)
  • secant(x) = sec(x) = the “ladder distance” to the screen

We have some fancy new vocab terms. Imagine seeing the Vitruvian “TAN GENTleman” projected on the wall. You climb the ladder, making sure you can “SEE, CAN’T you?”. (Yeah, he’s naked… won’t forget the analogy now, will you?)

Let’s notice a few things about tangent, the height of the screen.

  • It starts at 0, and goes infinitely high. You can keep pointing higher and higher on the wall, to get an infinitely large screen! (That’ll cost ya.)

  • Tangent is just a bigger version of sine! It’s never smaller, and while sine “tops off” as the dome curves in, tangent keeps growing.

How about secant, the ladder distance?

  • Secant starts at 1 (ladder on the floor to the wall) and grows from there
  • Secant is always longer than tangent. The leaning ladder used to put up the screen must be longer than the screen itself, right? (At enormous sizes, when the ladder is nearly vertical, they’re close. But secant is always a smidge longer.)

Remember, the values are percentages. If you’re pointing at a 50-degree angle, tan(50) = 1.19. Your screen is 19% larger than the distance to the wall (the radius of the dome).

(Plug in x=0 and check your intuition that tan(0) = 0, and sec(0) = 1.)

Cotangent/Cosecant: The Ceiling

Amazingly enough, your neighbor now decides to build a ceiling on top of your dome, far into the horizon. (What’s with this guy? Oh, the naked-man-on-my-wall incident…)

Well, time to build a ramp to the ceiling, and have a little chit chat. You pick an angle to build and work out:

trig ceiling

  • cotangent(x) = cot(x) = how far the ceiling extends before we connect
  • cosecant(x) = csc(x) = how long we walk on the ramp
  • the vertical distance traversed is always 1

Tangent/secant describe the wall, and COtangent and COsecant describe the ceiling.

Our intuitive facts are similar:

  • If you pick an angle of 0, your ramp is flat (infinite) and never reachers the ceiling. Bummer.
  • The shortest “ramp” is when you point 90-degrees straight up. The cotangent is 0 (we didn’t move along the ceiling) and the cosecant is 1 (the “ramp length” is at the minimum).

Visualize The Connections

A short time ago I had zero “intuitive conclusions” about the cosecant. But with the dome/wall/ceiling metaphor, here’s what we see:

Trig all functions in a single diagram

Whoa, it’s the same triangle, just scaled to reach the wall and ceiling. We have vertical parts (sine, tangent), horizontal parts (cosine, cotangent), and “hypotenuses” (secant, cosecant). (Note: the labels show where each item “goes up to”. Cosecant is the full distance from you to the ceiling.)

Now the magic. The triangles have similar facts:

Trig identities from similar triangles and pythagorean theorem

From the Pythagorean Theorem ($a^2 + b^2 = c^2$) we see how the sides of each triangle are linked.

And from similarity, ratios like “height to width” must be the same for these triangles. (Intuition: step away from a big triangle. Now it looks smaller in your field of view, but the internal ratios couldn’t have changed.)

This is how we find out “sine/cosine = tangent/1”.

I’d always tried to memorize these facts, when they just jump out at us when visualized. SOH-CAH-TOA is a nice shortcut, but get a real understanding first!

Gotcha: Remember Other Angles

Psst… don’t over-focus on a single diagram, thinking tangent is always smaller than 1. If we increase the angle, we reach the ceiling before the wall:

Trig alternative

The Pythagorean/similarity connections are always true, but the relative sizes can vary.

(But, you might notice that sine and cosine are always smallest, or tied, since they’re trapped inside the dome. Nice!)

Summary: What Should We Remember?

For most of us, I’d say this is enough:

  • Trig explains the anatomy of “math-made” objects, such as circles and repeating cycles
  • The dome/wall/ceiling analogy shows the connections between the trig functions
  • Trig functions return percentages, that we apply to our specific scenario

You don’t need to memorize $1^2 + \cot^2 = \csc^2$, except for silly tests that mistake trivia for understanding. In that case, take a minute to draw the dome/wall/ceiling diagram, fill in the labels (a tan gentleman you can see, can’t you?), and create a cheatsheet for yourself.

In a follow-up, we’ll learn about graphing, complements, and using Euler’s Formula to find even more connections.

Appendix: The Original Definition Of Tangent

You may see tangent defined as the length of the tangent line from the circle to the x-axis (geometry buffs can work this out).

Tangent

As expected, at the top of the circle (x=90) the tangent line can never reach the x-axis and is infinitely long.

I like this intuition because it helps us remember the name “tangent”, and here’s a nice interactive trig guide to explore:

Trig interactive

Still, it’s critical to put the tangent vertical and recognize it’s just sine projected on the back wall (along with the other triangle connections).

Appendix: Inverse Functions

Trig functions take an angle and return a percentage. $\sin(30) = .5$ means a 30-degree angle is 50% of the max height.

The inverse trig functions let us work backwards, and are written $\sin^{-1}$ or $\arcsin$ (“arcsine”), and often written asin in various programming languages.

If our height is 25% of the dome, what’s our angle?

Plugging asin(.25) into a calculator gives an angle of 14.5 degrees.

Now what about something exotic, like inverse secant? Often times it’s not available as a calculator function (even the one I built, sigh).

Looking at our trig cheatsheet, we find an easy ratio where we can compare secant to 1. For example, secant to 1 (hypotenuse to horizontal) is the same as 1 to cosine:

\displaystyle{\frac{\sec}{1} = \frac{1}{\cos}}

Suppose our secant is 3.5, i.e. 350% of the radius of the unit circle. What’s the angle to the wall?


\begin{aligned}
\frac{\sec}{1} &= \frac{1}{\cos} = 3.5 \\
\cos &= \frac{1}{3.5} \\
\arccos(\frac{1}{3.5}) &= 73.4
\end{aligned}

Appendix: A Few Examples

Example: Find the sine of angle x.

Sine Example

Ack, what a boring question. Instead of “find the sine” think, “What’s the height as a percentage of the max (the hypotenuse)?”.

First, notice the triangle is “backwards”. That’s ok. It still has a height, in green.

What’s the max height? By the Pythagorean theorem, we know


\begin{aligned}
3^2 + 4^2 &= \text{hypotenuse}^2 \\
25 &= \text{hypotenuse}^2 \\
5 &= \text{hypotenuse}
\end{aligned}

Ok! The sine is the height as a percentage of the max, which is 3/5 or .60.

Follow-up: Find the angle.

Of course. We have a few ways. Now that we know sine = .60, we can just do:

\displaystyle{\arcsin(.60) = 36.9}

Here’s another approach. Instead of using sine, notice the triangle is “up against the wall”, so tangent is an option. The height is 3, the distance to the wall is 4, so the tangent height is 3/4 or 75%. We can use arctangent to turn the percentage back into an angle:

\displaystyle{\tan = \frac{3}{4} = .75 }

\displaystyle{\arctan(.75) = 36.9}

Example: Can you make it to shore?

Boat Example

You’re on a boat with enough fuel to sail 2 miles. You’re currently .25 miles from shore. What’s the largest angle you could use and still reach land? Also, the only reference available is Hubert’s Compendium of Arccosines, 3rd Ed. (Truly, a hellish voyage.)

Ok. Here, we can visualize the beach as the “wall” and the “ladder distance” to the wall is the secant.

First, we need to normalize everything in terms of percentages. We have 2 / .25 = 8 “hypotenuse units” worth of fuel. So, the largest secant we could allow is 8 times the distance to the wall.

We’d like to ask “What angle has a secant of 8?”. But we can’t, since we only have a book of arccosines.

We use our cheatsheet diagram to relate secant to cosine: Ah, I see that “sec/1 = 1/cos”, so


\begin{aligned}
\sec &= \frac{1}{\cos} = 8 \\
\cos &= \frac{1}{8} \\
\arccos(\frac{1}{8}) &= 82.8
\end{aligned}

A secant of 8 implies a cosine of 1/8. The angle with a cosine of 1/8 is arccos(1/8) = 82.8 degrees, the largest we can afford.

Not too bad, right? Before the dome/wall/ceiling analogy, I’d be drowning in a mess of computations. Visualizing the scenario makes it simple, even fun, to see which trig buddy can help us out.

In your problem, think: am I interested in the dome (sin/cos), the wall (tan/sec), or the ceiling (cot/csc)?

Happy math.

Update: The owner of Grey Matters put together interactive diagrams for the analogies (drag the slider on the left to change the angle):

interactive-2

Thanks!

]]>
https://betterexplained.com/articles/intuitive-trigonometry/feed/ 153
Brevity Is Beautiful https://betterexplained.com/articles/brevity-is-beautiful/ https://betterexplained.com/articles/brevity-is-beautiful/#comments Thu, 22 Apr 2010 07:00:53 +0000 http://betterexplained.com/?p=620 Brevity is my favorite aspect of effective communication. We’re limited creatures, only able to handle a few thoughts at once — make them count!

Concise writing helps us share ideas, but we hamstring ourselves by trying to appear “substantial”. Let’s figure out how to avoid this trap.

Benefits of Brevity

Concise, efficient writing has non-obvious benefits:

We maximize information density.

We can hold about 7 digits in memory. Given limited room, a few powerful thoughts are better than a single dilute one.

What’s better: “x is the sum of two times y and three times z” or “x = 2y + 3z”?

Concise thoughts are more understandable. (By the way, math used to be written in English, as above. Egads.)

We respect the reader.

Long-winded diatribes are about the author: listen to me and look at what I know. Effective communication is about the reader: I’ve distilled hundreds of pages to these essential insights.

Information is everywhere, and I can eventually understand a topic by reading dozens of mediocre books. But time is limited — give me the source that communicates the most understanding in the least time.

We communicate raw thought.

Writing isn’t about words, it’s about recreating ideas:

  • Idea in my head → words are written → words are read → idea in your head

With good writing we hear the author’s voice, not our own thoughts deciphering their message. The ideal of communicating raw ideas appears in programming, design, art and even humor (“Brevity is the soul of wit”).

Obstacles to Brevity

If brevity is so desirable, why don’t we do it?

Schoolchild Guilt (aka the 10-page paper)

School assignments ask for pages of text, not ideas. The teacher really wants an essay with 3 meaningful insights, but that’s tough to specify. So instead he asks for a 10-pager, hoping some ideas are buried inside.

The assignment is easily gamed: take a few scattered thoughts, bump up the font and margins, and tada, we have 10 pages. We know this isn’t what the teacher wants, but it satisfies the letter of the law.

An analogy: A king secretly wants treasure. He asks his subjects to bring him a ton of dirt each, hoping for gems inside. They do, and on average there’s a single gem in each pile — but the king spends hours clawing through the dirt.

One day a peasant sees a lone gem on the beach. But because the king asked for dirt (he’ll be punished if he only brings a handful of “stuff”), he buries the gem in an enormous pile and delivers that to the king, who spends hours trying to find the jewel.

Is that what the king wanted? We writers are the peasants that bring material for you to sift through!

Getting Our Money’s Worth

Thought experiment: you see two reference books, one at 100 pages and the other at 200. Do you wonder if the smaller book could be concise and well-written, or do you immediately assume “bigger is better” and reach for the tome?

And that’s why publishers pad their books — we reward those with the most words, not the best ones. It’s akin to judging a portrait by how much paint was used, or a song by its length.

Brevity and Substance

My “brevity” means economy of words, saying what’s necessary and no more. “Necessary” could be a paragraph or 50 pages: the key is delivering gems, not dirt. While writing, you'll have a hunch :).

I still struggle to accept it’s ok, nay good, to share a single, concise thought if you think it’s a gem. There's no need to appear substantial.

Does anyone think the 278-word Gettysburg address isn’t meaty enough?

Expert’s Guilt (The sky is not blue)

Brevity’s enemy is an armada of helpful caveats. Quick question: is the sky blue?

Well, it’s black at night. And orange at sunset/sunrise. And grey when cloudy. In fact, it’s more likely to be non-blue than blue!

My goodness, I could never declare “The sky is blue” without a 3-page disclaimer, lest a meteorologist have my head.

No. Writing riddled with caveats is like the “Are you sure? Really sure?” dialogs we hate in software: yes, yes, we get it!

Models are simplifications, we all know this: assume an intelligent reader and don’t encumber your writing to satisfy every critic. Corner cases are exactly that, and should live away from the main text.

Examples of Brevity

I learn by reflecting on great examples — what makes them tick?

Computers and Programming

Ruby has wonderful shortcuts for everyday tasks.

value = parameter || getValue() || "default"

Which means “try to use parameter, then try getValue(), and if all else fails assign a default”. Ruby was the first language I felt I was reading without notational cruft getting in the way.

Kernighan and Ritchie’s The C Programming Language is the gold standard of technical manuals. Concise and useful, it has no desire to satisfy some publisher’s pagecount requirement: “C is not a big language, and it is not well served by a big book.”

Don’t Make Me Think! is an excellent usability guide. The title is the summary: keep things brainlessly easy. The book expands with examples, yet remains brief.

The unix command line (“cat foo.txt | sort | uniq -c | sort -rn”) is wonderfully concise and powerful: it’s hard to express the above more simply (output a file, sort the lines, count the unique ones, and sort again by that count in descending order).

Mathematics

As we saw with English vs. arithmetic, expressive notation helps us focus on the idea being conveyed.

Consider the difference between decimal and Roman numerals: how can you use math when it takes 5 minutes to decode MCMXCVII times XLII? Decimal notation is one of our greatest discoveries.

Quotes

Why do we love quotes? They are distilled thoughts! Great quotes help us experience an idea without getting lost in verbiage.

Some favorites:

  • “I have made this letter longer than usual because I lack the time to make it shorter.” –Blaise Pascal (It’s easier to plop down dirt than to dig through and pull out the gems)

  • “Vigorous writing is concise. A sentence should contain no unnecessary words, a paragraph no unnecessary sentences, for the same reason that a drawing should have no unnecessary lines and a machine no unnecessary parts. This requires not that the writer make all his sentences short, or that he avoid all detail and treat his subjects only in outline, but that every word tell.” –William Strunk Jr. (Efficiency is universally appreciated)

Economy of Motion

Great athletes and musicians are efficient. They move less and waste less than the rest of us, and do more with the same amount of time. Concise thoughts require less mental energy to understand.

Headlines

Top 10 lists grab our attention. Why? They imply someone has found the gems: we sifted through dozens of items and are bringing you the best. Unfortunately, these headlines have been abused to mean “Here are 10 random things”.

Cheatsheets

Cheatsheets are pure gems, going from A to B without distraction. The key is knowing the background of your audience. A physics cheatsheet is great for reference, not learning.

Final Thoughts

Reflection helps develop a learning philosophy. I discovered that my fear of not having enough substance was based on measuring dirt. Brainstorming, writing down ideas, and leaving the essentials is more than ok — it’s my ideal.

Remember: is our goal to satisfy a length requirement, impress with our vocabulary, or communicate effectively? Do readers a favor and give ‘em your best gems.

]]>
https://betterexplained.com/articles/brevity-is-beautiful/feed/ 56
Aha! Moments When Learning Git https://betterexplained.com/articles/aha-moments-when-learning-git/ https://betterexplained.com/articles/aha-moments-when-learning-git/#comments Wed, 10 Mar 2010 16:00:45 +0000 http://betterexplained.com/?p=603 Git is a fast, flexible but challenging distributed version control system. Before jumping in:

Along with a book, tutorial and cheatsheet, here are the insights that helped git click.

There's a staging area!

Git has a staging area. Git has a staging area!!!

Yowza, did this ever confuse me. There's both a repo ("object database") and a staging area (called "index"). Checkins have two steps:

  • git add foo.txt
    • Add foo.txt to the index. It's not checked in yet!
  • git commit -m "message"
    • Put staged files in the repo; they're now tracked
    • You can "git add --update" to stage all tracked, modified files

Why stage? Git's flexible: if a, b and c are changed, you can commit them separately or together.

But now there's two undos:

  • git checkout foo.txt
    • Undo local changes (like svn revert)
  • git reset HEAD foo.txt
    • Remove from staging area (local copy still modified).

Add and commit, add and commit -- Git has a rhythm.

Branching is "Save as..."

Branches are like "Save as..." on a directory. Best of all:

  • Easily merge changes with the original (changes tracked and never applied twice)
  • No wasted space (common files only stored once)

Why branch? Consider the utility of "Save as..." for regular files: you tinker with multiple possibilities while keeping the original safe. Git enables this for directories, with the power to merge. (In practice, svn is like a single shared drive, where you can only revert to one backup).

Imagine virtual directories

I see branches as "virtual directories" in the .git folder. While inside a physical directory (c:\project or ~/project), you traverse virtual directories with a checkout.

  • git checkout master
    • switch to master branch ("cd master")
  • git branch dev
    • create new branch from existing ("cp * dev")
    • you still need to "cd" with "git checkout dev"
  • git merge dev
    • (when in master) pull in changes from dev ("cp dev/* .")
  • git branch
    • list all branches ("ls")

My inner dialogue is "change to dev directory (checkout)... make changes... save changes (add/commit)... change to master directory... copy in changes from dev (merge)".

The physical directory is a scratchpad. Virtual directories are affected by git commands:

  • rm foo.txt
    • Remove foo.txt from your sandbox (restored if you checkout the branch again)
  • git rm foo.txt
    • Remove foo.txt from current virtual directory
    • Gotcha: you need to commit that change!

Know the current branch

Just like seeing your current directory, put the current branch in your prompt!

git branch highlighting

In my .bash_profile:

parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* (.*)/(1)/'
}

export PS1="[33[00m]u@h[33[01;34m] W [33[31m]$(parse_git_branch) [33[00m]$[33[00m] "

Visualize your branch structure

Git leaves branch organization to you. Nvie.com has a great branch strategy:

  • Have a mainline (master). Mentally it's on the far right.
  • Create branches (master -> dev) and subbranches (dev -> featureX). The further from master, the crazier.
  • Only merge with neighbors (master -> dev -> feature X, or featureX -> dev -> master)

Stay sane by choosing a branch layout up front. I have a master tracking a svn project, and dev for my own code. In general, master is clean so I can branch anytime for one-off fixes.

Understand local vs. remote

Git has local and remote commands; seeing both confused me ("When do you checkout vs. pull?"). Work locally, syncing remotely as needed.

Local data

  • git init
    • create local repo
    • use git add/commit/branch to work locally

Remote data

  • git remote add name path-to-repo
    • track a remote repo (usually "origin") from an existing repo
    • remote branches are "origin/master", "origin/dev" etc.
  • git branch -a
    • list all branches (remote and local)
  • git clone path-to-repo
    • create a new local git repo copied from a remote one
    • local master tracks remote master
  • git pull
    • merge changes from tracked remote branch (if in dev, pull from origin/dev)
  • git push
    • send changes to tracked remote branch (if in dev, push to origin/dev)

Why local and remote? Subversion has central checkins, so you avoid committing unfinished work. With git, local commits are frequent and you only push when ready.

GUIDs are GOOD

Git addresses information by a hash (GUID) of its contents. If two branches are the same, they have the same GUID (and vice versa).

Why's this cool? We can create branches independently, merge them, and have a common GUID. No central numbering needed. Usually, we just compare the first few digits: "Are you on a93?".

Tips & Tricks

For your .gitconfig:

[alias]
        ci = commit
        st = status
        co = checkout
        oneline = log --pretty=oneline
        br = branch
        la = log --pretty="format:%ad %h (%an): %s" --date=short

There are some GUI tools for git, but I prefer to learn via the command line. Git is opinionated software (which I like), and analogies help me understand its world view.

]]>
https://betterexplained.com/articles/aha-moments-when-learning-git/feed/ 35