Nikola Brežnjak blog - Tackling software development with a dose of humor
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Home
Daily Thoughts
Ionic
Stack Overflow
Books
About me
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Nikola Brežnjak blog - Tackling software development with a dose of humor
Programming

Code Complete 2 – Steve McConnell – General Control Issues

I just love Steve McConnell’s classic book Code Complete 2, and I recommend it to everyone in the Software ‘world’ who’s willing to progress and sharpen his skills.

Other blog posts in this series:

  • Part 1 (Chapters 1 – 4): Laying the Foundation
  • Chapter 5: Design in Construction
  • Chapter 6: Working Classes
  • Chapter 7: High-Quality Routines
  • Chapter 8: Defensive programming
  • Chapter 9: Pseudocode Programming Process
  • Chapter 10: General Issues in Using Variables
  • Chapter 11: General Issues in Using Variables
  • Chapter 12: Fundemental Data Types
  • Chapter 13: Unusual Data Types
  • Chapter 15: Using Conditionals
  • Chapter 16: Controlling Loops
  • Chapter 17: Unusual Control Structures
  • Chapter 18: Table-Driven Methods

Boolean Expressions

Except for the simplest control structure, the one that calls for the execution of statements in sequence, all control structures depend on the evaluation of boolean expressions.

Using true and false for Boolean Tests

Use the identifiers true and false in boolean expressions rather than using values like 0 and 1.

You can write clearer tests by treating the expressions as boolean expressions. For example, write

while ( !done ) ...
while ( a > b ) ...

rather than

while ( done == false ) ...
while ( (a > b) == true ) ...

Using implicit comparisons reduces the numbers of terms that someone reading your code has to keep in mind, and the resulting expressions read more like conversational English.

Making Complicated Expressions Simple

Break complicated tests into partial tests with new boolean variables rather than creating a monstrous test with half a dozen terms, assign intermediate values to terms that allow you to perform a simpler test.

Move complicated expressions into boolean functions if a test is repeated often or distracts from the main flow of the program. For example:

If ( ( document.AtEndOfStream ) And ( Not inputError ) ) And 
    ( ( MIN_LLINES <= lineCount ) And ( lineCount <= MAX_LINES ) ) And 
    ( Not ErrorProcessing() ) Then
    ...
End If

This is an ugly test to have to read through if you’re not interested in the test itself. By putting it into a function, you can isolate the test and allow the reader to forget about it unless it’s important.

If ( DocumentIsValid( document , lineCount, inputError) ) Then
    ' do something other
    ...
End If

If you use the test only once, you might not think it’s worthwhile to put it into a routine. But putting the test into a well-named function improves readability and makes it easier for you to see what your code is doing, and that’s sufficient reason to do it.

Forming Boolean Expressions Positively

I ain’t not no undummy.

~ Homer Simpson

Not a few people don’t have not any trouble understanding a nonshort string of nonpositives-that is, most people have trouble understanding a lot of negatives.

You can do several things to avoid complicated negative boolean expressions in your program:

  • In if statements, convert negatives to positives and flip-flop the code in the if and else clauses
    • You shouldn’t write if ( !statusOK ). Alternatively, you could choose a different variable name, one that would reverse the truth value of the test. In the example, you could replace statusOK with ErrorDetected, which would be true when statusOK was false.
  • Apply DeMorgean’s Theorems to simplify boolean test with negatives
    • DeMorgan’s Theorem lets you exploit the logical relationship between an expression and version of the expression that means the same thing because it’s doubly negated. For example:

if ( !displayOK || !printerOK ) ...

This is logically equvalent ot the following:

if ( !( displayOK && printerOK ) ) ...

Using Parentheses to Clarify Boolean Expressions

Using parentheses isn’t like sending a telegram: you’re not charged for each character – the extra characters are free.

Knowing How Boolean Expressions Are Evaluated

The pseudocodeThe pseudocode example of when “short-circuit” or “lazy” evaluation is necessary:

while( i < MAX_ELEMENTS and item[ i ] <> 0 ) ...

If the whole expression is evaluated, you’ll get an error on the last pass through the loop. The variable i equals MAX_ELEMENTS, so the expression item[ i ] is an array-index error.

In the pseudocode, you could restructure the test so that the error doesn’t occur:

while ( i < MAX_ELEMENTS )
    if (item[ i ] <> 0 ) then 
        ...

C++ uses short-circuit evaluation: if the first operand of the and is false, the second isn’t evaluated because the whole expression would be false anyway.

Write Numeric Expressions in Number-Line Order

MIN_ELEMENTS <= i and i <= MAX_ELEMENTS

The idea is to order the elements left to right, from smallest to largest. In the first line, MIN_ELEMENTS and MAX_ELEMENTS are the two endpoints, so they go at the ends. The variable i is supposed to be between them, so it goes in the middle.

Compound Statements (Blocks)

A “compound statement” or “block” is a collection of statements that are treated as a single statement for purposes of controlling the flow of a program. Compound statements are created by writing { and } around a group of statements in C++, C#, C, and Java.

⚠️ Use the block to clarify your intentions regardless of whether the code inside the block is 1 line or 20.

