Good habits

Consider this quote by Aristotle:

“Excellence is an art won by training and habituation: we do not act rightly because we have virtue or excellence, but we rather have these because we have acted rightly”

Wow. If this is a true statement (and I believe it is), then a man ought to build his life around doing the very things that produce virtues (goodness, compassion, magnanimity, honesty, etc.) and competencies (skills and abilities). To me, that means recognizing the actions that will grow your virtues and competencies, and making a real commitment to perform them on a consistent basis. Take for example the following well-known proverb:

“The early bird gets the worm.”

The phrase is usually said to mean “he who rises early finds opportunities which others miss.” The meaning of “early bird” lies in “he who rises early.” An “early bird” is not so much a thing that is or is not, such as gold or copper or air, but rather a word used to describe one who performs certain actions. Though a man can never through his actions become gold or silver, he can assuredly rise earlier each morning and thus become an early bird.

Thus, what life may really be about is deciding what activities you might participate in or abstain from which will form the virtues you wish to exhibit, or build the skills you wish to have.

Harry Truman once said, “In reading the lives of great men, I’ve found that with all of them self-discipline came first.” A man is not virtuous or competent because he was born as such, but rather because he has worked at it. The type of systematic work that actually makes the difference is what takes discipline. A man might be a great admirer of music. To become a musician, however, he must work. He must study theory, analyze the music of others, and become skilled with some instrument. Simply enjoying music is not enough. Simply wishing will not suffice.  A man must perform repeated actions to achieve a desired result.

All of this comes back to your habits. If you wake up early every day and focus for a few hours on getting something really important done, you become a person who gets up early and gets things done. If you can make time every day to learn more about your craft (a few hours), then very soon, you will find yourself surpassing your peers who perhaps only learn when necessity demands. Bad habits go the same way.  If you drink often, you risk becoming a drunk.  If you shun social interaction, you might become a pariah.

To simplify Aristotle’s original quote:

“We are what we repeatedly do.”

Posted in Abstract, Goals, Philosophy, Self Improvement | 1 Comment

The fire

A warm fire, a cool night; your lips on the tea cup. A savory liquid fills the soul like early morning light.

These years have been dark; despair an old friend. A fortitude beats yet inside – a muse that inspires, a desire to fight.

Fuel given, the fire builds. This tiny house a beacon, its radiance weakening winter’s grasp, a new creature emerges, a heart overcome with delight.

Keep at it, urges the muse. Your work known, your path defined; Cloaked in gold and purpose refined, go now, take hold of what you sought to find.

Posted in Poetry, Self Improvement | 3 Comments

Traits, Exceptions, and Better Automated Tests

I really, really dig 5.4′s traits. Let’s review:

  • Through the ‘use’ keyword, traits let you include shared functionality in a class without relying on inheritance or encapsulation of another class.
  • With the exception of declaring static variables (you can’t), and referencing parent (will call the class you’re using the trait in), traits behave just like they’re part of a class.

Now, let me say a few things about how I prefer to code:

  • Unless I know 100%, beyond a shadow of a doubt, that an argument list will *never* change, I prefer passing objects or arrays as arguments instead of variables.  What I’ve seen happen in many projects / frameworks is you end up with this impossible method list.
  • As much as possible, I like to write defensive code that favors exceptions I can catch over fatal errors that will crash my programs.
  • I do NOT like repeating myself.
  • I’m lazy.  When I’m running automated tests, I don’t just want to know that an assert failed, I want to know exactly why it failed.

Thus, was borne my solution to checking required params and throwing exceptions I can catch in my tests when they’re omitted.  Consider the following code snippets:

The RequiredParams trait:

namespace System\Friend;

trait RequiredParams
{
	protected function checkArgs($params, $required){
		$missing = array();
		if(is_array($params) || is_object($params)){
			if(!is_object($params)) $params = (object) $params;

			foreach($required as $k){
				if(!isset($params->$k)) $missing[] = $k;
			}

			if(count($missing) > 0) {
				$missingKeys = implode(", ", $missing);
				throw new \Exception("Required params are missing: $missingKeys");
			}
			else {
				return true;
			}
		}

		throw new \Exception("Argument list was empty.");
	}
}

