Table of Contents

About Programming Style
1.0 Foreword
2.0 The Major Programming Styles
3.0 Documenting Code
4.0 Programming Language Statements
5.0 Object Oriented Programming
6.0 Further Reading

About Programming Style


1.0 Foreword

1.1 Putting Quality In Software Development

Note: Every programming language has its own conventions, but same basic guidelines can be applied to many languages. The ideas in this document are applicable at least to languages: C, C++, C#, Mono, Java, PHP, Perl and Javascript. The ideas in section Basic Principles can be adapted to virtually any software project.

To be able to write programs that are not only correct but also understandable and maintainable requires discipline. These skills evolve as one becomes a more experienced programmer.

Well written programs will save time whenever examined, changed or reviewed. If the outcome is unreadable, it will be difficult and time-consuming to find and correct the errors in it. Making changes and testing those changes also take more time and cost valuable human resources.

[Picture 1.  pic/comics-geekandpoke-00-all.png]
Picture 1. Left: Simply Explained: Code Reuse 2009-12-03. Right: Behind The Lines 2010-09-23. By Oliver Widder, Webcomics Geek And Poke.

Projects always grow in size and become more complex in time. Being able to respond timely manner to bug reports like security flaws depends on the modularity and clarity of the implemented design. Part of the clarity becomes from the technical measures like using good names for directories, files, classes, methods, variables and by using proper structure (like indentation). Part of it comes from recording enough information in comments for the reader to understand how a program is designed and why. The rest comes from applying principle of KISS everywhere; by using simple building blocks that are elegant; methods and classes that illuminate their clarity.

"We discussed the removability of code. Before we get into it, let’s agree on one thing. Source code is a liability, not an asset. The more lines of code you have, the more time you will spend maintaining them, the more bugs you will have, the harder it will be to implement new code. When it comes to code, less is better." In blog post Removability of code, Sami Honkinen, 2012-12-06.

Merely producing code that works is like saying that a car "works". But what kind of motor drives the car is important. The engine may leak, drip oil, the car may have bad batteries and exterior covered in rust. It may have tires that slip on rain. Arguable the car "works" but at the same time most people would hesitate to run such a car for long. Writing programs is best treated like making good cars, houses or books. The basis, the style, is the key to everything.

A consistent style is important for all projects that share files. The code (or text) communicates the ideas from reader to reader. The selection of one style over another is a matter of convention. Switching from one project to another may also change the requirements in style. Good style, being a subjective matter, is difficult to concretely categorize; however, there are several elements common to a large number of programming styles. A competent programmer can fluently adapt to the style being valid for the project at hand.

"You have to understand how The Maintainer thinks. He has your giant program. He has no time to read it all, much less understand it. He wants to rapidly find the place to make his change, make it and get out and have no unexpected side effects from the change. (...) by subtly violating convention(s), you force him to read every line of your code with a magnifying glass." (From How To write unmaintainable code, section General Principles)

"whatever style you use, please use it consistently, since a mixture of styles within one program tends to look ugly. If you are contributing changes to an existing program, please follow the style of that program." (GNU Coding Standards, section 5.1 Formatting Your Source Code)

