100% found this document useful (2 votes)
24 views

Download Complete Learning Java Script Design Patterns 2nd Edition Addi Osmani PDF for All Chapters

The document promotes the ebook 'Learning JavaScript Design Patterns, 2nd Edition' by Addy Osmani, available for download on ebookmeta.com. It discusses the importance of design patterns in JavaScript development, their historical context, and their relevance in modern programming practices. The book aims to provide developers with a comprehensive understanding of design patterns to enhance code maintainability and performance.

Uploaded by

mcnewratesso
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
24 views

Download Complete Learning Java Script Design Patterns 2nd Edition Addi Osmani PDF for All Chapters

The document promotes the ebook 'Learning JavaScript Design Patterns, 2nd Edition' by Addy Osmani, available for download on ebookmeta.com. It discusses the importance of design patterns in JavaScript development, their historical context, and their relevance in modern programming practices. The book aims to provide developers with a comprehensive understanding of design patterns to enhance code maintainability and performance.

Uploaded by

mcnewratesso
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Get the full ebook with Bonus Features for a Better Reading Experience on ebookmeta.

com

Learning Java Script Design Patterns 2nd Edition


Addi Osmani

https://ebookmeta.com/product/learning-java-script-design-
patterns-2nd-edition-addi-osmani/

OR CLICK HERE

DOWLOAD NOW

Download more ebook instantly today at https://ebookmeta.com


Learning JavaScript Design Patterns
SECOND EDITION

A JavaScript and React Developer’s Guide

With Early Release ebooks, you get books in their earliest form—the author’s
raw and unedited content as they write—so you can take advantage of these
technologies long before the official release of these titles.