RequiredParams is used in AccountingProxy (duly noted that the hardcoded numeric literals should probably be constants). Here is one of the methods:

	public function createInvoice($params)
	{
		$this->checkArgs($params, array('type', 'id', 'created', 'due', 'items'));

		$invoice = array(
			'Invoice' => array(
				'Type' => ($params->type == 'payable') ? 'ACCPAY' : 'ACCREC',
				'Contact' => array(
					'ContactNumber' => $params->id
				),
				'Status' => 'AUTHORISED',
				'LineItems' => array(
				),
				'Date' => $params->created,
				'DueDate' => $params->due
			)
		);

		foreach($params->items as $item){
			$this->checkArgs($item, array('description', 'qty', 'amt'));

			$item = (object) $item;

			if(isset($item->code)){
				$code = $item->code;
			}
			else {
				$code = ($params->type == 'payable') ? 65700 : 410;
			}

			$invoice['LineItems']['LineItem'] = array(
				'LineItem' => array(
					'Description' => $item->description,
					'Quantity' => $item->qty,
					'UnitAmount' => $item->amt,
					'AccountCode' => $code
				)
			);
		}

		$created = $this->xero->invoices($invoice);

		return $created;
	}

And here is a a test definition for the method:

		$this->defineTest(
			new \Model\Implementation\AccountingProxy,
			array(
				'name' => 'Create a receivable invoice',
				'method' => 'createInvoice',
				'args' => array(
					(object) array(
						'type' => 'receivable',
						'id' => $customerId,
						'created' => '',
						'due' => \System\Implementation\DateTime::now(),
						'items' => array(
							array(
							'description' => 'This is an invoice item',
							'qty' => 1,
							'amt' => 20.00
							)
						)
					)
				),
				'assert' => array(
					'is',
					'numeric'
				),
				'responseToVar' => &$payInvId
			)
		);

So, as you can see, if createInvoice is missing any required items, even params within params, we can use checkArgs to throw an exception and give us real details about the problem.

Enjoy!

Posted in PHP, Programming | Leave a comment

Traits + Interfaces in PHP 5.4 – The Perfect Team

PHP has been getting consistently better over the past few years. One new feature that I’m really pleased with is traits, which is similar to multiple inheritance in Java, friend classes in C++ or mixins in Ruby and Python.

Basically, traits allow your classes to share functionality without constructing any objects or inheriting from any base classes. I’ve been able to put traits to some pretty cool uses already.

One of the neatest things I’ve done is teaming them with interfaces to implement shared functionality that adheres to an interface without needing monolithic base classes. Here’s a simple example:

interface Foo
{
	public function bop();
}

trait Baz
{
	public function bop()
	{
		print 'it works!';
	}
}

class Bar implements Foo
{
	use Baz;
}

$x = new Bar();
$x->bop();

As you can see, Bar does not have a bop() method in its class definition. It’s using the definition provided by the trait. The scoping in the Baz treat still works just like you’d expect for the most part (the only trouble I’ve had so far is using parent::__construct() in a shared constructor).

Let’s look at a more complicated example (Note – this is just an excerpt from a more complicated program, it won’t work if you just copy and paste it. If you want to give traits a shot, start with the simple example and work your way up):

namespace Model\Abstraction;

interface InterfaceRead
{
	public function __construct();

	public function fetchBy($qualifiers = array());

	public function fetchAll();
}

namespace Model\Friend;

trait Read
{
	/*
	*	Fetch records using a where clause
	*/
	public function fetchBy($qualifiers = array())
	{
		$this->applyQualifiers($qualifiers);

		$result = $this->stmtPrepExecFetchAll("*");	

		return $result;
	}

	/*
	*	Fetch all records
	*/
	public function fetchAll()
	{
		return $this->fetchBy();
	}
}

namespace Model\Implementation;

class Intl extends \Model\Implementation\Base\Base implements \Model\Abstraction\InterfaceRead
{
	use \Model\Friend\Read;

	public function __construct(){
		parent::__construct();
		$this->table('country');
	}
}

Since all of my models which are read only will use the same API, it makes great sense to use traits to implement common functionality. Fortunately, if I need to, I can still override the functionality provided by the trait by simply declaring the method within my class.

Ok, so let’s take this a step further. What If I want to adhere to an interface which demands more shared functionality? Easy, just toss another trait into the mix:

namespace Model\Implementation;

