About Dual Revelation In The Bible


15 OT Passages


Isaiah 45:14-19

Psalm 19 7-11

Number 23:19

Psalm 12:6

Psalm 119:160

Proverbs 30:5

2 Samuel 22:31

Psalm 19 (all)

Psalm 50:6

Psalm 89:5

Psalm 97:6

Psalm 18:10

Job 7-19

Job 16:19-21

Job 19:25-27


18 NT Passages


Col 1:15

John 14:6

Matt 22:16

Mark 12:14

Luke 20:21

John 18:37

Titus 1:2

Heb 6:18

2 Tim 2:15

James 1:18

Rom 1:18-32

John 10:35

Matt 5:18

Matt 22:29

Mark 12:24

2 Tim 3:26

Matt 4:4

2Peter 1:20-21

The above was discussed by Hugh Ross in Chapter 6 of Rescuing Inerrancy. I made a list and plan to post comments one each passage one by one. I may mention Hugh’s ideas or the ideas of others on each passage. I plan another similar post on the topic of inerrancy itself.

YEC and Nuclear Decay Rates

YEC’s tell me God changes the laws of physics in various ways and at numerous times. This seems to be a basic tenet of YEC belief.

This is demonstrated by a statement in RATE 2 as follows:


The quote was taken from the RATE2 statement. Here is the URL for RATE2: https://www.icr.org/rate2

The author suggest that YEC must question whether the laws of physics are constant. Basic laws of physics include speed of light, gravitational constant, and rate of nuclear decay. But there are also others. Strong forece, weak force, electromagnetic force, gravitational force all depend on basic laws of physics. When these change so does chemistry and biochemistry. And life.

Where did I find this? Virginia Peterson pointed this out on her comment to a post in Answers to Answers in Genesis. https://www.facebook.com/groups/answers2aig and her comment took place around July 19, 2026 in a post by Jeff Reichman.

This summer I had a discussion with YEC Chris Coatney about what do YEC advocates believe. Chris Coatney insisted God changes the laws of physics for special purposes and has done so capriciously from time to time in response to human behavior.

Chris specifically mentioned the laws of nature changing instantaneously at the fall of man, and again at the flood. And possibly more times.

These changes are allegedly a massive supernatural event that affects the entire universe, not just the earth. These ideas align with the statement in the image above taken from RATE2.

Virginia Peterson didnt identify which specific RATE2 document containing the quote. I will have to search for that in the RATE documents. The reader is invited to do so as well.

Why did this come up?

There is an AiG article by Andrew Snelling:

https://answersingenesis.org/dinosaurs/when-did-dinosaurs-live/review-dinosaur-blood-age-of-the-earth/dinosaur-blood-review-3/

And Jeff Reichman made a post with his take on it. And that led to a discussion where Virginia Peterson shared the RATE statements.

Also Riley Barton had written about it.
https://theevidenceisplain.blogspot.com/2026/07/the-carbon-14-paradox-why-we-trust.html

I have been following radiometric dating arguments from ICR since I was a college student. I had basically just started ignoring YEC because I decided it was a scam. Why? The image shown above which admits to old earth unless the laws of physics are vary over time.

Getting YECs to admit they believe laws of nature are variable is like pulling teeth. If they do believe it then I don’t believe them. I just don’t like being lied to. They say they care about truth. well, then they need to tell some.

What about Dino Bone Dating?

Andrew Snelling wrote articles in 2026 about this, claiming dinosaur bones have be carbon 14 dated to be recent.

Snelling references Vance Nelson and Brian Thomas in a 2015 article as follows:

Thomas, Brian, and Vance Nelson, “Radiocarbon in Dinosaur and Other Fossils,” Creation Research Society Quarterly 51 (Spring 2015): 299–311.

Here is a result of their research. Typical measurement, 3rd from the bottom, a horn of a Triceratops, dated at 40,000 BC. Does not support a 6000 year old earth.

One of my goals is to more fully understand how bones become fossilized so that carbon dating applies to their fossils.

I am frustrated that nothing is mentioned about the strata the bones were found in because if the strata is far older than the bones then this indicates an anomaly.

What minerals are in fossils?

To make fossils the following minerals can be involved.

Common minerals that replace or crystallize within ancient organic remains include:

Silica (SiO₂): Often found in petrified wood and agate. Replaces organic tissues in exquisite detail.

Calcite / Aragonite (CaCO₃): The primary building block for many marine fossils, such as ancient shells and coral.

Pyrite (FeS₂): Also known as “fool’s gold,” it can replace soft tissues and shell structures, resulting in brilliant, metallic golden fossils.

Phosphate (Apatite): Frequently replaces shark teeth and bone, giving the specimens a jet-black coloration.

Hematite / Goethite (Iron minerals): These produce rich red, brown, and orange colorations within the fossil matrix.

Sorry, I don’t have any reason to think C14 dating works on any of the fossils made of these materials.

What about anthracite (coal?). It is all carbon.

Some counter comments about Andrew Snelling.


Jeff Reichman writes, “Dr. Snelling’s entire argument hinges on a fundamental logical contradiction: he treats the presence of carbon-14 as an objective “clock” to date fossils, while simultaneously arguing that the dating system used to interpret that carbon-14 is a deceptive, “uniformitarian” construct.”

“Snelling posits that finding C-14 in dinosaur bones proves they are “only thousands of years old.” To arrive at this conclusion, he must rely on the stability of the radioactive decay constant. He needs this constant to be an immutable law of nature so that the presence of C-14 implies a specific, limited age. Yet, in the same breath, he attacks the “uniformitarian practitioners” who established that very constant, labeling their calibration curves as “biased, overinflated, and thus useless.” Snelling is caught in a trap of his own making: if the methodology and the framework established by mainstream science are truly “useless,” then by what authority does he declare the existence of C-14 to be evidence of any age? He is “borrowing” the authority of the physics he claims to reject to provide his own conclusion with a veneer of scientific legitimacy.”