Taming Dangerously Deep Nesting

Excessive indentation, or “nesting,” has been pilloried in computing literature for 25 years and is still one of the chief culprits in confusing code.

Many researchers recommend avoiding nesting to more than three or four levels (Myers 1976, Marca 1981, and Ledgard and Tauer 1987a). Deep nesting works against what Chapter 5 describes as Software’s Major Technical Imperative: Managing Complexity. That is reason enough to avoid deep nesting.

It’s not hard to avoid deep nesting. If you have deep nesting, you can redesign the tests performed in the if and else clauses or you can break the code into simpler routines. Here are the tips to reduce the nesting depth:

Simplify the nested if by testing part of the condition

if ( inputStatus == InputStatus_Success ) {
   // lots of code
   ...
   if ( printerRoutine != NULL ) {
    // lots of code
        ...
        if ( SetupPage() ) {
            // lots of code
            ...
            if ( AllocMem( &printData ) ) {
                // lots of code
                ... 
        }
    } 
}

Here’s the code revised to use retesting rather than nesting:

if ( inputStatus == InputStatus_Success ) {
   // lots of code
   ...
   if ( printerRoutine != NULL ) {
      // lots of code
... }
}
if ( ( inputStatus == InputStatus_Success ) &&
   ( printerRoutine != NULL ) && SetupPage() ) {
   // lots of code
   ...
   if ( AllocMem( &printData ) ) {
      // lots of code
      ...
    } 
}

This is a particularly realistic example because it shows that you can’t reduce the nesting level for free; you have to put up with a more complicated test in return for the reduced level of nesting.

Simplify a nested if by using break

If some condition in the middle of the block fails, execution continues at the end of the block.

do {
   // begin break block
   if ( inputStatus != InputStatus_Success ) {
      break; // break out of block
   }
   // lots of code
   ...
   if ( printerRoutine == NULL ) {
      break; // break out of block
   }
   // lots of code
   ...
   if ( !SetupPage() ) {
      break; // break out of block
   }
   // lots of code
   ...
   if ( !AllocMem( &printData ) ) {
      break; // break out of block
   }
   // lots of code
   ...
} while (FALSE); // end break block

This technique is uncommon enough that it should be used only when your entire team is familiar with it.

Convert a nested if to a set of if-then-elses

If you think about a nested if test critically, you might discover that you can reorganize it so that it uses if-then-elses rather than nested ifs. Suppose you have a busy decision tree like this:

if ( 10 < quantity ) {
   if ( 100 < quantity ) {
      if ( 1000 < quantity ) {
        discount = 0.10;
      } 
      else {
        discount = 0.05;
      }
    }
    else {
      discount = 0.025;
    } 
}
else {
   discount = 0.0;
}

You can reorganize the code for better readability and reduced complexity:

if ( 1000 < quantity ) {
   discount = 0.10;
}
else if ( 100 < quantity ) {
   discount = 0.05;
}
else if ( 10 < quantity ) {
   discount = 0.025;
}
else {
   discount = 0;
}

Convert a nested if to a case statement

You can recode some kinds of tests, particularly those with integers, to use a case statement rather than chains of ifs and elses. You can’t use this technique in some languages, but it’s a powerful technique for those in which you can.

Factor deeply nested code into its own routine

If deep nesting occurs inside a loop, you can often improve the situation by putting the inside of the loop into its own routine. This is especially effective if the nesting is a result of both conditionals and iterations. Leave the if-then-else branches in the main loop to show the decision branching, and then move the statements within the branches to their own routines.

The new code has several advantages. First, the structure is simpler and easier to understand. Second, you can read, modify, and debug the shorter while loop on one screen; it doesn’t need to be broken across the screen or printed- page boundaries.

⚠️ Complicated code is a sign that you don’t understand your program well enough to make it simple.

A Programming Foundation: Structured Programming

The core of structured programming is a simple idea that a program should use only one-in, one-out control constructs (also called single-entry, single-exit control constructs).

A structured program progresses in an orderly, disciplined way, rather than jumping around unpredictably. You can read it from top to bottom, and it executes in much the same way.

The Three Components of Structured Programming

  • Sequence
    • A sequence is a set of statements executed in order. Typical sequential statements include assignments and calls to routines.
  • Selection
    • A selection is a control structure that causes statements to be executed selectively. The if-then-else statement is a common example.
  • Iteration
    • An iteration is a control structure that causes a group of statements to be executed multiple times. An iteration is commonly referred to as a “loop”.
  • The core thesis of structured programming is that any control flow whatsoever can be created from these three constructs of sequence, selection, and iteration (Böhm Jacopini 1966).

How important is complexity?

The competent programmer is fully aware of the strictly limited size of his own skull; therefore he approaches the programming task in full humility

~ Edsger Dijkstra

Control-flow complexity is important because it has been correlated with low reliability and frequent errors.

Books

Leading Snowflakes by Oren Ellenbogen

These are my notes from an awesome and more importantly practical book called Leading Snowflakes by Oren Ellenbogen. This is a very good book if you just moved from a developer role to Lead or Manager.

Switch between Manager and Maker models

  • NSC! – Never stop coding!
  • Schedule Maker and Manager times on your calendar

No one is being promoted to a managerial position to increase their productivity. We already proved our capabilities there. Our job as managers is to amplify our teammates. Our job is to ask the right questions, to encourage people to think, to challenge, to inspire.

The only way we can keep our edge is by continuously practicing our Maker skills, even if it’s on a smaller scale. Make it easy to pick small tasks you can take. If you’ve got 3 hours to be productive, it would feel counter-productive to use this time to think of tasks instead of making them happen.

Code Review Your management decisions

  • WHEN/WHO/THE DILEMMA/THE DECISION MADE/RETROSPECTION/DID I SHARE THIS?
  • discuss these dilemmas with your boss and see how he would have handled it
  • discuss dilemmas with another engineering manager and review each other decisions
  • do a retrospection every day for ten mins
  • do a retrospection once a month for 1 hour

People quit their boss, not their job

Receiving constant feedback is the fastest way to learn

Confront and challenge your teammates

  • email summaries of your 1on1’s
  • care deeply about your team but don’t care about what they think of you
  • The Asshole Checklist: a) Did I show empathy (not sympathy) b) Did I clarify my expectations c) Did I practice what I just preached
  • share harsh feedback if needed no matter what
  • don’t go helping others with their tasks
  • share your failures with the team