class Intl extends \Model\Implementation\Base\Base implements \Model\Abstraction\InterfaceCreateRead
{
	use \Model\Friend\Create;
	use \Model\Friend\Read;

	public function __construct(){
		parent::__construct();
		$this->table('country');
	}
}

Anyway, thought this was cool and wanted to share = )

Posted in PHP, Programming | Comments closed

Evolving

For the past few months, I’ve been exploring software design patterns, both at their roots and in their modern implementations. I’ve been exploring new languages and deepening my understanding of the languages that I already use. Man can I ever tell ya, it’s been exhilarating.

I started reading a new book last night, given to me by a CS professor who has been extremely kind to me. It was written in 1979, published by IBM: “Structured programming, theory and practice“. In the preface to the book, the authors discuss the beginnings of the software development field (originally an afterthought to hardware, and an error-prone, cut-and-try process) and its evolution into a true discipline where a programmer could solve a problem correctly, the first time, with no mistakes. I found one statement incredibly profound, contrasting ad-hoc spray-and-pray methods with true precision: “A programmer can gain 10 years of experience, or a programmer can get the same years experiences 10 times over.” Wow. How true.

If there is any fundamental evil in the profession of software, it must be that horrible trial and error loop that is the result of a lack of understanding – about the problem at hand (if it has even been defined), the tools at your disposal, existing solutions, or all three. When we allow ourselves to subsist in such a state, we waste the little time we have on this planet. We become triflers and busy bodies, always scurrying about in a rush yet never accomplishing anything of significance.

Have you ever met someone who has been in the field for years, yet still seems to have abilities only slightly better than that of a novice? I have. In contrast, have you ever met a “whiz” who seems to make incredible progress in short amounts of time? I’ve met a few of those as well.

In Daniel Coyle’s “The Talent Code: Greatness isn’t Born, it’s Grown,” the process of building skill is discussed and examined at length. The book opens with a story about a girl who does a month’s worth of practice in five minutes, without even knowing it. This seems like a fantastic claim from the outset, but as the book progresses Coyle makes his case. Coyle claims that while duration of practice is indeed important, the method of practice is a far more effective mechanism for building talent. Coyle examines Russian Women’s Tennis Champions, South Korean Golf Champions, Brazilian Soccer Players, World Class Musicians and Singers, Surfers, Chess players, elite magnet schools and more. His argument is that in all cases – elite performers don’t simply spend lots of time in their respective courts – they spend their time doing completely different things. Elite performers focus on developing a fluency with the fundamentals. They “chunk” their learning such that each piece is mastered independently of the whole.

I feel software development is a field where this is especially true. From my own experiences, I know that my greatest personal gains have come from:

- Deep study of fundamentals. Language fundamentals. Programming paradigms. Data structures. Repetition of those fundamentals.
- Application of those fundamentals in more holistic contexts.
- Closely examining (not just reading, but PORING OVER) code written by more capable programmers

Conversely, I can say that my own gains plateau when I find myself debugging code I don’t understand, using tools I don’t understand, and staying in my comfort zone (ie writing code and designing systems I already know how to write and design). The longer I subsist in this state, the harder it is to get back to doing it right. Complacency and ignorance breed the same.

CS Lewis states in the preface to “The Great Divorce” that “when a man faces a fork in the road and chooses incorrectly, he will never reach his desired destination by continuing. He must backtrack to where the error was made and begin again on the correct path.”

A programmer will never grow in a state of willful ignorance and repetitive, mindless busy work. A commitment to knowledge and understanding, being guarded against error, a passion for our craft; These are the building blocks of growth. This is how we evolve…quickly.

Posted in Abstract, Computer Science, Programming, Self Improvement | 5 Comments

The Reason for the Fireworks

Being Independence Day and all, with people getting excited about fireworks and a day off work, I was hoping to take a step back and look at the whole reason for this day.  In this blog post I analyze the declaration of independence, put it in slightly simpler terms, and look at it in our current context.  On this day in 1776 a British colony decided it wanted to manage its own affairs.  Our founding fathers were brave enough to stand up to the greatest military power on the planet and demand freedom.  They boldly asserted:

“We hold these truths to be self-evident, that all men are created equal, that they are endowed by their Creator with certain unalienable Rights, that among these are Life, Liberty and the pursuit of Happiness.–That to secure these rights, Governments are instituted among Men, deriving their just powers from the consent of the governed, –That whenever any Form of Government becomes destructive of these ends, it is the Right of the People to alter or to abolish it, and to institute new Government, laying its foundation on such principles and organizing its powers in such form, as to them shall seem most likely to effect their Safety and Happiness.”

In simpler words: “Men form governments to ensure the continuation of life, liberty and the pursuit of happiness for each and all.  When a government no longer serves these needs, but becomes a threat to it, people have the right to change or destroy that government.”

They continue:

“Prudence, indeed, will dictate that Governments long established should not be changed for light and transient causes; and accordingly all experience hath shewn, that mankind are more disposed to suffer, while evils are sufferable, than to right themselves by abolishing the forms to which they are accustomed. But when a long train of abuses and usurpations, pursuing invariably the same Object evinces a design to reduce them under absolute Despotism, it is their right, it is their duty, to throw off such Government, and to provide new Guards for their future security.–Such has been the patient sufferance of these Colonies; and such is now the necessity which constrains them to alter their former Systems of Government.”

In simpler words: “Many times it is better to suffer a bit than to risk destroying a system of government.  However, when a long series of blows to the well being of the governed are made by the governing, the governed not only have a right, but a duty to throw down that government and establish a new one, for the sake of themselves and future generations.”

They go onto assert that the King of Britain, through his actions, have brought the colonies to such a point in which they must throw off his Tyranny.  They claim as grievances hat the king has meddled in nearly every facet of their lives in ways which are displeasing to them:

- Lack of justice in the legal system

- Interference in commerce

- Interference in allowing people to govern themselves

- Taxation without consent

- Searches and seizures, quartering of troops