“Snelling claims that the results of 30,000 to 40,000 years produced by laboratories are “inflated” and “inaccurate” due to magnetic field decay and the global Flood. By creating these ad hoc explanations to “correct” the data down to his preferred 4,500 years, he effectively admits that the machine’s output is not an objective measurement of time, but a blank slate upon which he can project his own desired history. If the clock must be adjusted by thousands of years to align with a theology, then the clock is not measuring time, it is being manipulated”

Snelling’s argument collapses into a logical vacuum. He asserts that:

— The raw detection of C-14 is “significant” and “valid evidence.”

— The dating interpretation of that same C-14 by the scientific community is “dishonest” and “erroneous.”

This is the peak of his logical inconsistency. He demands that we trust the fact of the detection while rejecting the method of the measurement. If Snelling is right, and the dating community’s assumptions about the past are “erroneous,” then he has no grounds to claim that the detection of C-14 is “significant.” A measurement from a system that is “useless” (his own words) for obtaining true ages is, by definition, useless for his argument as well. By rejecting the framework that gives the data its meaning, Snelling renders his own “evidence” scientifically vacuous. He is not using science to date a fossil; he is using an instrument as a prop to confirm a bias, then breaking the instrument the moment it fails to provide the exact answer he requires.”

Reichman next mentions something I had noticed about YEC Chris Coatney.

“Ultimately, articles like Dr. Snelling’s are far from a pursuit of truth; they are an exercise in rhetorical misdirection designed to bypass the rigor of the scientific method. By simultaneously claiming that the radiocarbon dating framework is a “biased” and “useless” uniformitarian invention while using that same framework’s physical constants to interpret trace carbon-14 as “evidence” of a young earth, Snelling engages in a profound logical fallacy. These arguments are inherently misleading because they function as a closed-loop system: they treat the machine’s sensitivity floor as a legitimate age when it supports their worldview, but dismiss the entire system as fraudulent the moment it produces a date that contradicts their theology. By rejecting the integrity of the very tools they rely upon to generate their data, such authors are not performing science; they are performing a performative dismissal of deep time, substituting an internally inconsistent “borrowed authority” for the objective search for truth.”












About DIID and EC.

Matt McClure mentioned something I didn’t know before:

The DI describes ID as “The theory of intelligent design holds that certain features of the universe and of living things are best explained by an intelligent cause, not an undirected process such as natural selection”.

Here is the part I didn’t know: That natural selection is 100% undirected.

What they mean by undirected is “Unperturbed. No perturbations.” How can they know? Lets think slightly deeper. What if there is/was a perturbation? Is it natural or unnatural? How could they know? If it was natural how do they know there was an intelligent cause versus an unintelligent cause? Again, how can they know?

What has happened is DI has made assumptions, and rolled these assumptions into the definition of DIID. And I didn’t previously know this.

I conclude that DIID is totally metaphysical because it has no epistemological basis. Therefore it cannot be scientifically falsified.

This is not my understanding of what ID was supposed to be.

What made me think about all this? The following discussion.

Matt McClure said:

I make no arguments against Divine Design because I believe it’s true. However, the problem with Discovery Institute Intelligent Design (DIID) is that it claims to be something it is not.

To be considered science, it must lend itself to empirically testable (i.e., falsifiable) hypotheses from which conclusions can be made, and no scientific conclusion can be made without the gathering and analysis of data. In contrast, Ben Stein’s quote above is an attempt to make a conclusion based on the lack of data.

The reason DIID is not science is that it begins with an unsupportable presupposition. The DI describes ID as “The theory of intelligent design holds that certain features of the universe and of living things are best explained by an intelligent cause, not an undirected process such as natural selection”. Immediately we see the problem: How do they know that a transcendent intelligent designer cannot or will not direct natural selection? How do they know that a transcendent intelligent designer cannot or will not direct ordinary natural processes in scientifically undetectable ways? How do they know? Answer: They don’t know it. They only assume it, and yet this assumption is completely unsupportable. So how can DIID possibly be science when its primary assumption is empirically unfalsifiable?

Given that the transcendent intelligent designer is God (i.e., the God of the Bible), then everything is designed whether it looks designed or not and whether it has a “naturalistic” explanation or not. So how can intelligent design possible be empirically testable when there is nothing un-designed for which to objectively compare?

The problems with DIID go beyond scientific veracity. Given that the transcendent intelligent designer is God then we can consult the Scriptures about God, and Hebrews 11:3 says “by faith we know” God did it. It does not say “by empirically based methods of inquiry we know”. Therefore, the premise that science can affirm God as Creator is inseparable from the premise that science can replace faith, and that premise is scientism. Despite the claims of Dawkins and Meyer, God is not a testable scientific hypothesis. Someone very important once said “thou shalt not put the Lord thy God to the test” and then later said “blessed are those who have not seen and yet have believed”.

ID (not necessarily DIID) is true, but ID is not science because the Designer is transcendent of nature and science is limited to the study of natural things. DIID falsely positing itself as science is the reason DIID has lost in the courts, and it is the reason why it will lose in the evangelical field as well.

My thoughts:

Here is the central question poses by the above:

“How do they know that a transcendent intelligent designer cannot or will not direct natural selection?

They don’t.

Also,
How do they know that a transcendent intelligent designer cannot or will not direct ordinary natural processes in scientifically undetectable ways?

This is a separate question because it is more general than just natural selection. It extends to all natural processes.

And the answer again is, they don’t.

To me there is yet a third question. How do they know that an intelligent designer will not perturb ordinary natural processes so they give a different outcome than ordinary natural unperturbed processes would have given?

They don’t.

So, How do they know? Answer: They don’t know it. They only assume it, and yet this assumption is completely unsupportable.

Also, how can DIID possibly be science when its primary assumption is empirically unfalsifiable?