If you want to achieve anything in this world, you have to get used to the idea that not everyone will like you.

I used to send a summary of my conversations with my teammates including my concrete examples and recommended steps. Then, I added how I understood the other side and the next action items we agreed on. I asked them to reply back to this email with their feedback if I got it wrong or they have anything else to add. That email was archived (I had a label per teammate), and used as a way to congratulate them on their progress or to figure out together why a particular pattern keeps emerging.

Not making a decision is equally important and explicit as making one

We also have to keep in mind that bored people quit. Engineers want to improve and get better over time. They want to learn new techniques. They want to tackle harder problems. They want to gain the respect of their peers and the organization they’re a part of. They enjoy new challenges; they appreciate different solutions. It’s our responsibility to help them grow. If we’re not giving our teammates feedback and challenging them, they will become unhappy (and bored) and will eventually leave.

Teach how to get things done

  • show how something is done
  • your job is to help someone else succeed
  • small increments (1-3hrs per task)
  • write docs after the feature is finished
  • see if you can have someone teach others

A great way to amplify teaching is by showing someone else how to get things done, rather than telling them what should be done

Managers should exist for only one reason. To help those who work underneath them be successful and succeed.

Delegate tasks without losing quality or visibility

  • make a list of things you’re doing today and see which ones you can start delegating
  • use the spreadsheet from the book
  • use the one-pager template from the book

Ask yourself two questions for each task:

  • Does it utilize my unique strength and responsibilities as a manager?
  • Does it serve the leader I want to become in the long-run (does it push me out of my comfort zone)?

The idea is to define only what we expect to see happening and not how we expect them to get there

Build trust with other teams in the organization

  • in the priority meetings list three priorities that are most important for you in the next week, but acknowledge that you know what is expected of you
  • TEAM is a group of people that TRUST each other
  • There is no I in TEAM
  • ‘Thank you’ email (or public praise) for a feature well done
  • Internal tech talks
  • Cross-team exchange program
  • Tracking our team’s output in a simple spreadsheet
  • Pizzability

Sitting down with other teams and watching how our product is being used could create a better understanding of the value we produce

Premature optimization is the root of all evil – it is the same logic we should apply when we are optimizing our process.

Don’t fall in love with the solution you’ve built, but with the problem, you’re trying to solve

Automated Testing can decrease the time to deliver each feature and so increase efficiency

Optimize for business learning

Startup Metrics for Pirates: AARRR!:

  • Acquisition
  • Activation
  • Retention
  • Referals
  • Revenue

Spend 80% on tweaking features and 20% on developing new features.

Technical Debt is less scary than getting out of business

Companies fail when they stop asking what they would do if they were started today, and instead just iterate on what they’ve already done.

Use inbound recruiting to attract better talent

  • Answer questions on StackOverflow for 1hr/week
  • Guest blog posts or repost your posts on Medium or dev.to
  • Have hackathons
  • Birthday pics to Instagram, Facebook, Blog. Also do a video maybe
  • Give talks
  • Have side projects

It’s so hard to find great employees these days – everyone, all the time.

Instagram talked about their unique infrastructure and lessons learned a year before they were acquired by Facebook for 1 billion dollars.

Make something people want includes making a company that people want to work for. — Sahil Lavingia

The goal of a successful Inbound Recruiting tactic is to cause a wow factor for our future candidate. The best case scenario would be that this person will sit at home, read our content or play with our project and say oh wow, that’s amazing! I wish I could work there.

Build a scalable team

  • Vision
  • Core values
  • Self-balanced
  • Sense of accomplishment
  • Who is putting down fires? – get him to distribute knowledge and mentor others to get the job done
  • Who is an expertise bottleneck – same as above
  • Who is not building trust?
  • On your 1on1’s ask “What is the worst thing about working here?”