"I like how Agile treats it. Code is common and belongs to everybody. It's not your own pet project, so express your individuality not in code, but in clothing or decorating your office. Get a perm. You should not be able to distinguish who wrote the code, ever. When your team can achieve this, all members of your team will benefit by not suffering cognitive dissonance when reading unfamiliar code." (spaceace on April 13, 2009 5:45 AM in one of the comments of Jef Atwood's Coding Horror blog about tabs vs spaces. Jeff is the founder of famous Stack Overflow site)

"When it's 2:30 in the morning on the deadline day, the LAST thing I need is to discover a crash bug in a piece of code that: 1) wasn't written to the company's coding standard. 2) was written with variables like a and f everywhere. 3) mixes tabs and spaces to such a degree that it's simply not possible to line up anything at all. 4) has been hacked upon by so many other engineers who were simply too afraid of pissing off everyone else to take a few minutes to reformat the damn code so I, at 2:30 am, could make sense of it. While I enjoy the friendship of my fellow workers, I have to remind everyone that when you work for a company, you're not there to make friends and be sensitive to other co-worker's feelings. If the company has a coding standard, and you're not adhering to it 100%, you'll get no sympathy from me when your code gets mercilessly reformatted to adhere to the coding standard. And don't cry about it; Learn from it and be thankful (...)" (John W on April 13, 2009 11:09 AM in one of the comments of Jef Atwood's Coding Horror blog about tabs vs spaces)

The object of a project should not focus only in getting the current job done, but to provide sustained, long-term viability and growth which comes from continually responding to changed needs and getting better at doing so. The Agile methodologies have shown that conservatism to resist change and keep the status quo with reasonings like these:

"Unless you have a good reason to change it, don't change it" or "If it ain't broken, don't fix it" (Compare these slogans to article Getting out of the Software Mud Pit by Steve Adolph)

will produce mediocrity and inherently lead to unsustainable code base where parts are kept together with patches and gum. The "No change" attitude and tight project management is a blockade to innovating the product to evolve better and faster than competitors.

"Software is like plant that grows ... You can't predict its exact shape or how big it will grow; you can control its growth only to a limited degree" (Patterns of Software by Richard Gabriel, p. 126)

Software is always incomplete and broken by nature due to shifting and evolving requirements. Constantly evaluating and refactoring the code can make gum and patches unnecessary. The healthiness is ensured at all times with systematic approach, applying style, keeping documentation in shape and using continuous testing practices.

Making things readable by others is the measure that helps grasping the concept "what a good style is all about".

[Picture 2.  pic/tiobe-coding-standard-methodology.gif]
Picture 2. The coding standard is the first step in the strategy towards high quality software. (2007-01-23 picture from: TIOBE Coding Standard Methodology; <http://www.tiobe.com/standards/index.htm>

1.2 Basic Principles

"Functions should be short and sweet, and do just one thing. They should fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24 and A4 paper), and do one thing and do that well (...) Another measure of the function is the number of local variables. They shouldn't exceed 5-10, or you're doing something wrong. Re-think the function, and split it into smaller pieces." (Chapter 6: Functions).

"How many words per line can a person scan, and still be able to grasp the content of the line in the context of the surrounding lines? Printing and publishing typographers figured out a long time ago that most people can read no more than 10 to 12 words per line before they have trouble differentiating lines from each other. (A word is counted as five characters on average.) Even allowing for a 25% to 50% increase, that brings us up to 15 words. Times 5 characters per word, that means 75 characters on a line. (...) So the style guide limitation on line length [of 80] is not exactly arbitrary. It is about the developer's ability to effectively scan and comprehend strings of text, not about the technical considerations of terminals and text-editors." (In blog post "Line Length, Volume, and Density" by Paul M. Jones)

One statement per line –rule4 improves top-down reading and attaching comments to the right.

      var  = 10;                // comment one
      str  = "string";          // comment two

      // Multiple statements in one line adds too much information

      var = 10; str = "string";    

The rule can also be applied to conditional statements. An example in ISO C++:

      if ( checkbox  == 0
           and doit  == 1
           and debug == 0 )
      {
          // do something
      }    

[1] Albert Einstein: "Everything should be made as simple as possible—but no simpler" (Wikipedia)

[2] The reason why half-tab indentation is considered industry standard is quite understandable. If it were less, like 2, we easily run into practical issues like: (1) If you adjust screen resolution to higher ones, would you you still feel comfortable with the indentation? (2) If you adjust font size of your editor to a smaller one to increase visible area for your coding, would the indentation still be as clear? (3) If the code were printed on paper, multiple pages on a sheet (4 on a page), would you still read the code fluently?

[3] The use of tabs vs. spaces is an eternal question. See e.g. article "Tabs versus Spaces: An Eternal Holy War" by Jamie Zawinski, 2000. See Coding Horror blog titled "Death to the Space Infidels" by Jeff Atwood which ends in words "only a moron would use tabs to format their code". The tabs are favored in Linux Kernel Coding Style. On the other hand, if code is copy/pasted/indented the spaces ensure uniform layout. In Version Control Systems spaces are also known to be diff-safe, whereas with TABs, an unlucky indentation boundary can cause output to jump many display columns to the right, due to the "+"/"-" column along the left edge of the diff. This makes reading diffs of TAB-indented code a dicey game.

[4] One statement perl line rule is well established in programming circles. See chapter 6.1 Number Per Line in Code Conventions for the Java Programming Language and Chapter 1: Indentation in Linux Kernel coding style.

1.3 Embracing the the KISS – for a good reason

Lines of code matter (p. 1021 ). For every written line, the programmer needs to read and understand anything that surrounds it (compare to YAGNI, cf. XP ). Any extra code is in the way towards understanding. A high level of abstraction and exception handling and error checking can easily bury the "meat" under its surroundings. In addition, accumulating a bigger code base means taking longer to code new features.

The more code there is, the more potential bugs it can contain (p. 1021 ). Just merely glancing over the code to see obvious mistakes is easy with few lines.

Writing code is not the only cost (p. 1031 ). Spending time in coding the application may seem like a costly investment when the schedules are tight and the customer is demanding ready product. Still, the code does not stay put once it has been written. The real costs come later from maintenance, upgradeability and overall modifiability. It must be remembered that people have to be trained to maintain and extend the code when developers leave.

The KISS2 principle effectively is the analogy of thinking the task first and not applying aphorism "If all you have is a hammer, everything looks like a nail3 ". In graphical programs the KISS translates to MVC and tries to strive to keep the UI as thin as reasonably possible since that's the hardest thing to write tests for, and code as much as possible to be UI agnostic. As the very last step, the UI itself is written.

Some use cases on programming languages

Considering to write a Java program to solve a text or file handling problem would be unwise if the same could be done 5-10 times more productive with Perl, Python or Ruby instead (measured in code lines and time). Similarly considering to write a web application with Java from ground up should be preceded by a serious analysis and evaluation of more rapid alternatives like Solar PHP, CakePHP or Ruby on Rails. Making a Java web application on a relational database will require a steep learning curve to cover tons of needed frameworks and APIs: something that is readily accessible only to only years trained Java programmers.

The thing to embrace from KISS is that there is no single programming language that would be suitable for every task and problem size. There is nothing that inherently limit what different programming languages can do, but there are certainly comfort zones for different languages. There is no need to struggle beneath mountains of complexity and collapsing under the weight on abstraction if alternative solutions work better and can be implemented in less time (p. 1171 ). The KISS principles and Agile methodologies aim to manage the fundamental problem of software development: the complexity. Sometimes the simplest answer, picking suitable language, is the best.

[1] Beyond Java by Bruce A. Tate, 2005, O'Reilly

[2] See also "The Principle of least surprise"

[3] Another common variation is: "To someone whose only tool is a hammer, every problem looks like a nail." (See Wikipedia)


2.0 The Major Programming Styles

2.1 Brace Styles

There are two major1 brace styles: the K&R end-brace style and line-up style. Some projects use end-brace style and some projects use line-up style. E.g. The SUN's Java coding convention describes the end-brace style.

An example of strict K&R end-brace style (pseudo code):

      function test () {
          if ( condition ) {
              one();
          } else {
              two();
          }
      }    

An example of line-up style, sometimes called the Allman or modern style:

      function test ()
      {
          if ( condition )
          {
              one();
          }
          else
          {
              two();
          }
      }    

The styles presented above are two of the most known. There exists multitude of variations to deal with e.g. the exact place of else keyword and how to treat simple if-else statements: are braces really always required or not. Hundreds of web pages and millions of discussions have been fought on behalf of the One-True-Brace religion for nothing. Inherently there is no point in arguing which one would be objectively better over another. There is no answer: it would be like deciding if "left lane" car driving (British style) is more natural than "right lane" (non-British style) driving. The habit is learnt when repeated long enough. In this regard the project's responsibility is to decide which to select and how to communicate the decision to all members. The decision is usually enforced using Quality Assurance (QA) and Lint utilities that may, among other things, check style violations.

[1] There exists other brace placement styles and variations (compare to GNU Coding Standards), but most of the projects settle for one of the two above mentioned styles.

2.2 Identifier Naming Styles

Similar to the brace style discussion, there are two major identifier naming styles: the Camel-Case style and underscore_between_tokens style. Some projects use former and some projects use the latter. E.g. the Java uses the Camel-Case (like System.out.println()) whereas PHP uses function names like str_replace().

An example of Camel-Case style in variables

      myEmail     = "address@example.com"
      userInput   = "";    

An example of underscore style:

      my_email     = "address@example.com"
      user_input   = "";    

The CameCase style is in some cases more convenient because editors usually support selecting a word by clicking over it. With underscore style the separate_words may not be copied as a single entity when clicked.

The fine print is that there is also variation of CamelCase called Pascal Style that is seen in Java class identifiers. There also existed a short while Hungarian notation which was popularized by Microsoft in its C/C++ programs. The style was short lived. The Problem with Hungarian identifier notation was that if the data type was changed, say from int to long, changes in variable names would have been required. Linux Kernel coding style (Chapter 4: Naming) describes Hungarian notation: "...brain damaged - the compiler knows the types anyway and can check those, and it only confuses the programmer".


3.0 Documenting Code

Note: Writing in clear is the first an foremost factor in good projects: 1) 80% of the lifetime cost of a piece of software goes to maintenance; (source: Code Conventions for the Java Programming Language). 2) Hardly any software is maintained for its whole life by the original developers; 3) Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly; and 4) Common guidelines make it possible to call for code reviews and auditing meetings