We do know one thing. Natural processes, left to themselves, are not likely to produce the physical results we see. It would take a lot of faith to believe it could or did. And it still would not explain the non physical aspects of the universe. Love, hate, justice, fairness, etc. The intangibles which have no natural explanation but nevertheless are real.

So DIID defeats atheism. But it does not defeat EC or TE.


Matt McClure also said:

DIID does not do what science does. You need to go back and read my comment because DIID still begins on the unsupportable, unfalsifiable presupposition that a transcendent intelligent designer cannot or will not divinely guide natural processes in scientifically undetectable ways, which is especially problematic for believing Christians because that presupposition is clearly contradicted by such scriptures as Psalm 139:13-15, Proverbs 16:33, and Acts 1:26.

What about this presupposition? That DIID posits that a transcendent intelligent designer cannot or will not divinely guide natural processes in scientifically undetectable ways?

How do they know? They cannot. So they have made a terrible mistake.

Stated slightly differently, what they also cannot know is this: How is it that an intelligent designer, employing just the laws of the universe, could not perturb ordinary natural processes so these perturbed processes give a different outcome than ordinary unperturbed natural processes would have given?

Again, they cannot know. But they dismiss the idea anyway without giving a reason.

Seems to me DIID actually would support both DIID and EC equally well if they would allow that God, being in the universe can perturb natural processes.

Matt gives Psalm 139:13-15, Proverbs 16:33, and Acts 1:26 for consideration.


Psalm 139:13-15 speaks of God’s ongoing creation activity. That which takes place after the beginning.


Matt McClure Also said:

DIID does not do what science does. You need to go back and read my comment because DIID still begins on the unsupportable, unfalsifiable presupposition that a transcendent intelligent designer cannot or will not divinely guide natural processes in scientifically undetectable ways, which is especially problematic for believing Christians because that presupposition is clearly contradicted by such scriptures as Psalm 139:13-15, Proverbs 16:33, and Acts 1:

God and Individuals, Part 1


Some scriptures on God’s immanance, God working through nature.


Commentary on each verse provided by https://www.bibleref.com/

I would like to point out the use of “created” (qanah) in Psalm 139:13 is interesting. See separate post.

Psalm 139:13-15

For you created my inmost being; you knit me together in my mother’s womb.

I praise you because I am fearfully and wonderfully made;your works are wonderful,I know that full well.


My frame was not hidden from youwhen I was made in the secret place,when I was woven together in the depths of the earth.


What does Psalm 139:13 mean?

Scripture credits God with creating children long before they are physically born. David addresses God as having formed his inner being before birth. Job says something similar: “You clothed me with skin and flesh, and knit me together with bones and sinews” (Job 10:11).

We know from Genesis 1:27 that we were created in the image of God. This passage also reveals that God wove us together in the womb. We are, therefore, not a product of randomness or nature, but of God’s omnipotent handiwork. God crafted each person in his or her mother’s womb to be a distinct individual. We owe our existence to Him and not to happenstance.

Because of this, human life both before and after birth is sacred. The unborn child is not simply tissue to be discarded at the mother’s discretion. Since every human being is created in the image of God, it is a heinous sin to commit murder, whether by aborting the unborn, killing oneself, or taking someone else’s life in an act of rage. Every person, whether male or female, no matter the ethnicity, age, or political persuasion, is someone made in the image of God and known completely by Him. Believers are called upon to love even our enemies (Matthew 5:44); often that begins by first acknowledging their inherent worth as a human knit together by God.

What does Psalm 139:14 mean?

Contemplating the fact that God wove him together in his mother’s womb, David praised God for His omnipotent act of creation. He especially notes how God’s creative power is beyond human comprehension.

The human body that God created in the womb is indeed wonderfully made. For instance, the heart beats about 70 times per minute and pumps about 2,000 gallons—7,500 liters—of blood per day. An average body contains nearly 100 trillion cells. The brain contains 100 billion nerve cells. Human kidneys process daily about 130 quarts—about 123 liters—of blood to filter out waste and water. Our skeletal system has 206 bones connected to an intricate system of tendons, cartilage, and ligaments. The skeletal system not only enables us to move but also helps to produce blood, and it stores calcium.

David recognized God’s creation of man was both marvelous and distinct from the creation of everything else. No two persons are completely identical, and human beings are distinct from animals. David was fully convinced that God had fearfully and wonderfully made him. He wrote: “My soul knows it very well.”


What does Psalm 139:15 mean?

In this verse David mentions his frame was not hidden from God when God made him in secret. “My frame” signifies the strength or framework of the body, essentially meaning the skeletal structure. The expression, “in the depths of the earth,” is a poetic term that describes the womb as being just as dark and hidden from human view as the subterranean caverns.

“Woven,” as rendered in this verse, is from the Hebrew word raqam. This term refers to the skill of an embroiderer or someone skilled in needlework. God’s creation of the human body in the womb is a masterpiece of design and workmanship. Conception and gestation have been designed by God as miracles that lead to birth.

Beyond the physical wonder of the human body, every person is made in the image of God (Genesis 1:27). To murder what God creates in the womb is an attack on the image of God, as is any other murder (Genesis 9:6).

In Bible times conception and birth were occasions to celebrate. Children were considered gifts from the Lord (Psalm 127:3). When Eve conceived and bore Cain, she said, “I have gotten a man with the help of the LORD” (Genesis 4:1). When Hannah bore a son, she called him Samuel, and said, “I have asked for him from the LORD” (1 Samuel 1:20). When she had weaned Samuel, she dedicated him to service in the temple, and she offered praise to the Lord (1 Samuel 2).

Proverbs 16:33

The lot is cast into the lap,but its every decision is from the Lord.

What does Proverbs 16:33 mean?