Own it. Never let someone else fix our mess: we understand that sometimes it’s not our fault, but we don’t believe in making excuses and pointing fingers. We believe in getting things done and take full ownership of our deliveries

If someone is kicking ass, it’s our job to recognize and celebrate it together. Most chances are, we’ll see each other on a daily basis more than we see our families. Let’s make sure we enjoy each other’s companionship.

Passion to learn & get better every single day is an agile state of mind: constant feedback, constant improvement, baby steps for large change.

Books

Coaching for performance – Sir John Whitmore

Here are my notes from the book Coaching for performance by Sir John Whitmore.

Coaching focuses on future possibilities, not past mistakes.

Coaching is unlocking peoples potential to maximize their own performance. It is helping them to learn rather than teaching them.

If blame and criticism are a prevalent communication style and this doesn’t change, relationship failure can be predicted with over 90% accuracy.

Of the spoken word: 7% in words, 38% in the way the words were said, 55% facial expression.

I think this person:
– Is a problem
– Has a problem
– Is on a learning journey and is capable, resourceful and full of potential

Intentionality – set a clear intention for a meeting. 2 min before a meeting: “if the meeting would wildly exceed your expectations, what would happen?” No limits!

Questions for building a great team:
– What would the dream or success look for us working together?
– What would the worst case look like
– What’s the best way for us to achieve success or dream
– What do we need to be mindful of to avoid the worst case
– What permissions each of us wants from each other
– What will we do when things get hard?

Open questions:
– What do you want to achieve
– What’s happening at the moment
– How would you like it to be
– What’s stopping you
– What’s helping you
– What problems might there be
– What can you do
– Who can help you
– Where can you find out more
– What will you do

Don’t ask WHY question => ask “what were the reasons” instead

Don’t ask HOW question => ask “what are the steps” instead

Top 10 questions in coaching:
– If I wasn’t here what would you do
– If you knew the answer, what would it be
– What if there were no limits
– What advice would you give to your friend in the same situation
– Imagine having a dialog with the wisest person you know; what would they tell you to do
– What else?
– What would you like to explore next
– I don’t know where to go next, where would you like to go
– What is the real issue
– What is your commitment on a scale from 1 to 10 to doing it. What can you do in doing it

1on1s:
– Goal setting for the sessions (both long and short-term)
– What do you want?
– Reality check to explore the current situation
– Where are you now?
– Options and alternative strategies
– What could you do?
– Will – What is to be done, when, by whom, and a will to do it
– What will you do?

SMART, PURE and CLEAR goals

Having a big dream brings as much work as a small dream.

To set up accountability:
– What will you do
– When
– How will I know

70 learning through experience on the job
20 learning from other people
10 formal learning

Feedback framework:
– What happened
– What have you learned
– How to use this knowledge in the future

Discussion may be facilitated by the team leader but what happens should be decided by team members.

Bonding opportunity by doing something together.

Our true values reside within us and at the deepest level, those values are universal.

Programming

Code Complete 2 – Steve McConnell – Table-Driven Methods

I just love Steve McConnell’s classic book Code Complete 2, and I recommend it to everyone in the Software ‘world’ who’s willing to progress and sharpen his skills.

Other blog posts in this series:

  • Part 1 (Chapters 1 – 4): Laying the Foundation
  • Chapter 5: Design in Construction
  • Chapter 6: Working Classes
  • Chapter 7: High-Quality Routines
  • Chapter 8: Defensive programming
  • Chapter 9: Pseudocode Programming Process
  • Chapter 10: General Issues in Using Variables
  • Chapter 11: General Issues in Using Variables
  • Chapter 12: Fundemental Data Types
  • Chapter 13: Unusual Data Types
  • Chapter 15: Using Conditionals
  • Chapter 16: Controlling Loops
  • Chapter 17: Unusual Control Structures

Table-driven code can be simpler than complicated logic using ifs. Suppose you wanted to classify characters into letters, punctuation marks, and digits; you might use a logic like this one (Java):

if ( ( ( 'a' <= inputChar ) && (inputChar <= 'z' ) )  || ( ( 'A' <= inputChar ) && (inputChar <= 'Z' ) ) ) {
    charType = CharacterType.Letter;
}
else if ( ( inputChar == ' ' ) || ( inputChar == ',' ) ||( inputChar == '.' ) || ( inputChar == '!' ) || 
    ( inputChar == '(' ) || ( inputChar == ')' ) || 
    ( inputChar == ':' ) || ( inputChar == ';' ) ||
    ( inputChar == '?' ) || ( inputChar == '-' ) ) {

    charType = CharacterType.Punctuation;
} else if ( ( '0' <= inputChar ) && ( inputChar <= '9' ) ) {
    charType = CharacterType.Digit;
}

Two Issues in Using Table-Driven Methods:

  • how to look up entries in the table
  • what to store in the table
    • the result of table lookup can be data, but also an action. In such case, you can store a code that describes the action, or in some languages, you can store a reference to the routine that implements the action. In either of these cases, tables become more complicated.

How to look up entries in the table

You can use some data to access a table directly. If you need to classify the data by month, for example, you can use an array with indexes 1 through 12.