You can read the full list at (http://www.archives.gov/exhibits/charters/declaration_transcript.html).

They continue in showing that they are not acting rashly, and have continued to express concern and request redress to every affront:

“Our repeated Petitions have been answered only by repeated injury.”

“We have warned them from time to time of attempts by their legislature to extend an unwarrantable jurisdiction over us. We have reminded them of the circumstances of our emigration and settlement here. We have appealed to their native justice and magnanimity, and we have conjured them by the ties of our common kindred to disavow these usurpations, which, would inevitably interrupt our connections and correspondence. They too have been deaf to the voice of justice and of consanguinity. We must, therefore, acquiesce in the necessity, which denounces our Separation, and hold them, as we hold the rest of mankind, Enemies in War, in Peace Friends.”

Because these requests had been ignored, laughed at, or responded to with violence, the United States of America is declaring its freedom:

“We, therefore, the Representatives of the united States of America, in General Congress, Assembled, appealing to the Supreme Judge of the world for the rectitude of our intentions, do, in the Name, and by Authority of the good People of these Colonies, solemnly publish and declare, That these United Colonies are, and of Right ought to be Free and Independent States; that they are Absolved from all Allegiance to the British Crown, and that all political connection between them and the State of Great Britain, is and ought to be totally dissolved; and that as Free and Independent States, they have full Power to levy War, conclude Peace, contract Alliances, establish Commerce, and to do all other Acts and Things which Independent States may of right do. And for the support of this Declaration, with a firm reliance on the protection of divine Providence, we mutually pledge to each other our Lives, our Fortunes and our sacred Honor.”

The takeaway here is that under any government, you should do your best to work within the system to change the system.  You should not be silent when you are wronged.  You must act peaceably and work to institute positive change.  There comes a point, however, when this course of action is no longer available.  The only course of action left is rebellion – as the founders put it – abolishing the current government and establishing a new one.  As Thomas Jefferson once stated, “The tree of liberty must from time to time be renewed with the blood of patriots and tyrants.” We must always keep in mind that if we fail to hold onto our rights, if our government reaches a state of corruption past reconciliation, the only dutiful choice is revolt.  This is why we must in our daily lives be vigilant to safeguard our nation’s founding principles in (sometimes) seemingly insignificant ways (voting, discussing, sending letters to senators, protesting).  Those daily practices delay the time until real sacrifice is required to secure a future for our offspring.

I can think of many things our distant government (headquartered in far away Washington DC) now does which with we should take issue:

- Unauthorized foreign wars.  There has been no formal declaration of war – being by congress, and thus of representatives of the people – since WW2, yet in over 100 minor and major conflicts since US troops have died and US taxpayer dollars have been spent.   (see http://en.wikipedia.org/wiki/Declaration_of_war_by_the_United_States).

- Legalized bribery.  The lobbying “industry” are essentially professional bribers.  They give gifts and and monies to government agents (congress, executive, judicial) in exchange for supporting or opposing legislation.  In some cases, companies (such as big pharma, big agriculture, war industrial, prison industrial) will author entire pieces of legislation and pay a politician to sign their name to it and sponsor it in congress.  The fact that this has been institutionalized in our country is sad and scary (see http://www.democracynow.org/2010/1/22/in_landmark_campaign_finance_ruling_supreme).

- Government spying and censorship.  The *first* item in the bill of rights – what the founders considered the *most* important – was freedom of speech, press, religion and assembly.  Now, we have hate crime legislation, making certain words illegal.  We have protestors across the country being arrested and brutalized by police for their actions.  We allow internet companies and large corporations to work in collusion with our government to censor the content we’re allowed to see in searches.

- Gun controls.  Some cities have banned handguns and both the state and federal government put increasing controls on gun possession allowances, through increasingly complex licensing requirements, taxes, and outright bans for certain classes of firearms. (see http://en.wikipedia.org/wiki/Federal_Assault_Weapons_Ban)

- Taxation and mandate.  If we can be forced to buy health insurance, can we not be forced to buy general motors vehicles?  We argue about income taxation, but we don’t stop to think about the fact that we are taxed on nearly everything: food, cell phones, internet usage, gasoline, healthcare, etc. etc.

- Educational interference.  Who can argue the programs like no child left behind have had a positive impact?  Who can argue that 4 decades of increasing cost and bureaucracy have positively impacted education?  Through increased meddling and through student aid programs which allow institutions to continue to increase their costs on the backs of taxpayers, we have crippled our educational system.

Those are just some of the things I can think of that we could all work on to improve.  I don’t think we’re yet at the point the founding fathers were when they chose to declare independence from the King, but if we don’t all get to work, that day will be here sooner than we might hope.

Posted in History, Liberty, Politics | Leave a comment

CodeIgniter / Expression Engine Nashville – Slides

Slides from CodeIgniter / EE Nashville Talk

http://www.calvinfroedge.com/slide-decks/codeigniter-ee-nashville-03-12.pdf

Posted in CodeIgniter, PHP | Leave a comment

Ikigai by Sebastian Marshall – A Review

I just finished up the book Ikigai (or rather, ordered collection of essays, email fragments and blog posts) by a guy named Sebastian Marshall.  Ikigai translates to “Reason for Living,” and Sebastian does a good job of putting together a case for what type of reasons one should live their life, and provides a general framework for doing it effectively.  The book constantly reminded me of work I’ve read by the Stoics (ie Marcus Aurelius, Cicero, and Epictetus).  I wouldn’t go so far as to put Sebastian’s work on an equal footing with Marcus Aurelius’ Meditations, but it is good.

The book covers a lot of ground for being a short read.  I finished in a week of  reading one hour per day.  Among the topics discussed:

- Why it pays to study history.  He includes tons of historical examples of figures who made both strategic strokes of genius and blunders.

- Managing your life.  The importance of tracking things.  Sebastian contends that what gets measured gets  managed, so if you want to stop a bad habit or create a good one  you need to start by tracking how much you do it.

- The importance of constant learning and self enrichment.  Why you should pursue all of your interests (yet carefully schedule that pursuit, thus eliminating all but the most important).

- Settings goals and getting things done.

- Self control and self discipline.  How to build them.

- The low value of temporary happiness and the high value of producing great work.

- Why the “All you have to do is find your passion!” stuff is mostly bullshit – sure you can’t hate what you do but no one who achieves anything does it without doing things that are hard.  For example, I don’t enjoy every line of code I write, nor am I *always* enthused about studying new programming techniques.

The book is by no means perfect.  There are many sentence fragments, a few misspelled / cut off words, etc.  It was not proofed well.  It is not polished, and as something of an English language snob, at times it annoyed the hell out of me.  However, it is a great read.  It’s inspiring, funny, and you’ll definitely learn something.  At times I found myself saying “HELL YES” and pumping my fist.  I rarely do that while I’m reading.

If I had to produce one paragraph that aptly described Sebastian’s message, it would be this:

“You’re going to DIE some day.  Don’t waste your life  mucking around in mediocrity.  Don’t  compare yourself to peers in your own generation – compare yourself to the greatest in history.  Put yourself at the bottom of THAT mountain and start climbing.  On your journey upwards, take care of your body, constantly feed your mind, and be a Johnny Appleseed.  Help others when you can, and do not grant that help begrudgingly.  What are you waiting for, go out and start doing things.”

Check out reviews on Amazon

Posted in Books, Goals, Health, Philosophy, Self Improvement | 3 Comments

A !Quick Lesson in Operators

Operators are one of the core components of any programming language. Knowing how they are classified and how they can be used is extremely important. This post might teach you some new operators. Since the samples are pulled from multiple languages, you may even learn something cool about a new language. Enjoy, and please point out any mistakes.

Arithmetic operators

Ok, lets roll through these as fast as we can. You know these, right?

+ for addition
- for subtraction
* for multiplication
/ for division
% for modulo (remainder after two numbers have been divided)

You can use each of these operators to work with numeric data types (examples in C – int, float, and double are all numeric data types):

//Addition
int x = 2 + 2; //4
int x = 2.0 + 2; //4;
float x = 2.0 + 2; //4.000000

//Subtraction
int x = 2 - 2; //0;
double x = 2.0 - 42; //-40

//Multiplication
int x = 2 * 2; //4

//Division
int x = 3 / 2; //1
double x = 3.0 / 2; //1.5
double x = 3 / 2; //1.000000 <- Be careful with these!

//Modulo
int x = 5 % 4; //1
double x = 3.0 % 2; //Won't compile, actual sanity check here!

Relational (also called comparison) operators

These operators are used to compare values. In all languages they can compare numeric types. In most languages they can compare strings and characters as well as simple datatypes (such as enums). In some languages they can compare more complex data types such as vectors, arrays, and objects.

>= greater than or equal to
> greater than
<> not equal to (less than OR greater than)
<= less than or equal to
< less than
!= not equal to
== equal to
=== equal and same type (PHP)

Python:

3 >= 4 #False
4 > 3 #True
"test" <> "test" #False
"apple" != "orange" #True
"3" == "3" #True

PHP:

$arr = array();
$arr2 = array();
var_dump($arr == $arr2); // bool(true)

$obj = new StdClass;
$obj2 = new StdClass;
$obj->apple = 'test';
var_dump($obj == $obj2); //bool(false)

var_dump(3 === "3") //bool(false)

Logical operators

&& and
|| or
! not

Increment and decrement operators

Pretty simple, like the arithmetic operators…

++var //Increment, equal to var + 1
–var //Decrement, equal to var – 1
+= //Add one number to another
-= //Subtract one number to another

var i = 1;
++i; //2
--i; //1
i += 1; //2
i -= 1; //1

Assignment operators

= //Assign a value
+= //Compact assignment, addition, equal to x = x + y
-= //Compact assignment, subtraction, equal to x = x – y
*= //Compact assignment, multiplication, equal to x = x * y
/= //Compact assignment, division, equal to x = x / y
%= //Compact assignment, modulo, equal to x = x % y

Bitwise operators

& //True if any is true. Evaluates to last statement (meaning all conditions are checked).
| //True if either is true.
^ //True if only one is true.
<< and >> // Left shift / right shift operators. Perform shifts at binary level.

Note that & and && are different in that && “short circuits” if one of the conditions it’s evaluating or false.  Consider the following example:

#include "stdio.h"

int printSomething()
{
	printf("%s", "Something");
	return 1;
}

int main()
{
	int x = 3, y = 2;

	int a = (x > y & y > 5 & printSomething()); //"Something" is printed

	int b = (x > y && y > 5 && printSomething()); //"Something" is not printed.  && operator short circuits and after y > 5 evaluates to false conditions stop being evaluated.

	printf("Example 1: %d \n \n", a);

	printf("Example 2: %d \n \n", b);

	return 0;
}

The | operator is the same as the &, but does OR comparisons.

The ^ operator evaluates whether or not ONLY ONE of the conditions is true:

#include "stdio.h"

int main()
{
	int x = 1, y = 2, z = 3;

	if(y > z ^ x > y ^ x > 0) printf("%s \n \n", "True!"); //Only one condition is true, statement evaluates to boolean true

	if(z > y ^ x > 0) printf("%s \n \n", "Also True!"); //Both conditions are true.  Statement evaluates to boolean false and "Also True!" is not printed

	return 0;
}

Shift operators work at the binary level. Easy way to raise any multiple of 2 to the nth power:

#include "stdio.h"

int main()
{
	int x, z, y = 2, a = 3, r;

	x = y << 2;  //Binary operation.  Bits are shifted two places to the left (001 becomes 100).  This evalutes to 8

	printf("%d \n \n", x);

	z = a << 2;  //Binary operation.  a starts as 011 and bits are shifted two spaces to the left.  a becomes 1100 (12)

	printf("%d \n \n", z);

	r = z >> 2;  //Binary operation.  r shifts z to spaces right.  r is 3.

	printf("%d \n \n", r);
}

Ternary

Seeing this freaked me out when I first started programming, but it’s actually really easy.

#include "stdio.h"

int main()
{
	int x = 1, y = 2, a;

	a = (x > y) ? x : y; //IF x > y, a = x, ELSE, a = y

	printf("%d \n \n", a); //a is equal to y
}

Other operator uses (strings, arrays, objects, etc.)

. //Dot notation for concatenating strings, not to be confused with dot notation like calling a method in ruby or python
+ //Used for concatenating strings. In some languages more complex data types can be joined.
+= //Add one string to another
.= //Concatenate strings
&= //Reference assignment

PHP

$string = 'test';
$stringtwo = 'test2';
$concat = $string . '  ' . $stringtwo; // "test test2"

$concatTwo = '';
$concatTwo .= $string;
$concatTwo .= $stringtwo; //test test2

$ref &= $string; //"test"

JavaScript

var myString = 'test';
var mySecondString = 'test2';

var concat = myString + mySecondString; //value is testtest2

Python uses the same concept:

test = "test"
maybe = "tester"

test + maybe # 'testtester'

In PHP associative arrays can be joined with the + operator. It’s not a good idea to add arrays with numeric keys because only one value will be retained:

$one = array('test');
$two = array('test2');

$three = $one + $two; //$three is now array('test');

$four = array('test' => 'tester');
$five = array('tester=> 'tester2');

$six = $one + $two; //$six is array('test' => 'tester', 'tester' => 'tester2');

At least in the languages I know a bit about, the -. *, % and / operators cannot be used on any non-integer types.

That’s all I got. Hope you learned something!

Posted in Programming | 2 Comments

The difference between a function-like macro and a function in C, C++

I’ve been working my way through some of the open courseware computer science materials that MIT hosts. The past few nights, I’ve been reviewing the “Practical Programming in C” lecture notes and assignments. For the most part, the first few assignments were really easy for me – few new concepts.

One bit that tripped me up were what looked like functions, but were actually macros (I later learned these are called macro-like functions).

Now, I know C is an ancient language and I’m sure this has been discussed thousands of times (or more) – but I still think it warrants a blog post. So here is a macro-like function:

#define squaredM(x) x*x

And here is a function:

double squaredF(double x)
{
    return x*x;
}

Here is what looks like the same code calling functions that do the same things:
double ans = 18.0 / squaredM(2+1);
double ans = 18.0 / squaredF(2+1);

You might assume that both pieces of code would be handled the same way. And you’d be wrong. I did not assume that both pieces of code would be handled the same way, but I also made an incorrect assumption how a function-like macro worked (I did not already know). The key difference is that a function-like macro is pre-processed and then compiled, while the function is compiled. In plain english, that means that when you compile the program, the preprocessor essentially creates a new piece of code, with the macro substituted in, and then compiles:

double ans = 18.0 / 2+1*2+1;

Order of operations tells us that division / multiplication, left to right, should happen first. So you actually end up with 9 + 2 + 1.

In the second example, using a function, 2+1 is already a float of 3.0 when it is received by squaredF. This may not ever be useful to you, but I thought it was cool and wanted to share it.

References:
Wikipedia (C Preprocessor)
IBM AIX Compilers Reference
MIT Open Courseware Answers

Posted in C Programming Language, C++ | 3 Comments