This proverb emphasizes the Lord’s sovereign control over all things. Many common English expressions about luck relate to rolling dice. The point of dice is belief that well-balanced cubes will give a completely random result each time they are used. Casting lots in the Old Testament era might have involved one or more methods meant to seek an uncontrolled, arbitrary result. Such techniques are often used when a decision needs to be completely free from human bias (Proverbs 18:18Joshua 14:2Jonah 1:7).

The truth is that what human beings call “luck” is merely the sum of all the factors we cannot see or control. No dice roll, or casting of lots, ever takes God by surprise. Some things do happen “by chance,” from the human perspective, as even Jesus noted (Luke 10:31). That does not mean they are arbitrary or random from God’s point of view. Even those things we perceive as determined by chance are in the Lord’s control (Psalm 16:5). This proverb points out that even those things we think of as “pure chance” are still under God’s sovereign control.



Acts 1:26

Then they cast lots, and the lot fell to Matthias; so he was added to the eleven apostles.



What does Acts 1:26 mean?

One hundred twenty Jesus-followers wait in an upper room in Jerusalem for the coming of the Holy Spirit (Acts 1:515). After prayer and consideration, they have identified two men, Joseph Barsabbas and Matthias, who are qualified to replace Judas Iscariot as one of the twelve apostles. Both men witnessed Jesus’ ministry from His baptism to His resurrection (Acts 1:21–22). Now the group needs to know which one God has chosen.

The practice of casting lots was an honored tradition in Israel for determining the will of God. Unlike fortune telling or scrying, God ordained and directed the Urim and Thummim that were kept with the high priest (Leviticus 8:8). Lots were used often in the Old Testament, most importantly in dividing up the Promised Land to the twelve tribes (Joshua 18:6). In this case, the names of Joseph and Matthias are probably written on stones and placed in a jar. The jar is shaken until one of the stones comes out.

This is the last recorded case in the Bible of God’s people using lots. Within days, the Holy Spirit will come upon this room and permanently dwell inside the hearts of the people (Acts 2:1–4). As Jesus promised, the Holy Spirit will guide Jesus-followers into truth; lots are no longer needed (John 16:13).

There is great discussion as to whether God really wanted Matthias to be the twelfth apostle or if he was a placeholder until Paul was converted. Everything points to Matthias. Although Paul saw Jesus after the resurrection (1 Corinthians 9:1), he did not witness Jesus’ baptism or travel with Him during His ministry, as Peter stipulated (Acts 1:21–22). There were many godly men and women in that room, and thousands more came after God sent the Holy Spirit. Each of them had specific roles, chosen by God (Ephesians 2:10). Matthias’ role is that of an apostle.







Falling Apart Quietly

Seven ways men look stable while quietly falling apart.
From JR McGregor.

1. He functions, but he doesn’t feel alive Gets up. Works. Provides. Shows up.

Still feels numb most days. Like he’s running a life on autopilot that he never consciously chose.

2. He tells everyone he’s fine because explaining feels harder Not lying. Just tired.

If he starts talking, he doesn’t know where it will go. So he keeps it short. Keeps it light. Keeps it moving.

3. He stays busy so the silence can’t catch him Work. Gym. Projects. Fixing things that don’t matter.

As long as there’s noise, nothing has space to ask him the questions he’s avoiding.

4. He laughs a lot, but sleeps badly Easy with jokes. Easy with banter. Hard alone at night.

Mind racing. Chest tight. Thinking about everything he hasn’t said and everything he doesn’t understand about himself.

5. He’s reliable for everyone except himself Keeps promises to work. To family. To partners.

Breaks every promise he makes to his own body, his own needs, his own life. Then wonders why he feels invisible.

6. He hasn’t cried in years but feels heavy all the time Not dramatic sadness. Just a constant weight. Pressure in the chest. Short temper. Low patience.

Grief that never found a way out.

7. He has a quiet fear that this isn’t the life he’s meant to be living Not because it’s bad. Because it doesn’t feel like his.

Like he stepped into a role before he ever figured out who he actually was.

And here’s the part no one tells men.

You don’t fall apart loudly. You fall apart slowly.

By functioning. By coping. By surviving. By calling it adulthood.

If you’re reading this and felt uncomfortable instead of offended, DM me HEAL

That’s usually where a man finally admits he’s not broken… he’s just been carrying too much alone.

Todays YEC Rumors


A friend posted this:

I wrote to her the following:


My friend David Rhoads tells me the YEC people claim the laws of physics change (when it is convenient for their viewpoint). I dont know if thats true. It seems to be. He has studied this for years. So, let us assume its true. God changes the laws of physics. OK, so then tell me why God cannot tweak the DNA of 100 organisms in a species to cause 50 reproducing pairs to suddenly exist to make a new species?

If God can and does change the laws of physics WHY cant he spawn a new species every day of the week?

Keep in mind the YEC claim is that the ENTIRE COSMOS had the laws of physics changed the first few days of creation and also changed the day Adam sinned.

Their claim is the speed of light everywhere changed.

Well, thats waaaaaaayyyyyy bigger of an effect on the universe than making a new species would be on tiny little earth.

So I am having a hard time understanding why god cannot do macroevolution.

I dont believe in naturalistic macro-evolution. I believe in theistic-macro-evolution. So to me what we seen in the natural world and what we see in the bible is One-Seamless-Truth.

So….”Evolution requires a lot more faith than the Creator view”… why do the YEC people limit God’s power? They believe God cannot do evolution. He is constrained to only being able to do creative acts at the beginning. Even if it means he changed all the physical laws of the universe. But during history? Oh, well, he is not allowed to tweak biology.

So I think this evolution versus theology idea seems to be a false dichotomy invented in the middle of the 19th century.

If we believe God can heal people and can resurrect people, why cant he make new species? I don’t get it. I used to go visit Henry Morris at his school in San Diego. I believed his world view. But now it doesnt make any sense.

Naturalism of the Gaps