Other data is too awkward to be used to look up a table entry directly. If you need to classify data by Social Security Number, for example, you can’t use the Social Security Number to key into the table directly unless you can afford to store 999-99-9999 entries in your table. You’re forced to use a more complicated approach. Here’s a list of ways to look up an entry in a table:

  • Direct access
  • Indexed access
  • Stair-step access

Direct Access Tables

Suppose you need to determine the number of days per month (forgetting about leap year, for the sake of argument). A clumsy way to do it, of course, is to write a large if statement:

if ( month == 1 ) {
    days = 31;
} else if ( month == 2 ) {
    days = 28;
}
// ...for all 12 months, you get the point
else if ( month == 12 ) {
    days = 31;
}

An easier and more modifiable way to perform the same function is to put the data in a table:

int daysPerMonth [12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

Now, instead of using the long if statement, you can just use simple array access to find out the number of days in a month:

days = daysPerMonth[ month - 1 ];

Indexed access Tables

Sometimes a simple mathematical transformation isn’t powerful enough to make the jump from data like Age to a table key.

Suppose you run a warehouse and have an inventory of about 100 items. Suppose further that each item has a four-digit part number that ranges from 0000 through 9999.

First, if each of the entries in the main lookup table is large, it takes a lot less space to create an index array with a lot of wasted space than it does to create a main lookup table with a lot of wasted space.

For example, suppose that the main table takes 100 bytes per entry and that the index array takes 2 bytes per entry. Suppose that the main table has 100 entries and that the data used to access it has 10,000 possible values.

In such a case, the choice is between having an index with 10,000 entries or the main data member with 10,000 entries. If you use an index, your total memory use is 30,000 bytes. If you forgo the index structure and waste space in the main table, your total memory use is 1,000,000 bytes.

That means you waste 97% less memory with indexed access tables.

Stair-Step Access Tables

Another kind of table access is the stair-step method. This access method isn’t as direct as an index structure, but it doesn’t waste as much data space.

The general idea of stair-step structures is that entries in a table are valid for ranges of data rather than for distinct data points.

For example, if you’re writing a grading program, here’s a range of grades you might have to program:

> 90.0% A
< 90.0% B
< 75.0% C
< 65.0% D
< 50.0% F

This is an ugly range for a table lookup because you can’t use a simple data-transformation function to key into the letters A through F. An index scheme would be awkward because the numbers are floating points. You might consider converting the floating-point numbers to integers, and in this case, that would be a valid design option, but for the sake of illustration, this example will stick with floating point.

Here’s the code in Visual Basic that assigns grades to a group of students based on this example.

' set up data for grading table
Dim rangeLimit() As Double = { 50.0, 65.0, 75.0, 90.0, 100.0 }
Dim grade() As String = { "F", "D", "C", "B", "A"}
maxGradeLevel = grade.Length - 1
...
' assign a grade to a student based on the student's score
gradeLevel = 0
studentGrade = "A"
while ( ( studentGrade = "A" ) and ( gradeLevel < maxGradeLevel) ) 
    If ( studentScore < rangeLimit( gradeLevel ) ) Then
        studentGrade = grade( gradeLevel )
    End If
    gradeLevel = gradelevel + 1
wend

Although this is a simple example, you can easily generalize it to handle multiple students, multiple grading schemes, and changes in the grading scheme.

The advantage of this approach over other table-driven methods is that it works well with irregular data. The grading example is simple in that although grades are assigned at irregular intervals, the numbers are “round,” ending with 5s and 0s. The stair-step is equally well suited to data that doesn’t end neatly with 5s and 0s. You can use the stair-step approach in statistics work for probability distributions with numbers like this:

Probability Insurance Claim Amount
0.456935 $0.00
0.546654 $254.32
0.627782 $514.77
0.771234 $717.82

Ugly numbers like these defy any attempt to come up with a function to neatly transform them into table keys. The stair-step approach is the answer.

⚠️ Tables can provide an alternative to complicated logic, so ask yourself whether you could simplify by using a lookup table.

Programming

Code Complete 2 – Steve McConnell – Unusual Control Structures

I just love Steve McConnell’s classic book Code Complete 2, and I recommend it to everyone in the Software ‘world’ who’s willing to progress and sharpen his skills.

Other blog posts in this series:

  • Part 1 (Chapters 1 – 4): Laying the Foundation
  • Chapter 5: Design in Construction
  • Chapter 6: Working Classes
  • Chapter 7: High-Quality Routines
  • Chapter 8: Defensive programming
  • Chapter 9: Pseudocode Programming Process
  • Chapter 10: General Issues in Using Variables
  • Chapter 11: General Issues in Using Variables
  • Chapter 12: Fundemental Data Types
  • Chapter 13: Unusual Data Types
  • Chapter 15: Using Conditionals
  • Chapter 16: Controlling Loops

Recursion

For a small group of problems, recursion can produce simple, elegant solutions. For a slightly larger group of problems, it can produce simple, elegant, hard-to-understand solutions. ?

Java Example:

void QuickSort( int firstIndex, int lastIndex, String [] names ) {
    if ( lastIndex > firstIndex ) {
        int midPoint =  Partition( firstIndex, lastIndex, names );
        QuickSort( firstIndex, midPoint-1, names );
        QuickSort( midPoint+1, lastIndex, names );            
    }
}

In this case, the sorting algorithm chops an array in two and then calls itself to sort each half of the array. When it calls itself with a subarray that’s too small to sort-such as ( lastIndex <= firstIndex ) – it stops calling itself.

Tips for Using Recursion

  • Make sure the recursion stops – Check the routine to make sure that it includes a nonrecursive path.
  • Limit recursion to one routine – Cyclic recursion (A calls B calls C calls A) is dangerous because it’s hard to detect.
  • Keep an eye on the stack – With recursion, you have no guarantees about how much stack space your program uses. To prevent stack overflow, you can use safety counter and set the limit low enough or allocate objects on the heap using new.
  • Don’t use recursion for factorials or Fibonacci numbers – You should consider alternatives to recursion before using it. You can do anything with stacks and iteration that you can do with recursion. Sometimes one approach works better, sometimes the other does. Consider both before you choose either one.

goto

You might think the debate related to gotos is extinct, but a quick trip through modern source-code repositories like SourceForge.net shows that the goto is still alive and well and living deep in your company’s server.

The Argument Against gotos

The general argument against gotos is that code without them is higher-quality code
+ Dijkstra observed that the quality of the code was inversely proportional to the number of gotos the programmer used
+ Code containing gotos is hard to format
+ Use of gotos defeats compiler optimizations
+ The use of gotos leads to the violation of the principle that code should flow strictly from top to bottom

The Arguments for gotos

The argument for the goto is characterized by advocacy of its careful use in specific circumstances rather than its indiscriminate use.

A well-placed goto can eliminate the need for duplicate code. Duplicate code leads to problems if the two sets of code are modified differently. Duplicate code increases the size of the source and executable files. The bad effects of the goto are outweighed in such a case by the risks of duplicate code.

Good programming doesn’t mean eliminating gotos. Methodical decomposition, refinement, and selection of control structures automatically lead to goto-free programs in most cases. Achieving goto-less code is not the aim but the outcome, and putting the focus on avoiding gotos isn’t helpful.

Summary of Guidelines for Using gotos

Use of gotos is a matter of religion. My dogma is that in modern languages, you can easily replace nine out of ten gotos with equivalent sequential constructs.

  • Use gotos to emulate structured control constructs in languages that don’t support them directly. When you do, emulate them exactly. Don’t abuse the extra flexibility the goto gives you.
  • If goto improve efficiency, document the efficiency improvement so that goto-less evangelists won’t remove it.
  • Limit yourself to one goto label per routine
  • Limit yourself to gotos that go forward, not backward
  • Make sure all gotos labels are used.
  • Make sure a goto doesn’t create unreachable code.

https://t.co/AGH65l2L9F

— Nikola Brežnjak (@HitmanHR) March 12, 2018

Programming

Code Complete 2 – Steve McConnell – Controlling Loops

I just love Steve McConnell’s classic book Code Complete 2, and I recommend it to everyone in the Software ‘world’ who’s willing to progress and sharpen his skills.

Other blog posts in this series:

  • Part 1 (Chapters 1 – 4): Laying the Foundation
  • Chapter 5: Design in Construction
  • Chapter 6: Working Classes
  • Chapter 7: High-Quality Routines
  • Chapter 8: Defensive programming
  • Chapter 9: Pseudocode Programming Process
  • Chapter 10: General Issues in Using Variables
  • Chapter 11: General Issues in Using Variables
  • Chapter 12: Fundemental Data Types
  • Chapter 13: Unusual Data Types
  • Chapter 15: Using Conditionals

“Loop” is a structure that causes a program to repeatedly execute a block of code. Common loop types are for, while, and do-while.

When to use the while loop

If you don’t know ahead of time exactly how many times you’ll want the loop to iterate, use the while loop. Contrary to what some novices think, the test for the loop exit is performed only once each time through the loop, and the main issue concerning while loop is deciding whether to test at the beginning or the end of the loop.

  • while – loop tests condition at the beginning
  • do-while – tests condition at the end, which means that the body of the loop gets executed at least once.
  • loop-with-exit – structure more closely models human thinking. This is the loop in which the exit condition appears in the middle of the loop rather than at the beginning or the end.

When to use the for loop

A for loop is a good choice when you need a loop that executes a specified number of times. If you have a condition under which execution has to jump out of a loop, use a while loop instead.

When to use the foreach loop

It is useful for performing an operation on each member of an array or some other container. It has an advantage of eliminating loop-housekeeping arithmetic and therefore eliminating any chance of errors in the loop-housekeeping arithmetic.

Controlling the loop

You can use two practices. First, minimize the number of factors that affect the loop. Simplify! Simplify! Simplify! Second, treat the inside of the loop as if it were a routine-keep as much control as possible outside the loop.

Entering the loop

  • Enter the loop from one location only
  • Put initialization code directly before the loop – Principle of Proximity advocates putting related statements together.
  • Use while ( true ) for infinite loops – that’s considered a standard way of writing an infinite loop in C++, Java, Visual Basic, and other languages. for(;;) is an accepted alternative.

Processing the middle of the loop

  • Use { and } to enclose the statements in a loop – Use brackets every time. They don’t cost anything in speed or space at runtime, they help readability, and they help prevent errors as the code is modified.
  • Avoid empty loops – In C++ and Java, it’s possible to create an empty loop, one in which the work the loop is doing is coded on the same line as the test that checks whether the work is finished. Here’s an example:
    while( (inputChar = dataFile.GetChar() ) != CharType_Eof ) {
        ;
    }
    

    The loop would be much clearer if it were recoded so that the work it does is evident to the reader:

    do {
        inputChar = dataFile.GetChar();
    } while ( inputChar != CharType_Eof );
    

The new code takes up three full lines rather than that of one line, which is appropriate since it does the work of three lines rather than that of one line.
+ Keep loop-housekeeping chores at either the beginning or the end of the loop – As a general rule, the variables you initialize before the loop are the variables you’ll manipulate in the housekeeping part of the loop.

Exiting the loop

  • Assure that the loop ends
  • Don’t monkey with the loop index of a for loop to make the loop terminate
  • Avoid code that depends on the loop index’s final value

Exiting loops early

The break statement causes a loop to terminate through the normal exit channel; the program resumes execution at the first statement following the loop.

continue causes the program to skip the loop body and continue executing at the beginning of the next iteration of the loop.

Inefficient programmers tend to experiment randomly until they find a combination that seems to work. If a loop isn’t working the way it’s supposed to; the inefficient programmer changes the < sign to a <= sign. If that fails, the inefficient programmer changes the loop index by adding or subtracting 1. Eventually, the programmer using this approach might stumble onto the right combination or simply replace the original error with a more subtle one. Even if this random process results in a correct program, it doesn’t result in the programmer’s knowing why the program is correct.

How long should a loop be?

Make your loops short enough to view all at once. Experts have suggested a loop-length limit of one page (about 50 lines of code). When you begin to appreciate the principle of writing simple code, however, you’ll rarely write loops longer than 15 or 20 lines.

Creating loops easily – from the inside out

If you sometimes have trouble coding a complex loop, which most programmers do, you can use a simple technique to get it right the first time.

Here’s the general process:
+ Start with one case.
+ Code that case with literals.
+ Then indent it, put a loop around it, and replace the literals with loop indexes or computed expressions.
+ Put another loop around that, if necessary, and replace more literals.
+ Continue the process as long as you have to
+ When you finish, add all the necessary initializations.

Since you start at the simple case and work outward to generalize it, you might think of this as coding from the inside out.

Books

Executed – RR Haywood

Executed is a second book from the Extracted trilogy. Same as with the first book (Extracted), I don’t have any special quotes, but I really enjoyed the story and characters; Harry, Safa, and Ben just rock!

Taken from the official website:

The team of heroes extracted from their timelines to stop the impending apocalypse didn’t think they needed a leader.

But they’ve got one anyway

With their mission in tatters, Miri has been called in to steady the ship. And to focus them on their assignment: preventing the end of the world.

The problem is, the world doesn’t know it’s in danger. With governments pursuing them relentlessly, attempting to steal the time-travel device to use for their own ends, the heroes are on the run—fighting for survival in a world they’re supposed to save.

Meanwhile, Miri has motives of her own. And when the existence of a second device is discovered, the team’s mission and their lives are in mortal danger…

Can’t wait for the final book in the trilogy! ?

⚠️ In case you’re into stories that deal with time travel then please recommend!

I just read a great sequel #Executed by @RRHaywood https://t.co/3IIHEFf0yF

— Nikola Brežnjak (@HitmanHR) November 22, 2017

Books

Finding Ultra – Rich Roll

My favorite quotes from a remarkable biography Finding Ultra: Rejecting Middle Age, Becoming One of the World’s Fittest Men, and Discovering Myself by Rich Roll, a man who finished EPIC5 in under a week: each day a full ironman-distance triathlon (2.4 mile swim, 112-mile bike and 26 mile run) on 5 different islands of Hawaii. Respect!

You can set a positive example. But you simply can not make someone change.

Spirolina

Pursue what’s in your heart and the Universe will conspire to support you.

The prize never goes to the fastest guy,” Chris replied. “It goes to the guy who slows down the least.” True in endurance sports. And possibly even truer in life.

David Goggins quote I’d read years back—the idea that when you believe you’ve reached your absolute limit, you’ve only tapped into about 40 percent of what you’re truly capable of. The barrier isn’t the body. It’s the mind.

With obstacles comes the opportunity for growth. And if you’re not growing, you’re not living. Do what you love; love those you care about; give service to others; and know that you’re on the right path. There’s a new path waiting for you, too. All you have to do is look for it—then take that first step. If you show up and stay present, that step will eventually become a gigantic leap forward. And then you’ll show us who you really are.

When purpose aligns with faith, there can be no failure and all needs will be met—because the universe is infinitely abundant.

My #notes from a remarkable #book Finding Ultra by Rich Roll https://t.co/rzn7qsigqY

— Nikola Brežnjak (@HitmanHR) November 12, 2017

Books

The Art of Being Brilliant – Andy (Cope & Whittaker)

My favorite quotes from the book The Art of Being Brilliant: Transform Your Life by Doing What Works For You by Andy (Cope &  Whittaker):

Our final thought in this chapter goes to a great quote that seems to sum up a lot of thinking young people nowadays: “The world is passing through troubled times. The young people of today think of nothing but themselves. They have no respect for parents or older people. They are impatient. They talk as if they know everything. And what passes for wisdom with us is foolishness with them. As for the girls; they are forward, immodest and unladylike in speech behavior and dress.”. Hard to disagree. Except that this quotes is from a sermon preached by Peter the Hermit in AD 1274. Seems like young people have always been frowned upon by the older generation. Maybe it’s not the younger generation that needs to change. Maybe it’s up to us to chill out a bit.

A modern prayer (read at a very fast pace ?): “Dear God, help me to slow down and not rush past everything that is important today. Amen.”

10% of life is made up of what happens to you. 90% of life is decided by how you react to the 10%.

  1. Choose to be positive
  2. Understand your impact
  3. Take personal responsibility
  4. Have bouncebackability
  5. Set huge goals
  6. Play to your strengths

The change will not come if we wait for some other person or some other time. We are the ones we’ve been waiting for. We are the change that we seek.

Happy button – don’t wear it out 😉

Failure is only the opportunity to begin again, more intelligently.

Recommended books:

  • The naked leader
  • The naked leader experience
  • S.U.M.O
  • Success intelligence
  • Man’s search for meaning
  • The art of possibility
  • Good to great
  • Average to A+
  • Flourish
  • The Alchemist
  • The monk who sold his Ferrari
  • Do more great work
  • The happiness hypothesis
  • Drop the pink elephant
  • The happiness advantage
  • The pig of happiness
  • The yes man

My #notes from the #book The Art of Being Brilliant by Andy (Cope & Whittaker) https://t.co/qfd6hcLYJ4

— Nikola Brežnjak (@HitmanHR) November 4, 2017

Books

Extracted – RR Haywood

I don’t read a lot of fiction books, but recently I stumbled upon a fiction book that I liked quite a bit. I don’t have any special quotes from the book Extracted by RR Haywood, as I usually do, but the book itself captivated me quite a bit. I was drawn to the story and listening (Audible ❤️) onward to learn what will happen. This is the first book in the trilogy and I can’t wait to start the second one.

Taken from the official website:

In 2061, a young scientist invents a time machine to fix a tragedy in his past. But his good intentions turn catastrophic when an early test reveals something unexpected: the end of the world.

A desperate plan is formed. Recruit three heroes, ordinary humans capable of extraordinary things, and change the future.

Safa Patel is an elite police officer, on duty when Downing Street comes under terrorist attack. As armed men storm through the breach, she dispatches them all.

‘Mad’ Harry Madden is a legend of the Second World War. Not only did he complete an impossible mission—to plant charges on a heavily defended submarine base—but he also escaped with his life.

Ben Ryder is just an insurance investigator. But as a young man he witnessed a gang assaulting a woman and her child. He went to their rescue, and killed all five.

Can these three heroes, extracted from their timelines at the point of death, save the world?

So, in case you’re into stories which deal with time travel (like I am ?), then you’ll like this one. Oh, btw, in case you know some other book that deals with the similar concept, then please recommend!

#time-travel #books anyone? I liked Extracted by RR Haywood https://t.co/RTOiv2t45C

— Nikola Brežnjak (@HitmanHR) October 21, 2017

Page 3 of 12« First...«2345»10...Last »

Recent posts

  • Discipline is also a talent
  • Play for the fun of it
  • The importance of failing
  • A fresh start
  • Perseverance

Categories

  • Android (3)
  • Books (114)
    • Programming (22)
  • CodeProject (35)
  • Daily Thoughts (77)
  • Go (3)
  • iOS (5)
  • JavaScript (127)
    • Angular (4)
    • Angular 2 (3)
    • Ionic (61)
    • Ionic2 (2)
    • Ionic3 (8)
    • MEAN (3)
    • NodeJS (27)
    • Phaser (1)
    • React (1)
    • Three.js (1)
    • Vue.js (2)
  • Leadership (1)
  • Meetups (8)
  • Miscellaneou$ (77)
    • Breaking News (8)
    • CodeSchool (2)
    • Hacker Games (3)
    • Pluralsight (7)
    • Projects (2)
    • Sublime Text (2)
  • PHP (6)
  • Quick tips (40)
  • Servers (8)
    • Heroku (1)
    • Linux (3)
  • Stack Overflow (81)
  • Unity3D (9)
  • Windows (8)
    • C# (2)
    • WPF (3)
  • Wordpress (2)

"There's no short-term solution for a long-term result." ~ Greg Plitt

"Everything around you that you call life was made up by people that were no smarter than you." ~ S. Jobs

"Hard work beats talent when talent doesn't work hard." ~ Tim Notke

© since 2016 - Nikola Brežnjak