3.1 Documentation Conventions

It is not uncommon that non-native speakers are reading the documentation and code. To overcome language barriers there must be some smallest common denominator to transfer the knowledge. In multi-cultural, – possibly globally wide – projects, the communication language is english and therefore it is natural to write comments, documentation, function names, variable names with it.

If URLs are needed in documentation, there are safe names like example.com, example.org and example.net that can be used for links and email addresses. See Internet standard RFC 2606 (Reserved Top Level DNS Names; Chapter 3) for more information.

3.2 Variable Naming and Self Documenting Code

Variables' case is an important communication mean. The local variables are traditionally written in lowercase letters whereas the global, program wide, variables are capitalized1. See examples below:

      DEBUG   = 0;               //  Global variable; in capital letters
      myEmail = "me@example.com" //  local variable    

Lining up assignments (=) and comments (//) can improve legibility when the size of the identifiers don't vary too much:

       color   = "blue";         //  First comment
       counter = 0;              //  Second comment
       status  = false;          //  Third comment    

The code can be made self documenting with descriptive identifier names. Thoughtfully selected names communicate the flow of code without additional documentation.

[Picture 3.  pic/comics-geekandpoke-the-real-coder.png]
Picture 3. The Real Coder by Oliver Widder, Webcomics Geek Aad Poke, 2011-02-14.

An example from Java:

      if ( buttonPressed  &&  ! isValidResponse(answer) ) {

      }    

Compared to abbreviated alternative:

      if ( btn  &&  ! chkResp(ans) ) {

      }    

[1] There are other type of variables in context of classes. These variables can have various access modifiers like public, private, protected, static. This presents an interesting problem. Some projects differentiate the class level variables from the rest with initial uppercase letter: e.g. Variable. Some make distinction between the private and public variables. In any case, too many naming conventions usually lead to confusion especially when people work with several programming languages and switch between them.

3.3 Commenting Style

Note: some comment styles, like multi line comment, like /* */, can be used for special cases like documentation (see next chapter). The single line comment, like //, is the simplest and safest1.

What and why to comment:

Comments are good, but there is also a danger of over-commenting. NEVER try to explain HOW your code works in a comment: it's much better to write the code so that the working is obvious, and it's a waste of time to explain badly written code. (Chapter 7: Commenting in Linux Kernel coding style).

The best place for comments is just above the code statement so that they naturally follow the code flow and indentation. Using extra spaces and newlines may also improve readability. Notice below how an extra whitespace can be used in front of the actual text: "// ". An example from C++:

      if (condition)
      {
          // This if statement does that and that
          // and possibly tests something more.
          // Notice an empty line separating the code statement.

          flag = 1;
      }
      else
      {
          // This if statement does that and that
          // and possibly tests something more.

          flag = 0;
      }    

Compared to this:

      //This if statement does that and that
      //and possibly tests something more.
      //it's stuck to the code and has no leading indent space "// "
      if (condition)
      {
          flag = 1;
      }
      //Comment placement disrupts reading the LOGIC of code.
      //The condition did not match. Then use
      //default action
      else
      {
          flag = 0;
      }    

[1] The multiline comment syntax is subject to errors. In the classic example, it is impossible to comment out large chunks of code if the inner already uses multiline comments:

      /*

      status = someFunction(with, many, params) /* comment */

      */    

3.4 Documentation Comments

The design becomes visible in classes and functions. They introduce the building blocks of the program which can be explained to the reader. By documenting each function and method keeps the code easily maintained. Any "out of synch" problems are usually inevitable if separate documentation is kept outside of the actual code.

Considering the comments like a story describing the system gives a feel how they should be laid out. Expecting that the comments are to be extracted and analyzed by other programs will remind the writer how important they are. If there is support for programming language1 and special comments, their use will help integrating documentation next to the real "action". This is the currently favored practice.

An example pseudo code using javadoc / phpdoc / C++ Doc / C# Doc, which all can use similar commenting syntax:

      /**
       * <Short, one line description using voice: Sets, Returns ... >
       *
       * <Longer description.>
       *
       * @access public       <E.g. used in PHPDoc>
       * @param  name         Username to set.
       * @return status       non-zero if failed.
       */
      public void setUsername (name)
      {
          username = name;
          return(0);
      }    

An example using perldoc

      =pod

      =head2 setUsername($)

      =over

      =item Description

      Set global variable USERNAME

      =item arg1: $name

      String like "Foo Bar".

      =item Return values

      Non-zero on failure.

      =back

      =cut

      sub setUsername ($name)
      {
          $USERNAME = $name;
          return 0;
      }    

[1] Java was the first language which had the documentation comments built-in. It also helped to popularize the concept of documenting code using special commenting rules and tokens. However the father of the idea can be considered Perl/POD although the POD is not widely used for documenting functions per se; in Perl, POD is more used for manuals and separate documentation. The code documenting idea was soon followed by PHP, where – while the syntax is not yet part of the language – http://www.phpdoc.org/ is widely in use. For C/C++, Objective-C, Python, IDL (Corba and Microsoft flavors), Fortran, VHDL, PHP, C#, and to some extent D there exists utility Doxygen. In contrast, See Microsoft's support for documentation comments in 2008-08-06 blog post "C# documentation comments: useless?".


4.0 Programming Language Statements

4.1 Improving Readability

Legibility and layout of the code can be improved with minor changes in spacing. If language support readable alternative keywords over the more technical && and ||, their use will also improve legibility. Also the conditions around keywords and or can be made more distinct with two or more spaces. Any non-programmer can understand the meaning of written words, but punctuation like && and || need "a priori" learnt understanding.

An example from PHP/Perl. Notice the use of "and", "or" keywords (also in ISO C++1):

      if (($flag  or  $value -2 < 10)   and  ! $this)
      {

      }    

Compared to tightly packed excerpt in C. Notice how many parentheses are needed for the same effect. The added punctuation &&, || increase signal to noise ratio:

      if ((flag||(value-2<10)) && !this)
      {

      }    

Some programming languages can use simple tests, so it is possible to avoid extra tests against NULL, FALSE, TRUE. Here is example for PHP/Perl and applicable to other programming languages as well:

      if ($status)                      // "true" test
      {

      }

      if (! $status)                    // not "true" test
      {

      }    

In the spirit of Agile/XP's less is more principle2, the extra tests do not necessarily add more value. Here is example from PHP. No doubt the reading time of (1) is less that time needed to comprehend the multiple conditions in (2)

      //  Read as: "if there is nothing in status"
      //  Two examples in PHP which lead to the same result

      if (! $status)                    // case (1)
      {

      }

      if ($status == false  or  $status == null  or  $status == "")  // case (2)
      {

      }    

4.2 Utilizing weak typing

Programming langauges which are weakly typed (PHP, Perl, Python, Ruby), allow storing multiple kind of data types (boolean, integers, strings) into same variable at its lifetime. This ability offers some expressive freedom that can be used e.g. in document the code better. Compare these two examples from PHP:

      // Traditional: What does "true" mean here?
      sqlInsert($table, $array, true);

      // Using "true" better; utilizing the epxressiveness of a language
      sqlInsert($table, $array, "remove whitespace");    

Now, the actual function definition can stay the same. The point is not to think literal meaning of "boolean", but to understand how the programming language's power can be used better e.g. in truth tests. Because in these languages, any non-empty value is true, there is no need to always use literal true, but you can use "any string" for the same effect. The two calls above behave identically.

      /**
       * Inserts DATA from array to database TABLE.
       *
       * @param string  $table    Table name.
       * @param array   $data     Values for database TABLE.
       * @param boolean $flag     If true, remove whitespace from values in DATA.
       */
      function sqlInsert($table, $data, $flag)
      ...    

[1] The ISO C++ standard defines readable and, or, not, not_eq keywords that are synonyms for &&, ||, ! and !=. See ISO/IEC 14882:1998 "2.11 Keywords / Table 4 – alternative representations" at page 40, "2.12 Operators and Punctuators [lex.operators]" and C++ operator synonyms at Wikipedia.

[2] "You're not going to get it right the first time ... Change must be easy and cheap ... A quick look at physics makes this obvious. The more massive a moving object the more energy it takes to change its direction. What applies to the physical world also applies to the business world. Less mass makes change easier." (Mike Mindel, 2005-03-24 in Signal vs. Noise weblog, article Getting Real: Less Mass).

4.3 Conditional Statements and Variables

Using assignments (=) inside tests must be considered carefully. The condition statement usually stays more descriptive when there is not too much going on in it. Using simple tests also make code more easy to test and debug when the results are stored separately. In earlier decades extra variables were avoided due to limited PC memory and CPU performance, but today the compilers are smart enough to do the optimizations for the developers. Extra variables may also be very effective way to document the design decisions. Note: there are very good reasons to place assignments inside conditionals. These include looping e.g. inside while where the input is read and tested. For if statements the variable assignments are not always imperative.

An example from Java:

      boolean result = isEmail(string);
      debug("Email check result: " + result);

      if (! result) {
          ...
      }    

Compared to "one liner", while compact, is difficult to automatically test and debug:

      if (! (result = isEmail(string))) {
          ...
      }    

4.4 Quoting styles

Some languages like Perl, PHP, Python and Ruby provide two quoting syntax styles: single or double quotes. The difference between these are that single quotes take literal meaning whereas double quotes are said to interpolate certain elements inside them. An example from PHP/Perl:

      print 'hello $variable';        # No interpolaton of $variable
      print "hello $variable";        # $variable's value is displayed    

There are two major styles and opinions about when and if each pair of quotes should be used.

And Exampe of Quote Ping-Pong:

The latter style has been found to cause quote ping-pong with changing quotes. When the code is changed and variables are inserted inside quotes, you're forced to "rewrite" quoting syntax again and again. The problem is multiplied in a version controlled environments with team of developers. E.g. See Damian Conway's book Perl Best Practices style (c.f. Perl::Critic) whose suggestions would lead to unfortunate Quote-Ping-Pong. Here is a Perl code example:

      my $debug = 'DEBUG: ' . $LIBRARY;    

Ok, according to the above, let's apply that style convention into this code:

      my $debug = "$DEBUG:$LIBRARY ($LEVEL)";    

Broken down, it looks like this. Is this the path to the wisdom?

      my $debug = $DEBUG . ':' . $LIBRARY . ' (' . $LEVEL . ')'; # Ouch    

If the code were written according to the use-always-double-quotes rule, things would be simpler. No quote ping-pong appears with any of these:

      my $debug = "DEBUG: ";
      my $debug = "DEBUG: $LIBRARY";
      my $debug = "$DEBUG:$LIBRARY ($LEVEL)";    

5.0 Object Oriented Programming

5.1 One File, One Class

In good Object Oriented Programming (OOP) style all classes are stored to separate files. The file is usually named with the same name as the class itself.

      class Example       // filename: Example.{cc,php,java,rb}
      {

      }    

5.2 Constructors and Destructors

Java: In Java, there is only constructor (see Providing Constructors for Your Classes) but no destructor. A finalize method would exist, but it cannot be used like a real destructor because there is no guarantee when the finalize will be invoked by the Java JVM. In Java, to make the constructor well behaving, the access modifier private, static or public are best left out (see Controlling Access to Members of a Class).

An example from Java:

      class MyClass
      {
          MyClass()
          {
              // Constructor
          }
      }    

And example from PHP:

      class MyClass
      {
          function __destruct ()
          {
              // Code
          }

          function __construct ()
          {
              // Code
          }
      }    

5.3 Accessor methods

In standard Object Oriented Programming paradigm (OOP), direct access to instance variables is a discouraged practice. A class is best treated like self containing object that is responsible for managing its state. The properties of the class are not made visible to user. The class interacts with outside world by providing accessor methods. These methods are by custom prefixed with get for returning values or prefixed set to change the values.

An example from Java:

      class MyClass
      {
          protected int debug = 0;

          void setDebug(int value)
          {
              debug = value;        // Change debug status in class
          }
      }    

5.4 About OOP and program maintenance

It must be kept in mind that OOP can also lead to problems. Adding an abstraction is like adding a new word to the to language. It requires learning new vocabulary. Real languages rarely invent new words, because the same can be expressed with existing words. Only specific circles – like families, culture minorities – invent expressions which are meaningless outside of the circle.

If abstraction is taken too far, the result maybe code that is structured like a big pyramid (inheritance). If any of the abstraction layers change, it forces repair of all of its uses. The more the abstraction is shared, the more repair will be needed. A highly abstracted code is very difficult to maintain after the original designers and architects have disappeared.

The norm of the software development is that they grow, change, and are repaired. A minimalist approach to inheritance and object features in general ensures that program is maintainable in the long run by others after the original architects are long gone.


6.0 Further Reading

—— Jari Aalto