Francis Collins writes,

Science is not the only way of knowing. The spiritual worldview finds another way of finding truth. scientists who deny this would be well advised to observe the limits of their own tools, as nicely represented in a parable old by astronomer Arthur Eddington.

He [Eddington] described a man who set about to study deep-sea life using a net that had a mesh size of three inches. After catching many wild and wonderful creatures from the depths, the man concluded there are no deep-sea fish that are smaller than three inches in length! If we are using the scientific net to catch our particular version of truth, we should not be surprised that it does not catch the evidence of spirit.

Reference: Language of God, p 229 https://www.amazon.com/Language-God-Scientist-Presents-Evidence/dp/1416542744

Collins is quoting this fellow:

Sir Arthur Stanley Eddington OM FRS[2] (28 December 1882 – 22 November 1944) was an English astronomer, physicist, and mathematician. He was also a philosopher of science and a populariser of science. The Eddington limit, the natural limit to the luminosity of stars, or the radiation generated by accretion onto a compact object, is named in his honour.


My remarks:

Eddington points out an epistemological mistake that is then used to draw an ontological conclusion that is not warranted. This is exactly what believers in philosophical naturalism (PN) commit when they tell us “science says there is no god.” PN believers are actually asserting that the natural world comprises all of reality and therefore theists must give up theism because the supernatural is impossible. This, BTW, is scientism.

I label this as Naturalism of the Gaps. I coined the phrase as a satire and later realized it is a serious position that invokes questions about human knowledge. I recently mentioned Naturalism of the Gaps to Jonathon Blocker. That afternoon I also read the remarks by Collins. It seems many physicists and philosophers have pondered these questions. I only noticed it because of the virulent and boisterous criticism of theists by science students who are looking for their daily student dose of confirmation bias.

Posted to FTDNA user group today:

I build trees on ancestry, export the tree, then import to ftdna. FTDNA project admins like to ask for a Y-tree (only contains paternal line relatives) and I did a special tree on ancestry for just that purpose.

There is no perfect web service, web developers are very expensive, and it is very frustrating to try find the optimum place to study genealogy. My family members do not know what the word “Browser” even means. Nobody in the family owns a laptop. they all use mobile devices. My son tells me the fact that I have a laptop and use the term browser means I AM A REALLY OLD GUY. 😉

I even use something called eeee-male. Whats that?

Troll Wear

Once upon a time a race of Norwegian trolls invaded Scotland. And they wore pants around their knees. Scottish youth started mimicking them. So the Scots invented the kilt and passed a law banning pants, which were now considered undignified, rediculus and disgusting troll wear. As a result, the trolls moved to America, as we all can now see.

Protocol Buffer Basics: C++

I love this IDL stuff.



One can define an ontology and a vocabulary for one’s own application pretty easily. Its basically a data definition language, commonly called IDL (interface definition language), and it is the core of any distributed toolkit you might build. Google decided to build data marshalling tools around it. La Dee Dah. May as well go with it. Please note, microshaft was not able to get everyone to use their stupid stuff – many don’t want their world. So google invented their own.

This tutorial provides a basic C++ programmer’s introduction to working with protocol buffers. By walking through creating a simple example application, it shows you how to

  • Define message formats in a .proto file.
  • Use the protocol buffer compiler.
  • Use the C++ protocol buffer API to write and read messages.

This isn’t a comprehensive guide to using protocol buffers in C++. For more detailed reference information, see the Protocol Buffer Language Guide, the C++ API Reference, the C++ Generated Code Guide, and the Encoding Reference.

Why Use Protocol Buffers?

The example we’re going to use is a very simple “address book” application that can read and write people’s contact details to and from a file. Each person in the address book has a name, an ID, an email address, and a contact phone number.

How do you serialize and retrieve structured data like this? There are a few ways to solve this problem:

  • The raw in-memory data structures can be sent/saved in binary form. Over time, this is a fragile approach, as the receiving/reading code must be compiled with exactly the same memory layout, endianness, etc. Also, as files accumulate data in the raw format and copies of software that are wired for that format are spread around, it’s very hard to extend the format.
  • You can invent an ad-hoc way to encode the data items into a single string – such as encoding 4 ints as “12:3:-23:67”. This is a simple and flexible approach, although it does require writing one-off encoding and parsing code, and the parsing imposes a small run-time cost. This works best for encoding very simple data.
  • Serialize the data to XML. This approach can be very attractive since XML is (sort of) human readable and there are binding libraries for lots of languages. This can be a good choice if you want to share data with other applications/projects. However, XML is notoriously space intensive, and encoding/decoding it can impose a huge performance penalty on applications. Also, navigating an XML DOM tree is considerably more complicated than navigating simple fields in a class normally would be.

Protocol buffers are the flexible, efficient, automated solution to solve exactly this problem. With protocol buffers, you write a .proto description of the data structure you wish to store. From that, the protocol buffer compiler creates a class that implements automatic encoding and parsing of the protocol buffer data with an efficient binary format. The generated class provides getters and setters for the fields that make up a protocol buffer and takes care of the details of reading and writing the protocol buffer as a unit. Importantly, the protocol buffer format supports the idea of extending the format over time in such a way that the code can still read data encoded with the old format.

Where to Find the Example Code

The example code is included in the source code package, under the “examples” directory. Download it here.

Defining Your Protocol Format

To create your address book application, you’ll need to start with a .proto file. The definitions in a .proto file are simple: you add a message for each data structure you want to serialize, then specify a name and a type for each field in the message. Here is the .proto file that defines your messages, addressbook.proto.

syntax = "proto2";

package tutorial;

message Person {
  optional string name = 1;
  optional int32 id = 2;
  optional string email = 3;

  enum PhoneType {
    MOBILE = 0;
    HOME = 1;
    WORK = 2;
  }

  message PhoneNumber {
    optional string number = 1;
    optional PhoneType type = 2 [default = HOME];
  }

  repeated PhoneNumber phones = 4;
}