Addy Osmani
Learning JavaScript Design Patterns
by Addy Osmani
Copyright © 2023 Adnan Osmani. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA
95472.
O’Reilly books may be purchased for educational, business, or sales promotional
use. Online editions are also available for most titles (http://oreilly.com). For more
information, contact our corporate/institutional sales department: 800-998-9938 or
[email protected].

Acquisitions Editor: Amanda Quinn

Development Editor: Michele Cronin

Production Editor: Clare Laylock

Interior Designer: David Futato

Cover Designer: Karen Montgomery

Illustrator: Kate Dullea

June 2023: Second Edition

Revision History for the Early Release

2022-12-05: First Release


2023-01-19: Second Release
2023-03-09: Second Release

See http://oreilly.com/catalog/errata.csp?isbn=9781098139872 for release details.


The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Learning
JavaScript Design Patterns, the cover image, and related trade dress are trademarks
of O’Reilly Media, Inc.
The views expressed in this work are those of the author and do not represent the
publisher’s views. While the publisher and the author have used good faith efforts to
ensure that the information and instructions contained in this work are accurate, the
publisher and the author disclaim all responsibility for errors or omissions, including
without limitation responsibility for damages resulting from the use of or reliance on
this work. Use of the information and instructions contained in this work is at your
own risk. If any code samples or other technology this work contains or describes is
subject to open source licenses or the intellectual property rights of others, it is your
responsibility to ensure that your use thereof complies with such licenses and/or
rights.
978-1-098-13981-0
[LSI]
Chapter 1. Introduction to Design
Patterns

A NOTE FOR EARLY RELEASE READERS


With Early Release ebooks, you get books in their earliest form—the author’s
raw and unedited content as they write—so you can take advantage of these
technologies long before the official release of these titles.
This will be the 1st chapter of the final book.
If you have comments about how we might improve the content and/or
examples in this book, or if you notice missing material within this chapter,
please reach out to the editor at [email protected].

Good code is like a love letter to the next developer who will maintain it!
Design patterns provide a common vocabulary to structure code, making it easier to
understand. They help enhance the quality of this connection to other developers.
Knowledge of design patterns helps us identify recurring themes in requirements
and map them to definitive solutions. We can rely on the experience of others who
have encountered a similar problem and devised an optimized method to address it.
This knowledge is invaluable as it paves the way for writing or refactoring code to
make it maintainable.
Whether on the server or client, JavaScript is a cornerstone of modern web
application development. The previous edition of this book focused on several
popular design patterns in the JavaScript context. Over the years, JavaScript has
significantly evolved as a language in terms of features and syntax. It now supports
modules, classes, arrow functions, and template literals that were not there earlier.
We also have advanced JavaScript libraries and frameworks that have made life easy
for many web developers. How relevant, then, are Design Patterns in the modern
JavaScript context?
It’s important to note that traditionally design patterns are neither prescriptive nor
language specific. You can apply them when you think they fit, but you don’t have
to. Like data structures or algorithms, you can still apply classic design patterns
using modern programming languages, including JavaScript. You may not need
some of these design patterns in modern frameworks or libraries where they are
already abstracted. Conversely, the use of specific patterns may even be encouraged
by some frameworks.
In this edition, we are taking a pragmatic approach to patterns. We will explore why
specific patterns may be the right fit for implementing certain features and if a
pattern it is still recommended in the modern JavaScript context.
As applications got more interactive, requiring a large amount of JavaScript, the
language came under constant criticism for its negative impact on performance.
Developers are continuously looking for new patterns that can optimize JavaScript
performance. This edition highlights such improvements wherever relevant. We will
also discuss framework-specific patterns such as React Hooks and Higher Order
Components that have become increasingly popular in the age of React.js.
Going back a step, let us start by exploring the history and importance of design
patterns. If you are already familiar with this history, feel free to skip to “What Is a
Pattern?” to continue reading.

History of Design Patterns


Design patterns can be traced back to the early work of an architect named
Christopher Alexander. He often wrote about his experiences in solving design issues
and how they related to buildings and towns. One day, it occurred to Alexander that
certain design constructs lead to a desired optimal effect when used repeatedly.
Alexander produced a pattern language in collaboration with two other architects,
Sara Ishikawa and Murray Silverstein. This language would help empower anyone
wishing to design and build at any scale. They published it in 1977 in a paper titled
“A Pattern Language,” later released as a complete hardcover book.
Around 1990, software engineers began to incorporate the principles Alexander had
written about into the first documentation about design patterns to guide novice
developers looking to improve their coding skills. It’s important to note that the
concepts behind design patterns have been around in the programming industry
since its inception, albeit in a less formalized form.
One of the first and arguably the most iconic formal works published on design
patterns in software engineering was a book in 1995 called Design Patterns:
Elements of Reusable Object-Oriented Software—written by Erich Gamma, Richard
Helm, Ralph Johnson, and John Vlissides. Most engineers today recognize this group
as the Gang of Four (or GoF for short).
The GoF publication is particularly instrumental in pushing the concept of design
patterns further in our field. It describes several development techniques and pitfalls
and provides 23 core object-oriented design patterns frequently used worldwide
today. We will cover these patterns in more detail in Chapter 6, and they also form
the basis for our discussion of Chapter 7.

What Is a Pattern?
A pattern is a reusable solution template that you can apply to recurring problems
and themes in software design. Similar to other programming languages, when
building a JavaScript web application, you can use the template to structure your
JavaScript code in different situations where you think it will help.
Learning and using Design patterns is mainly advantageous for developers because:
Patterns are proven solutions.
They are the result of the combined experience and insights of developers
who helped define them. They are time-tested approaches known to work
when solving specific issues in software development.

Patterns can be easily reused.


A pattern usually delivers an out-of-the-box solution you can adopt and
adapt to suit your needs. This feature makes them quite robust.

Patterns can be expressive.


Patterns can help express elegant solutions to extensive problems using a
set structure and a shared vocabulary.

Additional advantages that patterns offer are:


Patterns assist in preventing minor issues that can cause significant problems in the
application development process.
When you use established patterns to build code, you can relax about
getting the structure wrong and focus on the quality of the overall solution.
The pattern encourages you to write more structured and organized code
naturally, avoiding the need to refactor it for cleanliness in the future.

Patterns provide generalized solutions, documented in a fashion that doesn’t require


them to be tied to a specific problem.
This generalized approach means you can apply design patterns to improve
code structure regardless of the application (and, in many cases, the
programming language).

Some patterns can decrease the overall code file-size footprint by avoiding
repetition.
Design patterns encourage developers to look more closely at their
solutions for areas where they can achieve instant reductions in
duplication. For example, you can reduce the number of functions
performing similar processes in favor of a single generalized function to
decrease the size of your codebase. This is also known as making code
more dry.
Patterns add to a developer’s vocabulary, which makes communication faster.
Developers can reference the pattern when communicating with their
team, discussing it in the design patterns community, or indirectly when
another developer later maintains the code.

Popular design patterns can be improvised further by harnessing the collective


experiences of developers using those patterns and contributing back to the
community.
In some cases, this leads to the creation of entirely new design patterns,
while in others, it can lead to improved guidelines on the usage of specific
patterns. This can ensure that pattern-based solutions continue to become
more robust than ad hoc ones.

NOTE
Patterns are not exact solutions. The role of a pattern is merely to provide us with a solution
scheme. Patterns don’t solve all design problems nor replace good software designers. You still need
sound designers to choose the correct patterns that can enhance the overall design.

An everyday use case for design patterns


If you have used React.js, you have probably come across the Provider pattern. If
not, you may have experienced the following situation.
The component tree in web applications often needs access to shared data like user
information or user access permissions. The traditional way to do this in JavaScript
is to set these properties for the root level component and then pass them down
from parent to child components. As the component hierarchy deepens and
becomes more nested, you drill down it with your data resulting in the practice of
prop-drilling. This leads to unmaintainable code where the property setting and
passing will get repeated in every child component, which relies on that data.
React and a few other frameworks address this problem using the Provider Pattern.
With the Provider pattern, the React Context API can broadcast the state/data to
multiple components via a context provider. Child components needing the shared
data can tap into this provider as a context consumer or use the useContext Hook.
This is an excellent example of a design pattern used to optimize the solution to a
very common problem. We will cover this and many such patterns in a lot of detail
in this book.
Summary
With that introduction to the importance of design patterns and their relevance to
modern JavaScript, we can now deep dive into learning JavaScript Design Patterns.
The first few chapters in this book talk about structuring and classifying patterns
and identifying anti-patterns before we go into the specifics of design patterns for
JavaScript. But first, let us see what it takes for a proposed “proto-pattern” to be
recognized as a pattern in the next chapter.
Chapter 2. “Pattern”-ity Testing, Proto-
Patterns, and the Rule of Three

A NOTE FOR EARLY RELEASE READERS


With Early Release ebooks, you get books in their earliest form—the author’s
raw and unedited content as they write—so you can take advantage of these
technologies long before the official release of these titles.
This will be the 2nd chapter of the final book.
If you have comments about how we might improve the content and/or
examples in this book, or if you notice missing material within this chapter,
please reach out to the editor at [email protected].

From the moment a new pattern is proposed to its potential widespread adoption, a
pattern may have to go through multiple rounds of deep inspection by the design
community and software developers. This chapter talks about this journey of a
newly introduced “Proto-Pattern” through a “pattern”-ity test till it is eventually
recognized as a pattern if it meets the Rule of Three.
This and the next chapter explore the approach to structuring, writing, presenting,
and reviewing nascent design patterns. If you’d prefer to learn established design
patterns first, you can skip these two chapters for the time being.

What are Proto-Patterns?


Remember that not every algorithm, best practice, or solution represents what
might be considered a complete pattern. There may be a few key ingredients
missing, and the pattern community is generally wary of something claiming to be
one without an extensive and critical evaluation. Even if something is presented to
us which appears to meet the criteria for a pattern, we should not consider it as one
until it has undergone suitable periods of scrutiny and testing by others.
Looking back upon Alexander’s work once more, he claims that a pattern should
both be a process and a “thing”. This definition is obtuse as he follows by saying
that it is the process that should create the “thing”. This is why patterns generally
focus on addressing a visually identifiable structure; we should be able to visually
depict (or draw) a picture representing the structure resulting from placing the
pattern into practice.
The “Pattern” Tests
You may often come across the term “proto-pattern” when studying design patterns.
What is this? Well, a pattern that has not yet conclusively passed the “pattern”-ity
tests is usually referred to as a proto-pattern. Proto-patterns may result from the
work of someone who has established a particular solution worthy of sharing with
the community. However, due to its relatively young age, the community has not
had the opportunity to vet the proposed solution suitably.
Alternatively, the individual(s) sharing the pattern may not have the time or interest
in going through the “pattern”-ity process and might release a short description of
their proto-pattern instead. Brief descriptions or snippets of this type of pattern are
known as patlets.
The work involved in comprehensively documenting a qualified pattern can be pretty
daunting. Looking back at some of the earliest work in the field of design patterns, a
pattern may be considered “good” if it does the following:
Solves a particular problem.
Patterns are not supposed to just capture principles or strategies. They
need to capture solutions. This is one of the most essential ingredients for
a good pattern.

Does not have an obvious solution.


We can find that problem-solving techniques often attempt to derive from
well-known first principles. The best design patterns usually provide
solutions to issues indirectly—this is considered a necessary approach for
the most challenging problems related to design.

Describes a proven concept.


Design patterns require proof that they function as described, and without
this proof, the design cannot be seriously considered. If a pattern is highly
speculative in nature, only the brave will attempt to use it.

Describes a relationship.
In some cases, it may appear that a pattern describes a type of module.
Despite what the implementation looks like, the official description of the
pattern must describe much deeper system structures and mechanisms
that explain its relationship to code.

We would be forgiven for thinking that a proto-pattern that fails to meet guidelines
isn’t worth learning from; however, this is far from the truth. Many proto-patterns
are actually quite good. I am not saying that all proto-patterns are worth looking at,
but there are quite a few useful ones in the wild that could assist us with future
projects. Use your best judgment with the above list in mind, and you’ll be fine in
your selection process.

Rule of Three
One of the additional requirements for a pattern to be valid is that they display
some recurring phenomenon. You can often qualify this in at least three key areas,
referred to as the rule of three. To show recurrence using this rule, one must
demonstrate:
Fitness of purpose
How is the pattern considered successful?

Usefulness
Why is the pattern considered successful?

Applicability
Is the design worthy of being a pattern because it has broader
applicability? If so, this needs to be explained. When reviewing or defining
a pattern, it is vital to keep the above in mind.

Summary
This chapter has shown how every proposed proto-pattern may not always be
accepted as a pattern. The next chapter shares the essential elements and best
practices for structuring and documenting patterns so the community can easily
understand and consume them.
Chapter 3. Structuring and Writing
Patterns

A NOTE FOR EARLY RELEASE READERS


With Early Release ebooks, you get books in their earliest form—the author’s
raw and unedited content as they write—so you can take advantage of these
technologies long before the official release of these titles.
This will be the 3rd chapter of the final book.
If you have comments about how we might improve the content and/or
examples in this book, or if you notice missing material within this chapter,
please reach out to the editor at [email protected].

The success of a new idea depends on its utility and also on how you present it to
those it is trying to help. For developers to understand and adopt a design pattern,
it should be presented with relevant information about the context, circumstances,
prerequisites, and significant examples. This chapter applies to those trying to
understand a specific pattern and those trying to introduce a new one as it provides
essential information on how patterns are structured and written.

The Structure of a Design Pattern


Pattern authors would be unable to successfully create and publish a pattern if they
cannot define its purpose. Similarly, developers will find understanding or
implementing a pattern challenging if they do not have a background or context.
Pattern authors must outline a new pattern’s design, implementation, and purpose.
Authors initially present a new pattern in the form of a rule that establishes a
relationship between:

A context
A system of forces that arises in that context
A configuration that allows these forces to resolve themselves in
context
With this in mind, let‘s now summarize the component elements for a design
pattern. A design pattern should have the following, with the first five elements
being the most important:
Pattern name
A unique name representative of the purpose of the pattern

Description
A brief description of what the pattern helps achieve.

Context outline
The contexts in which the pattern effectively responds to its users’ needs.

Problem statement
A statement of the problem addressed so that we understand the pattern’s
intent.

Solution
A description of how the user’s problem is solved in an understandable list
of steps and perceptions.

Design
A description of the pattern’s design and, in particular, the user’s behavior
in interacting with it.

Implementation
A guide to how developers would implement the pattern.

Illustrations
Visual representations of classes in the pattern (e.g., a diagram).

Examples
Implementations of the pattern in a minimal form.

Corequisites
What other patterns may be needed to support the use of the pattern
being described?

Relations
What patterns does this pattern resemble? Does it closely mimic any
others?
Known usage
Is the pattern being used in the wild? If so, where and how?

Discussions
The team or author’s thoughts on the exciting benefits of the pattern.

Well Written Patterns


Understanding the structure and purpose of a design pattern can help us gain a
deeper appreciation for the reasoning behind why a pattern is needed. It also helps
us evaluate the pattern for our own needs.
A good pattern should ideally provide a substantial quantity of reference material for
end users. Patterns should also provide evidence of why they are necessary.
Just having an overview of a pattern is not enough to help us identify them in the
code we may encounter day-to-day. It’s not always clear if a piece of code we’re
looking at follows a set pattern or accidentally resembles one.
If you suspect that the code you see uses a pattern, consider writing down some
aspects of the code that fall under a particular existing pattern or set of patterns. It
may be that the code follows sound principles and design practices that
coincidentally overlap with the rules for a specific pattern.

TIP
Solutions in which neither interactions nor defined rules appear are not patterns.

Although patterns may have a high initial cost in the planning and write-up phases,
the value returned from that investment can be worth it. Patterns are valuable
because they help to get all the developers in an organization or team on the same
page when creating or maintaining solutions. If you are considering working on a
pattern of your own, research beforehand, as you may find it more beneficial to use
or extend existing, proven patterns rather than starting afresh.

Writing a pattern
If you are trying to develop a design pattern yourself, I recommend learning from
others who have already been through the process and done it well. Spend time
absorbing the information from several different design pattern descriptions and
take in what’s meaningful to you. Explore structure and semantics—you can do this
Random documents with unrelated
content Scribd suggests to you:
Dense Stars
The agreement of the observational points with the curve is
remarkably close, considering the rough nature of the observational
measurements; and it seems to afford a rather strong confirmation of
the theory. But there is one awful confession to make—we have
compared the theory with the wrong stars. At least when the
comparison was first made at the beginning of 1924 no one
entertained any doubt that they were the wrong stars.
We must recall that the theory was developed for stars in the
condition of a perfect gas. In the right half of Fig. 7 the stars
represented are all diffuse stars; Capella with a mean density about
equal to that of the air in this room may be taken as typical. Material
of this tenuity is evidently a true gas, and in so far as these stars
agree with the curve the theory is confirmed. But in the left half of the
diagram we have the Sun whose material is denser than water,
Krueger 60 denser than iron, and many other stars of the density
usually associated with solid or liquid matter. What business have
they on the curve reserved for a perfect gas? When these stars were
put into the diagram it was not with any expectation that they would
agree with the curve; in fact, the agreement was most annoying.
Something very different was being sought for. The idea was that the
theory might perhaps be trusted on its own merits with such
confirmation as the diffuse stars had already afforded; then by
measuring how far these dense stars fell below the curve we should
have definite information as to how great a deviation from a perfect
gas occurred at any given density. According to current ideas it was
expected that the sun would fall three or four magnitudes below the
curve, and the still denser Krueger 60 should be nearly ten
magnitudes below.[8] You see that the expectation was entirely
unfulfilled.
The shock was even greater than I can well indicate to you,
because the great drop in brightness when the star is too dense to
behave as a true gas was a fundamental tenet in our conception of
stellar evolution. On the strength of it the stars had been divided into
two groups known as giants and dwarfs, the former being the
gaseous stars and the latter the dense stars.
Two alternatives now lie before us. The first is to assume that
something must have gone wrong with our theory; that the true curve
for gaseous stars is not as we have drawn it, but runs high up on the
left of the diagram so that the Sun, Krueger 60, &c., are at the
appropriate distances below it. In short, our imaginary critic was
right; Nature had hidden something unexpected inside the star and
so frustrated our calculations. Well, if this were so, it would be
something to have found it out by our investigations.
The other alternative is to consider this question—Is it impossible
that a perfect gas should have the density of iron? The answer is
rather surprising. There is no earthly reason why a perfect gas
should not have a density far exceeding iron. Or it would be more
accurate to say, the reason why it should not is earthly and does not
apply to the stars.
The sun’s material, in spite of being denser than water, really is a
perfect gas. It sounds incredible, but it must be so. The feature of a
true gas is that there is plenty of room between the separate
particles—a gas contains very little substance and lots of emptiness.
Consequently when you squeeze it you do not have to squeeze the
substance; you just squeeze out some of the waste space. But if you
go on squeezing, there comes a time when you have squeezed out
all the empty space; the atoms are then jammed in contact and any
further compression means squeezing the substance itself, which is
quite a different proposition. So as you approach that density the
compressibility characteristic of a gas is lost and the matter is no
longer a proper gas. In a liquid the atoms are nearly in contact; that
will give you an idea of the density at which the gas loses its
characteristic compressibility.
The big terrestrial atoms which begin to jam at a density near that
of the liquid state do not exist in the stars. The stellar atoms have
been trimmed down by the breaking off of all their outer electrons.
The lighter atoms are stripped to the bare nucleus—of quite
insignificant size. The heavier atoms retain a few of the closer
electrons, but have not much more than a hundredth of the diameter
of a fully arrayed atom. Consequently we can go on squeezing ever
so much more before these tiny atoms or ions jam in contact. At the
density of water or even of platinum there is still any amount of room
between the trimmed atoms; and waste space remains to be
squeezed out as in a perfect gas.
Our mistake was that in estimating the congestion in the stellar
ball-room we had forgotten that crinolines are no longer in fashion.
It was, I suppose, very blind of us not to have foreseen this result,
considering how much attention we had been paying to the
mutilation of the atoms in other branches of the investigation. By a
roundabout route we have reached a conclusion which is really very
obvious. And so we conclude that the stars on the left of the diagram
are after all not the ‘wrong’ stars. The sun and other dense stars are
on the perfect gas curve because their material is perfect gas.
Careful investigation has shown that in the small stars on the
extreme left of Fig. 7 the electric charges of the atoms and electrons
bring about a slight deviation from the ordinary laws of a gas; it has
been shown by R. H. Fowler that the effect is to make the gas not
imperfect but superperfect—it is more easily compressed than an
ordinary gas. You will notice that on the average the stars run a little
above the curve on the left of Fig. 7. It is probable that the deviation
is genuine and is partly due to superperfection of the gas; we have
already seen that imperfection would have brought them below the
curve.
Even at the density of platinum there is plenty of waste space, so
that in the stars we might go on squeezing stellar matter to a density
transcending anything known on the earth. But that’s another story—
I will tell it later on.
The general agreement between the observed and predicted
brightness of the stars of various masses is the main test of the
correctness of our theories of their internal constitution. The
incidence of their masses in a range which is especially critical for
radiation pressure is also valuable confirmation. It would be an
exaggeration to claim that this limited success is a proof that we
have reached the truth about the stellar interior. It is not a proof, but
it is an encouragement to work farther along the line of thought
which we have been pursuing. The tangle is beginning to loosen.
The more optimistic may assume that it is now straightened out; the
more cautious will make ready for the next knot. The one reason for
thinking that the real truth cannot be so very far away is that in the
interior of a star, if anywhere, the problem of matter is reduced to its
utmost simplicity; and the astronomer is engaged on what is
essentially a less ambitious problem than that of the terrestrial
physicist to whom matter always appears in the guise of electron
systems of the most complex organization.
We have taken the present-day theories of physics and pressed
them to their remotest conclusions. There is no dogmatic intention in
this; it is the best means we have of testing them and revealing their
weaknesses if any.
In ancient days two aviators procured to themselves wings.
Daedalus flew safely through the middle air and was duly honoured
on his landing. Icarus soared upwards to the sun till the wax melted
which bound his wings and his flight ended in fiasco. In weighing
their achievements, there is something to be said for Icarus. The
classical authorities tell us that he was only ‘doing a stunt’, but I
prefer to think of him as the man who brought to light a serious
constructional defect in the flying-machines of his day. So, too, in
Science. Cautious Daedalus will apply his theories where he feels
confident they will safely go; but by his excess of caution their hidden
weaknesses remain undiscovered. Icarus will strain his theories to
the breaking-point till the weak joints gape. For the mere adventure?
Perhaps partly; that is human nature. But if he is destined not yet to
reach the sun and solve finally the riddle of its constitution, we may
at least hope to learn from his journey some hints to build a better
machine.
LECTURE II
SOME RECENT INVESTIGATIONS

I T will help us to appreciate the astronomical significance of what


we have learnt in the previous lecture if we turn from the general to
the particular and see how it applies to individual stars. I will take
two stars round which centre stories of special interest, and relate
the history of our knowledge of them.
The Story of Algol
This is a detective story, which we might call ‘The Missing Word
and the False Clue’.
In astronomy, unlike many sciences, we cannot handle and probe
the objects of our study; we have to wait passively and receive and
decode the messages that they send to us. The whole of our
information about the stars comes to us along rays of light; we watch
and try to understand their signals. There are some stars which
seem to be sending us a regular series of dots and dashes—like the
intermittent light from a lighthouse. We cannot translate this as a
morse code; nevertheless, by careful measurement we disentangle a
great deal of information from the messages. The star Algol is the
most famous of these ‘variable stars’. We learn from the signals that
it is really two stars revolving round each other. Sometimes the
brighter of the two stars is hidden, giving a deep eclipse or ‘dash’;
sometimes the faint star is hidden, giving a ‘dot’. This recurs in a
period of 2 days 21 hours—the period of revolution of the two stars.
There was a great deal more information in the message, but it
was rather tantalizing. There was, so to speak, just one word
missing. If we could supply that word the message would give full
and accurate particulars as to the size of the system—the diameters
and masses of the two components, their absolute brightness, the
distance between them, their distance from the sun. Lacking the
word the message told us nothing really definite about any of these
things.
In these circumstances astronomers would scarcely have been
human if they had not tried to guess the missing word. The word
should have told us how much bigger the bright star was than the
fainter, that is to say, the ratio of the masses of the two stars. Some
of the less famous variable stars give us complete messages.
(These could accordingly be used for testing the relation of mass
and absolute brightness, and are represented by triangles in Fig. 7.)
The difficulty about Algol arose from the excessive brightness of the
bright component which swamped and made illegible the more
delicate signals from the faint component. From the other systems
we could find the most usual value of the mass ratio, and base on
that a guess as to its probable value for Algol. Different authorities
preferred slightly different estimates, but the general judgement was
that in systems like Algol the bright component is twice as massive
as the faint component. And so the missing word was assumed to be
‘two’; on this assumption the various dimensions of the system were
worked out and came to be generally accepted as near the truth.
That was sixteen years ago.[9]
In this way the sense of the message was made out to be that
the brighter star had a radius of 1,100,000 kilometres (one and a half
times the sun’s radius), that it had half the mass of the sun, and thirty
times the sun’s light-power, &c. It will be seen at once that this will
not fit our curve in Fig. 7; a star of half the sun’s mass ought to be
very much fainter than the sun. It was rather disconcerting to find so
famous a star protesting against the theory; but after all the theory is
to be tested by comparison with facts and not with guesses, and the
theory might well have a sounder basis than the conjecture as to the
missing word. Moreover, the spectral type of Algol is one that is not
usually associated with low mass, and this cast some suspicion on
the accepted results.
If we are willing to trust the theory given in the last lecture we can
do without the missing word. Or, to put it another way, we can try in
succession various guesses instead of ‘two’ until we reach one that
gives the bright component a mass and luminosity agreeing with the
curve in Fig. 7. The guess ‘two’ gives, as we have seen, a point
which falls a long way from the curve. Alter the guess to ‘three’ and
recalculate the mass and brightness on this assumption; the
corresponding point is now somewhat nearer to the curve. Continue
with ‘four’, ‘five’, &c.; if the point crosses the curve we know that we
have gone too far and must take an intermediate value in order to
reach the desired agreement. This was done in November 1925, and
it appeared that the missing word must be ‘five’, not ‘two’—a rather
startling change. And now the message ran—
Radius of bright component = 2,140,000 kilometres.
Mass of bright component = 4·3 x sun’s mass.
If you compare these with the original figures you will see that
there is a great alteration. The star is now assigned a large mass
much more appropriate to a B-type star. It also turns out that Algol is
more than a hundred times as bright as the sun; and its parallax is
0·028"—twice the distance previously supposed.
At the time there seemed little likelihood that these conclusions
could be tested. Possibly the prediction as to the parallax might be
proved or disproved by a trigonometrical determination; but it is so
small as to be almost out of range of reasonably accurate
measurement. We could only adopt a ‘take it or leave it’ attitude—‘If
you accept the theory, this is what Algol is like; if you distrust the
theory, these results are of no interest to you.’
But meanwhile two astronomers at Ann Arbor Observatory had
been making a search for the missing word by a remarkable new
method. They had in fact found the word and published it a year
before, but it had not become widely known. If a star is rotating, one
edge or ‘limb’ is coming towards us and the other going away from
us. We can measure speeds towards us or away from us by means
of the Doppler effect on the spectrum, obtaining a definite result in
miles per second. Thus we can and do measure the equatorial
speed of rotation of the sun by observing first the east limb then the
west limb and taking the difference of velocity shown. That is all very
well on the sun, where you can cover up the disk except the special
part that you want to observe; but how can you cover up part of a
star when a star is a mere point of light? You cannot; but in Algol the
covering up is done for you. The faint component is your screen. As
it passes in front of the bright star there is a moment when it leaves a
thin crescent showing on the east and another moment when a thin
crescent on the west is uncovered. Of course, the star is too far
away for you actually to see the crescent shape, but at these
moments you receive light from the crescents only, the rest of the
disk being hidden. By seizing these moments you can make the
measurements just as though you had manipulated the screen
yourself. Fortunately the speed of rotation of Algol is large and so
can be measured with relatively small error. Now multiply the
equatorial velocity by the period of rotation;[10] that will give you the
circumference of Algol. Divide by 6·28, and you have the radius.
That was the method developed by Rossiter and McLaughlin.
The latter who applied it to Algol found the radius of the bright
component to be
2,180,000 kilometres.
So far as can be judged his result has considerable accuracy;
indeed it is probable that the radius is now better known than that of
any other star except the sun. If you will now turn back to p. 44 and
compare it with the value found from the theory you will see that
there is cause for satisfaction. McLaughlin evaluated the other
constants and dimensions of the system; these agree equally well,
but that follows automatically because there was only one missing
word to be supplied. In both determinations the missing word or
mass ratio turned out to be 5·0.
This is not quite the end of the story. Why had the first guess at
the mass ratio gone so badly wrong? We understand by now that a
disparity in mass is closely associated with a disparity in brightness
of the two stars. The disparity in brightness was given in Algol’s
original message; it informed us that the faint component gives about
one-thirteenth of the light of the bright one. (At least that was how we
interpreted it.) According to our curve this corresponds to a mass
ratio 2½, which is not much improvement on the original guess 2.
For a mass ratio 5 the companion ought to have been much fainter—
in fact its light should have been undetectable. Although
considerations like these could not have had much influence on the
original guess, they seemed at first to reassure us that there was not
very much wrong with it.
Let us call the bright component Algol A and the faint component
Algol B. Some years ago a new discovery was made, namely Algol
C. It was found that Algol A and B together travel in an orbit round a
third star in a period of just under two years—at least they are
travelling round in this period, and we must suppose that there is
something present for them to revolve around. Hitherto we had
believed that when Algol A was nearly hidden at the time of deepest
eclipse all the remaining light must come from Algol B; but now it is
clear that it belongs to Algol C, which is always shining without
interference. Consequently the mass ratio 2½ is that of Algol A to
Algol C. The light from Algol B is inappreciable as it should be for a
mass ratio 5.[11]
The message from Algol A and B was confused, not only on
account of the missing word, but because a word or two of another
message from Algol C had got mixed up with it; so that even when
the missing word was found to be ‘five’ and confirmed in two ways,
the message was not quite coherent. In another place the message
seemed to waver and read ‘two-and-a-half’. The finishing step is the
discovery that ‘two-and-a-half’ belongs to a different message from a
previously unsuspected star, Algol C. And so it all ends happily.
The best detective is not infallible. In this story our astronomical
detective made a reasonable but unsuccessful guess near the
beginning of the case. He might have seen his error earlier, only
there was a false clue dropped by a third party who happened to be
present at the crime, which seemed to confirm the guess. This was
very unlucky. But it makes all the better detective story of it.
The Story of the Companion of Sirius
The title of this detective story is ‘The Nonsensical Message’.
Sirius is the most conspicuous star in the sky. Naturally it was
observed very often in early days, and it was used by astronomers
along with other bright stars to determine time and set the clocks by.
It was a clock star, as we say. But it turned out that it was not at all a
good clock; it would gain steadily for some years, and then lose. In
1844 Bessel found out the cause of this irregularity; Sirius was
describing an elliptic orbit. Obviously there must be something for it
to move around, and so it came to be recognized that there was a
dark star there which no one had ever seen. I doubt whether any one
expected it would ever be seen. The Companion of Sirius was, I
believe, the first invisible star to be regularly recognized. We ought
not to call such a star hypothetical. The mechanical properties of
matter are much more crucial than the accidental property of being
visible; we do not consider a transparent pane of glass ‘hypothetical’.
There was near Sirius something which exhibited the most universal
mechanical property of matter, namely, exerting force on
neighbouring matter according to the law of gravitation. That is better
evidence of the existence of a material mass than ocular evidence
would be.
However, eighteen years later the Companion of Sirius was
actually seen by Alvan Clark. This discovery was unique in its way;
Clark was not looking at Sirius because he was interested in it, but
because Sirius was a nice bright point of light with which to test the
optical perfection of a large new object-glass that his firm had made.
I dare say that when he saw the little point of light close to Sirius he
was disappointed and tried to polish it away. However, it stayed, and
proved to be the already known but hitherto unseen Companion.
The big modern telescopes easily show the star and rather spoil
the romance; but as romance faded, knowledge grew, and we now
know that the Companion is a star not much less massive than the
sun. It has ⅘ths of the mass of the sun, but gives out only ¹⁄₃₆₀th of
the sun’s light. The faintness did not particularly surprise us;[11]
presumably there should be white-hot stars glowing very brightly and
red-hot stars glowing feebly, with all sorts of intermediate degrees of
brightness. It was assumed that the Companion was one of the
feeble stars only just red hot.
In 1914 Professor Adams at the Mount Wilson Observatory found
that it was not a red star. It was white—white hot. Why, then, was it
not shining brilliantly? Apparently the only answer was that it must be
a very small star. You see, the nature and colour of the light show
that its surface must be glowing more intensely than the sun’s; but
the total light is only ¹⁄₃₆₀th of the sun’s; therefore the surface must
be less than ¹⁄₃₆₀th of the sun’s. That makes the radius less than
¹⁄₁₉th of the sun’s radius, and brings the globe down to a size which
we ordinarily associate with a planet rather than with a star. Working
out the sum more accurately we find that the Companion of Sirius is
a globe intermediate in size between the earth and the next larger
planet Uranus. But if you are going to put a mass not much less than
that of the sun into a globe not very much larger than the earth, it will
be a tight squeeze. The actual density works out at 60,000 times that
of water—just about a ton to the cubic inch.
We learn about the stars by receiving and interpreting the
messages which their light brings to us. The message of the
Companion of Sirius when it was decoded ran: ‘I am composed of
material 3,000 times denser than anything you have ever come
across; a ton of my material would be a little nugget that you could
put in a match-box.’ What reply can one make to such a message?
The reply which most of us made in 1914 was—‘Shut up. Don’t talk
nonsense.’
But in 1924 the theory described in the last lecture had been
developed; and you will remember that at the end it pointed to the
possibility that matter in the stars might be compressed to a density
much transcending our terrestrial experience. This called back to
mind the strange message of the Companion of Sirius. It could no
longer be dismissed as obvious nonsense. That does not mean that
we could immediately assume it to be true; but it must be weighed
and tested with a caution which we should not care to waste over a
mere nonsense jingle.
It should be understood that it was very difficult to explain away
the original message as a mistake. As to the mass being ⅘ths of the
sun’s mass there can be no serious doubt at all. It is one of the very
best determinations of stellar mass. Moreover, it is obvious that the
mass must be large if it is to sway Sirius out of its course and upset
its punctuality as a clock. The determination of the radius is less
direct, but it is made by a method which has had conspicuous
success when applied to other stars. For example, the radius of the
huge star Betelgeuse was first calculated in this way; afterwards it
was found possible to measure directly the radius of Betelgeuse by
means of an interferometer devised by Michelson, and the direct
measurement confirmed the calculated value. Again the Companion
of Sirius does not stand alone in its peculiarity. At least two other
stars have sent us messages proclaiming incredibly high density;
and considering our very limited opportunities for detecting this
condition, there can be little doubt that these ‘white dwarfs’, as they
are called, are comparatively abundant in the stellar universe.
But we do not want to trust entirely to one clue lest it prove false
in some unsuspected way. Therefore in 1924 Professor Adams set
to work again to apply to the message a test which ought to be
crucial. Einstein’s theory of gravitation indicates that all the lines of
the spectrum of a star will be slightly displaced towards the red end
of the spectrum as compared with the corresponding terrestrial lines.
On the sun the effect is almost too small to be detected having
regard to the many causes of slight shift which have to be
disentangled. To me personally Einstein’s theory gives much
stronger assurance of the real existence of the effect than does the
observational evidence available. Still it is a striking fact that those
who have made the investigation are now unanimous in their
judgement that the effect really occurs on the sun, although some of
them at first thought that they had evidence against it. Hitherto
Einstein’s theory has been chiefly regarded by the practical
astronomer as something he is asked to test; but now the theory has
a chance to show its mettle by helping us to test something much
more doubtful than itself. The Einstein effect is proportional to the
mass divided by the radius of the star; and since the radius of the
Companion of Sirius is very small (if the message is right) the effect
will be very large. It should in fact be thirty times as large as on the
sun. That lifts it much above all the secondary causes of shift of the
lines which made the test on the sun so uncertain.
The observation is very difficult because the Companion of Sirius
is faint for work of this kind, and scattered light from its
overpoweringly brilliant neighbour causes much trouble. However,
after a year’s effort Professor Adams made satisfactory
measurements, and he found a large shift as predicted. Expressing
the results in the usual unit of kilometres per second, the mean of his
measurements came to 19, whilst the predicted shift was 20.
Professor Adams has thus killed two birds with one stone. He has
carried out a new test of Einstein’s general theory of relativity, and he
has shown that matter at least 2,000 times denser than platinum is
not only possible but actually exists in the stellar universe.[13] This is
the best confirmation we could have for our view that the sun with a
density 1½ times that of water is still very far indeed from the
maximum density of stellar matter; and it is therefore entirely
reasonable that we should find it behaving like a perfect gas.
I have said that the observation was exceedingly difficult.
However experienced the observer, I do not think we ought to put
implicit trust in a result which strains his skill to the utmost until it has
been verified by others working independently. Therefore you should
for the present make the usual reservations in accepting these
conclusions. But science is not just a catalogue of ascertained facts
about the universe; it is a mode of progress, sometimes tortuous,
sometimes uncertain. And our interest in science is not merely a
desire to hear the latest facts added to the collection; we like to
discuss our hopes and fears, probabilities and expectations. I have
told the detective story so far as it has yet unrolled itself. I do not
know whether we have reached the last chapter.
Unknown Atoms and Interpretation of
Spectra
It should be understood that this matter of enormous density is
not supposed to be any strange substance—a new chemical
element or elements. It is just ordinary matter smashed about by the
high temperature and so capable of being packed more tightly—just
as more people could be squeezed into a room if a few bones were
broken. It is one of the features of astronomical physics that it shows
us the ordinary elements of the earth in an extraordinary state—
smashed or ionized to a degree that has either not been reproduced
or has been reproduced with great difficulty in the laboratory. It is not
only in the inaccessible interior of the star that we find matter in a
state outside terrestrial experience.
Here is a picture of the Ring Nebula in Lyra (Fig. 8).[14] It is taken
through a prism so that we see not one ring but a number of rings
corresponding to different lines of the spectrum and representing the
different kinds of atoms which are at work producing the light of the
nebula. The smallest ring, which is rather faint (marked by an arrow),
consists of light produced by the helium atoms in the nebula—not
ordinary helium but smashed helium atoms. It was one of the great
laboratory achievements of recent times when Professor A. Fowler in
1912 succeeded in battering helium atoms in a vacuum tube
sufficiently to give this kind of light, already well known in the stars.
Two other rings are due to hydrogen. With these three exceptions
none of the rings have yet been imitated in the laboratory. For
instance, we do not know what elements are producing the two
brightest rings on the extreme right and left respectively.
We are sometimes asked whether any new elements show
themselves in the stars which are not present or are not yet
discovered on the earth. We can give fairly confidently the answer
No. That, however, is not because everything seen in the stars has
been identified with known terrestrial elements. The answer is in fact
given not by the astronomer but by the physicist. The latter has been
able to make out the orderly scheme of the elements; and it
transpires that there are no gaps left for fresh elements until we
come to elements of very high atomic weight, which would not be
likely to rise into the atmosphere of a star and show themselves in
astronomical observation. Every element carries a number, starting
with hydrogen which is No. 1, and going up to uranium which is No.
92.

Fig. 8. THE RING NEBULA IN LYRA

Fig. 9. HYDROGEN—THE BALMER SERIES


And what is more, the element carries its number-plate so
conspicuously that a physicist is able to read it. He can, for instance,
see that iron is No. 26 without having to count up how many known
elements precede it. The elements have been called over by their
numbers, and up to No. 84 they have all answered ‘Present’.[15]
The element helium (No. 2) was first discovered by Lockyer in the
sun, and not until many years later was it found on the earth.
Astrophysicists are not likely to repeat this achievement; they cannot
discover new elements if there aren’t any. The unknown source of
the two rings close together on the right of the photograph (a bright
ring and a fainter ring) has been called nebulium. But nebulium is not
a new element. It is some quite familiar element which we cannot
identify because it has lost several of its electrons. An atom which
has lost an electron is like a friend who has shaved off his
moustache; his old acquaintances do not recognize him. We shall
recognize nebulium some day. The theoretical physicists are at work
trying to find laws which will determine exactly the kind of light given
off by atoms in various stages of mutilation—so that it will be purely
a matter of calculation to infer the atom from the light it emits. The
experimental physicists are at work trying more and more powerful
means of battering atoms, so that one day a terrestrial atom will be
stimulated to give nebulium light. It is a great race; and I do not know
which side to back. The astronomer cannot do much to help the
solution of the problem he has set. I believe that if he would measure
with the greatest care the ratio of intensity of the two nebulium lines
he would give the physicists a useful hint. He also provides another
clue—though it is difficult to make anything of it—namely, the
different sizes of the rings in the photograph, showing a difference in
the distribution of the emitting atoms. Evidently nebulium has a
fondness for the outer parts of the nebula and helium for the centre;
but it is not clear what inference should be drawn from this difference
in their habits.
The atoms of different elements, and atoms of the same element
in different states of ionization, all have distinctive sets of lines which
are shown when the light is examined through a spectroscope.
Under certain conditions (as in the nebulae) these appear as bright
lines; but more often they are imprinted as dark lines on a
continuous background. In either case the lines enable us to identify
the element, unless they happen to belong to an atom in a state of
which we have had no terrestrial experience. The rash prophecy that
knowledge of the composition of the heavenly bodies must be for
ever beyond our reach has long been disproved; and the familiar
elements, hydrogen, carbon, calcium, titanium, iron, and many
others, can be recognized in the most distant parts of the universe.
The thrill of this early discovery has now passed. But meanwhile
stellar spectroscopy has greatly extended its scope; it is no longer
chemical analysis, but physical analysis. When we meet an old
acquaintance there is first the stage of recognition; the next question
is ‘How are you?’ After recognizing the stellar atom we put this
question, and the atom answers, ‘Quite sound’ or ‘Badly smashed’,
as the case may be. Its answer conveys information as to its
environment—the severity of the treatment to which it is being
subjected—and hence leads to a knowledge of the conditions of
temperature and pressure in the object observed.
Surveying the series of stars from the coolest to the hottest, we
can trace how the calcium atoms are at first whole, then singly
ionized, then doubly ionized—a sign that the battering becomes
more severe as the heat becomes more intense. (The last stage is
indicated by the disappearance of all visible signs of calcium,
because the ion with two electrons missing has no lines in the
observable part of the spectrum.) The progressive change of other
elements is shown in a similar way. A great advance in this study
was made in 1920 by Professor M. N. Saha, who first applied the
quantitative physical laws which determine the degree of ionization
at any given temperature and pressure. He thereby struck out a new
line in astrophysical research which has been widely developed.
Thus, if we note the place in the stellar sequence where complete
calcium atoms give place to atoms with one electron missing, the
physical theory is able to state the corresponding temperature or
pressure.[16] Saha’s methods have been improved by R. H. Fowler
and E. A. Milne. One important application was to determine the
surface temperatures of the hottest types of stars (12,000°—
25,000°), since alternative methods available for cooler stars are not
satisfactory at these high temperatures. Another rather striking result
was the discovery that the pressure in the star (at the level surveyed
by the spectroscope) is only ¹⁄₁₀₀₀₀th of an atmosphere; previously it
had been assumed on no very definite evidence to be about the
same as that of our own atmosphere.
We commonly use the method of spectrum analysis when we
wish to determine which elements are present in a given mineral on
the earth. It is equally trustworthy in examining the stars since it can
make no difference whether the light we are studying comes from a
body close at hand or has travelled to us for hundreds of years
across space. But one limitation in stellar work must always be
remembered. When the chemist is looking, say, for nitrogen in his
mineral, he takes care to provide the conditions which according to
his experience are necessary for the nitrogen spectrum to show
itself. But in the stars we have to take the conditions as we find
them. If nitrogen does not appear, that is no proof that nitrogen is
absent; it is much more likely that the stellar atmosphere does not hit
off the right conditions for the test. In the spectrum of Sirius the lines
of hydrogen are exceedingly prominent and overwhelm everything
else. We do not infer that Sirius is composed mainly of hydrogen; we
infer instead that its surface is at a temperature near 10,000°,
because it can be calculated that that is a temperature most
favourable for a great development of these hydrogen lines. In the
sun the most prominent spectrum is iron. We do not infer that the
sun is unusually rich in iron; we infer that it is at a comparatively low
temperature near 6,000° favourable for the production of the iron
spectrum. At one time it was thought that the prominence of
hydrogen in Sirius and of metallic elements in the sun indicated an
evolution of the elements, hydrogen turning into heavier elements as
the star cools from the Sirian to the solar stage. There is no ground
for interpreting the observations in that way; the fading of the
hydrogen spectrum and the increase of the iron spectrum would
occur in any case as the result of the fall of temperature; and similar
spurious appearances of evolution of elements can be arranged in
the laboratory.

You might also like