message AddressBook {
  repeated Person people = 1;
}

As you can see, the syntax is similar to C++ or Java. Let’s go through each part of the file and see what it does.

The .proto file starts with a package declaration, which helps to prevent naming conflicts between different projects. In C++, your generated classes will be placed in a namespace matching the package name.

Next, you have your message definitions. A message is just an aggregate containing a set of typed fields. Many standard simple data types are available as field types, including boolint32floatdouble, and string. You can also add further structure to your messages by using other message types as field types – in the above example the Person message contains PhoneNumber messages, while the AddressBook message contains Person messages. You can even define message types nested inside other messages – as you can see, the PhoneNumber type is defined inside Person. You can also define enum types if you want one of your fields to have one of a predefined list of values – here you want to specify that a phone number can be one of MOBILEHOME, or WORK.

The ” = 1″, ” = 2″ markers on each element identify the unique “tag” that field uses in the binary encoding. Tag numbers 1-15 require one less byte to encode than higher numbers, so as an optimization you can decide to use those tags for the commonly used or repeated elements, leaving tags 16 and higher for less-commonly used optional elements. Each element in a repeated field requires re-encoding the tag number, so repeated fields are particularly good candidates for this optimization.

Each field must be annotated with one of the following modifiers:

  • optional: the field may or may not be set. If an optional field value isn’t set, a default value is used. For simple types, you can specify your own default value, as we’ve done for the phone number type in the example. Otherwise, a system default is used: zero for numeric types, the empty string for strings, false for bools. For embedded messages, the default value is always the “default instance” or “prototype” of the message, which has none of its fields set. Calling the accessor to get the value of an optional (or required) field which has not been explicitly set always returns that field’s default value.
  • repeated: the field may be repeated any number of times (including zero). The order of the repeated values will be preserved in the protocol buffer. Think of repeated fields as dynamically sized arrays.
  • required: a value for the field must be provided, otherwise the message will be considered “uninitialized”. If libprotobuf is compiled in debug mode, serializing an uninitialized message will cause an assertion failure. In optimized builds, the check is skipped and the message will be written anyway. However, parsing an uninitialized message will always fail (by returning false from the parse method). Other than this, a required field behaves exactly like an optional field.

Required Is Forever You should be very careful about marking fields as required. If at some point you wish to stop writing or sending a required field, it will be problematic to change the field to an optional field – old readers will consider messages without this field to be incomplete and may reject or drop them unintentionally. You should consider writing application-specific custom validation routines for your buffers instead. Within Google, required fields are strongly disfavored; most messages defined in proto2 syntax use optional and repeated only. (Proto3 does not support required fields at all.)

You’ll find a complete guide to writing .proto files – including all the possible field types – in the Protocol Buffer Language Guide. Don’t go looking for facilities similar to class inheritance, though – protocol buffers don’t do that.

Compiling Your Protocol Buffers

Now that you have a .proto, the next thing you need to do is generate the classes you’ll need to read and write AddressBook (and hence Person and PhoneNumber) messages. To do this, you need to run the protocol buffer compiler protoc on your .proto:

  1. If you haven’t installed the compiler, download the package and follow the instructions in the README.
  2. Now run the compiler, specifying the source directory (where your application’s source code lives – the current directory is used if you don’t provide a value), the destination directory (where you want the generated code to go; often the same as $SRC_DIR), and the path to your .proto. In this case, you…:protoc -I=$SRC_DIR –cpp_out=$DST_DIR $SRC_DIR/addressbook.protoBecause you want C++ classes, you use the --cpp_out option – similar options are provided for other supported languages.

This generates the following files in your specified destination directory:

  • addressbook.pb.h, the header which declares your generated classes.
  • addressbook.pb.cc, which contains the implementation of your classes.

The Protocol Buffer API

Let’s look at some of the generated code and see what classes and functions the compiler has created for you. If you look in addressbook.pb.h, you can see that you have a class for each message you specified in addressbook.proto. Looking closer at the Person class, you can see that the compiler has generated accessors for each field. For example, for the nameidemail, and phones fields, you have these methods:

  // name
  inline bool has_name() const;
  inline void clear_name();
  inline const ::std::string& name() const;
  inline void set_name(const ::std::string& value);
  inline void set_name(const char* value);
  inline ::std::string* mutable_name();

  // id
  inline bool has_id() const;
  inline void clear_id();
  inline int32_t id() const;
  inline void set_id(int32_t value);

  // email
  inline bool has_email() const;
  inline void clear_email();
  inline const ::std::string& email() const;
  inline void set_email(const ::std::string& value);
  inline void set_email(const char* value);
  inline ::std::string* mutable_email();

  // phones
  inline int phones_size() const;
  inline void clear_phones();
  inline const ::google::protobuf::RepeatedPtrField< ::tutorial::Person_PhoneNumber >& phones() const;
  inline ::google::protobuf::RepeatedPtrField< ::tutorial::Person_PhoneNumber >* mutable_phones();
  inline const ::tutorial::Person_PhoneNumber& phones(int index) const;
  inline ::tutorial::Person_PhoneNumber* mutable_phones(int index);
  inline ::tutorial::Person_PhoneNumber* add_phones();

As you can see, the getters have exactly the name as the field in lowercase, and the setter methods begin with set_. There are also has_ methods for each singular (required or optional) field which return true if that field has been set. Finally, each field has a clear_ method that un-sets the field back to its empty state.

While the numeric id field just has the basic accessor set described above, the name and email fields have a couple of extra methods because they’re strings – a mutable_ getter that lets you get a direct pointer to the string, and an extra setter. Note that you can call mutable_email() even if email is not already set; it will be initialized to an empty string automatically. If you had a singular message field in this example, it would also have a mutable_ method but not a set_ method.

Repeated fields also have some special methods – if you look at the methods for the repeated phones field, you’ll see that you can

  • check the repeated field’s _size (in other words, how many phone numbers are associated with this Person).
  • get a specified phone number using its index.
  • update an existing phone number at the specified index.
  • add another phone number to the message which you can then edit (repeated scalar types have an add_ that just lets you pass in the new value).

For more information on exactly what members the protocol compiler generates for any particular field definition, see the C++ generated code reference.

Enums and Nested Classes

The generated code includes a PhoneType enum that corresponds to your .proto enum. You can refer to this type as Person::PhoneType and its values as Person::MOBILEPerson::HOME, and Person::WORK (the implementation details are a little more complicated, but you don’t need to understand them to use the enum).

The compiler has also generated a nested class for you called Person::PhoneNumber. If you look at the code, you can see that the “real” class is actually called Person_PhoneNumber, but a typedef defined inside Person allows you to treat it as if it were a nested class. The only case where this makes a difference is if you want to forward-declare the class in another file – you cannot forward-declare nested types in C++, but you can forward-declare Person_PhoneNumber.

Standard Message Methods

Each message class also contains a number of other methods that let you check or manipulate the entire message, including:

  • bool IsInitialized() const;: checks if all the required fields have been set.
  • string DebugString() const;: returns a human-readable representation of the message, particularly useful for debugging.
  • void CopyFrom(const Person& from);: overwrites the message with the given message’s values.
  • void Clear();: clears all the elements back to the empty state.

These and the I/O methods described in the following section implement the Message interface shared by all C++ protocol buffer classes. For more info, see the complete API documentation for Message.

Parsing and Serialization

Finally, each protocol buffer class has methods for writing and reading messages of your chosen type using the protocol buffer binary format. These include:

  • bool SerializeToString(string* output) const;: serializes the message and stores the bytes in the given string. Note that the bytes are binary, not text; we only use the string class as a convenient container.
  • bool ParseFromString(const string& data);: parses a message from the given string.
  • bool SerializeToOstream(ostream* output) const;: writes the message to the given C++ ostream.
  • bool ParseFromIstream(istream* input);: parses a message from the given C++ istream.

These are just a couple of the options provided for parsing and serialization. Again, see the Message API reference for a complete list.

Protocol Buffers and Object Oriented Design Protocol buffer classes are basically dumb data holders (like structs in C); they don’t make good first class citizens in an object model. If you want to add richer behavior to a generated class, the best way to do this is to wrap the generated protocol buffer class in an application-specific class. Wrapping protocol buffers is also a good idea if you don’t have control over the design of the .proto file (if, say, you’re reusing one from another project). In that case, you can use the wrapper class to craft an interface better suited to the unique environment of your application: hiding some data and methods, exposing convenience functions, etc. You should never add behaviour to the generated classes by inheriting from them. This will break internal mechanisms and is not good object-oriented practice anyway.

Writing A Message

Now let’s try using your protocol buffer classes. The first thing you want your address book application to be able to do is write personal details to your address book file. To do this, you need to create and populate instances of your protocol buffer classes and then write them to an output stream.

Here is a program which reads an AddressBook from a file, adds one new Person to it based on user input, and writes the new AddressBook back out to the file again. The parts which directly call or reference code generated by the protocol compiler are highlighted.

#include <iostream>
#include <fstream>
#include <string>
#include "addressbook.pb.h"
using namespace std;

// This function fills in a Person message based on user input.
void PromptForAddress(tutorial::Person* person) {
  cout << "Enter person ID number: ";
  int id;
  cin >> id;
  person->set_id(id);
  cin.ignore(256, '\n');

  cout << "Enter name: ";
  getline(cin, *person->mutable_name());

  cout << "Enter email address (blank for none): ";
  string email;
  getline(cin, email);
  if (!email.empty()) {
    person->set_email(email);
  }

  while (true) {
    cout << "Enter a phone number (or leave blank to finish): ";
    string number;
    getline(cin, number);
    if (number.empty()) {
      break;
    }

    tutorial::Person::PhoneNumber* phone_number = person->add_phones();
    phone_number->set_number(number);

    cout << "Is this a mobile, home, or work phone? ";
    string type;
    getline(cin, type);
    if (type == "mobile") {
      phone_number->set_type(tutorial::Person::MOBILE);
    } else if (type == "home") {
      phone_number->set_type(tutorial::Person::HOME);
    } else if (type == "work") {
      phone_number->set_type(tutorial::Person::WORK);
    } else {
      cout << "Unknown phone type.  Using default." << endl;
    }
  }
}

// Main function:  Reads the entire address book from a file,
//   adds one person based on user input, then writes it back out to the same
//   file.
int main(int argc, char* argv[]) {
  // Verify that the version of the library that we linked against is
  // compatible with the version of the headers we compiled against.
  GOOGLE_PROTOBUF_VERIFY_VERSION;

  if (argc != 2) {
    cerr << "Usage:  " << argv[0] << " ADDRESS_BOOK_FILE" << endl;
    return -1;
  }

  tutorial::AddressBook address_book;

  {
    // Read the existing address book.
    fstream input(argv[1], ios::in | ios::binary);
    if (!input) {
      cout << argv[1] << ": File not found.  Creating a new file." << endl;
    } else if (!address_book.ParseFromIstream(&input)) {
      cerr << "Failed to parse address book." << endl;
      return -1;
    }
  }

  // Add an address.
  PromptForAddress(address_book.add_people());

  {
    // Write the new address book back to disk.
    fstream output(argv[1], ios::out | ios::trunc | ios::binary);
    if (!address_book.SerializeToOstream(&output)) {
      cerr << "Failed to write address book." << endl;
      return -1;
    }
  }

  // Optional:  Delete all global objects allocated by libprotobuf.
  google::protobuf::ShutdownProtobufLibrary();

  return 0;
}

Notice the GOOGLE_PROTOBUF_VERIFY_VERSION macro. It is good practice – though not strictly necessary – to execute this macro before using the C++ Protocol Buffer library. It verifies that you have not accidentally linked against a version of the library which is incompatible with the version of the headers you compiled with. If a version mismatch is detected, the program will abort. Note that every .pb.cc file automatically invokes this macro on startup.

Also notice the call to ShutdownProtobufLibrary() at the end of the program. All this does is delete any global objects that were allocated by the Protocol Buffer library. This is unnecessary for most programs, since the process is just going to exit anyway and the OS will take care of reclaiming all of its memory. However, if you use a memory leak checker that requires that every last object be freed, or if you are writing a library which may be loaded and unloaded multiple times by a single process, then you may want to force Protocol Buffers to clean up everything.

Reading A Message

Of course, an address book wouldn’t be much use if you couldn’t get any information out of it! This example reads the file created by the above example and prints all the information in it.

#include <iostream>
#include <fstream>
#include <string>
#include "addressbook.pb.h"
using namespace std;

// Iterates though all people in the AddressBook and prints info about them.
void ListPeople(const tutorial::AddressBook& address_book) {
  for (int i = 0; i < address_book.people_size(); i++) {
    const tutorial::Person& person = address_book.people(i);

    cout << "Person ID: " << person.id() << endl;
    cout << "  Name: " << person.name() << endl;
    if (person.has_email()) {
      cout << "  E-mail address: " << person.email() << endl;
    }

    for (int j = 0; j < person.phones_size(); j++) {
      const tutorial::Person::PhoneNumber& phone_number = person.phones(j);

      switch (phone_number.type()) {
        case tutorial::Person::MOBILE:
          cout << "  Mobile phone #: ";
          break;
        case tutorial::Person::HOME:
          cout << "  Home phone #: ";
          break;
        case tutorial::Person::WORK:
          cout << "  Work phone #: ";
          break;
      }
      cout << phone_number.number() << endl;
    }
  }
}

// Main function:  Reads the entire address book from a file and prints all
//   the information inside.
int main(int argc, char* argv[]) {
  // Verify that the version of the library that we linked against is
  // compatible with the version of the headers we compiled against.
  GOOGLE_PROTOBUF_VERIFY_VERSION;

  if (argc != 2) {
    cerr << "Usage:  " << argv[0] << " ADDRESS_BOOK_FILE" << endl;
    return -1;
  }

  tutorial::AddressBook address_book;

  {
    // Read the existing address book.
    fstream input(argv[1], ios::in | ios::binary);
    if (!address_book.ParseFromIstream(&input)) {
      cerr << "Failed to parse address book." << endl;
      return -1;
    }
  }

  ListPeople(address_book);

  // Optional:  Delete all global objects allocated by libprotobuf.
  google::protobuf::ShutdownProtobufLibrary();

  return 0;
}

Extending a Protocol Buffer

Sooner or later after you release the code that uses your protocol buffer, you will undoubtedly want to “improve” the protocol buffer’s definition. If you want your new buffers to be backwards-compatible, and your old buffers to be forward-compatible – and you almost certainly do want this – then there are some rules you need to follow. In the new version of the protocol buffer:

  • you must not change the tag numbers of any existing fields.
  • you must not add or delete any required fields.
  • you may delete optional or repeated fields.
  • you may add new optional or repeated fields but you must use fresh tag numbers (i.e. tag numbers that were never used in this protocol buffer, not even by deleted fields).

(There are some exceptions to these rules, but they are rarely used.)

If you follow these rules, old code will happily read new messages and simply ignore any new fields. To the old code, optional fields that were deleted will simply have their default value, and deleted repeated fields will be empty. New code will also transparently read old messages. However, keep in mind that new optional fields will not be present in old messages, so you will need to either check explicitly whether they’re set with has_, or provide a reasonable default value in your .proto file with [default = value] after the tag number. If the default value is not specified for an optional element, a type-specific default value is used instead: for strings, the default value is the empty string. For booleans, the default value is false. For numeric types, the default value is zero. Note also that if you added a new repeated field, your new code will not be able to tell whether it was left empty (by new code) or never set at all (by old code) since there is no has_ flag for it.

Optimization Tips

The C++ Protocol Buffers library is extremely heavily optimized. However, proper usage can improve performance even more. Here are some tips for squeezing every last drop of speed out of the library:

  • Reuse message objects when possible. Messages try to keep around any memory they allocate for reuse, even when they are cleared. Thus, if you are handling many messages with the same type and similar structure in succession, it is a good idea to reuse the same message object each time to take load off the memory allocator. However, objects can become bloated over time, especially if your messages vary in “shape” or if you occasionally construct a message that is much larger than usual. You should monitor the sizes of your message objects by calling the SpaceUsed method and delete them once they get too big.
  • Your system’s memory allocator may not be well-optimized for allocating lots of small objects from multiple threads. Try using Google’s tcmalloc instead.

Advanced Usage

Protocol buffers have uses that go beyond simple accessors and serialization. Be sure to explore the C++ API reference to see what else you can do with them.

One key feature provided by protocol message classes is reflection. You can iterate over the fields of a message and manipulate their values without writing your code against any specific message type. One very useful way to use reflection is for converting protocol messages to and from other encodings, such as XML or JSON. A more advanced use of reflection might be to find differences between two messages of the same type, or to develop a sort of “regular expressions for protocol messages” in which you can write expressions that match certain message contents. If you use your imagination, it’s possible to apply Protocol Buffers to a much wider range of problems than you might initially expect!

Reflection is provided by the Message::Reflection interface.

Adding More Structure

I started adding some structure on conservatism, liberalism, progressivism, etc, laying out buckets in which to organize thoughts. And filled in some things. TBD: Add some pages defining each actual world view and a note on it’s history and evolution.