PDA

View Full Version : Article: Why Code Readability Matters



WILL
05-06-2011, 08:07 PM
Have a read of this one guys. Since I work in another field (Avionics) that requires me to do more paperwork than actual hands-on work I can relate to this person's perspective on the matter. But I wonder if his approach is absolutely necessary the way he goes about it. What do you guys think?

http://blog.ashodnakashian.com/2011/03/code-readability/

dazappa
05-06-2011, 08:24 PM
I think the biggest thing I've learned in terms of readability is variable names. Having 1-3 character variable names that are used in multiple procedures or functions can get very confusing on first glance. I'm not quite sure about the multiple variable declarations in one line... it's readable enough if the variables have proper names IMO.

chronozphere
05-06-2011, 09:34 PM
Variable names (and ofcourse class/procedure/function names) are IMHO the most important thing to do right, because this is the only text you usually read apart from the comments. Using a load of comments to compensate for bad naming is just bad.

Some things I also find important are the more subtle aspects of a coding style. For example, I find it annoying when someone writes his code using capitals everywhere (Especially for the reserved words: IF, BEGIN, ELSE). Because capitals are very attention-hungry, I tend to use them as least as possible. I think JAVA has pretty good conventions regarding case. They use lower camel case (http://en.wikipedia.org/wiki/CamelCase) for variable/method names and upper camel case (http://en.wikipedia.org/wiki/CamelCase) for classnames. Finally they use capitals for constants (were compound words are separated by underscores). I find this convention very nice, especially because allmost everyone uses it. I wish there was such a clear consensus within the pascal-world (Allthough I DO love the T, P and F prefixes, there is still quite a bit of freedom in using different case ;) )

dazappa
05-06-2011, 09:58 PM
Egh, the only time I ever completely capitalize something is for a constant.

WILL
06-06-2011, 12:10 PM
I find most will just copy-cat from the conventions used in examples. Makes sense. Just going with what another programmer of that language/script is doing since it seems to work.

For example, I was originally taught to use i, j and k consecutively in my for loops. What sense does this make in practice? I have no idea, I just use them instead of say... a, b and c for example. Though this doesn't become a readability issue unless I'm trying to use the darn thing globally or something weird like that.

gasdeveloper
07-06-2011, 09:46 PM
I understand the i for iteration or for index, I always that the j was just because it looked similar to i ;)

I stand on the more structured your code is the better off you are in the future. I look back at some of my code from 5 years ago and think to myself "Dang i sucked back then." mainly because I can hardly read the code. It is all cryptic and never used any standards for scope named variables or any prefix for the variable type.
var
strName : String;
intCurIndex : Integer;
chrDelimiter : Char;

and etc. this is the convention I use for prefix, and if it is a class variable it is prefixed with an underscore _chrDelimiter or _blnRunning

it just helps me to know what to expect the value should be. after all, it is all preference if you are working on your project "el solo" The compiler doesn't care as long as you haven't made a grave mistake and called the wrong function or have declared something in local scope that overrides global scope and have forgotten to reference the global scope with Self.VarName

Well that is just my 2 cents.

Oh and indentation. that is a big one for me. I must always indent consistently.

Ñuño Martínez
08-06-2011, 09:16 AM
Nice article. It has a lot of good advices. :)

I'm sorry but I use capitals for keywords and data types (not defined by user, just the ones defined by the language). I found it's easer to read for me even if I'm using syntax highlighting. You can locate almost any language structure at a glance. For everything else (variables, classes, procedures, etc) I use CamelCase. Often I use upper-case for constants too.

About spaces, I put one before "(" always, and also after ",". See:



ThisProcedureHasSomeParameters(Parameter1, Parameter2, LastOne);

ThisProcedureHasSomeParameters (Parameter1, Parameter2, LastOne);



Also, I separate procedure implementations by three empty lines. This way is easer to find where it starts and ends. I use indentation, of course (2 spaces each level, 1 TAB for 8 spaces).

And I never, never, NEVER use hungarian notation (http://en.wikipedia.org/wiki/Hungarian_notation). That's true annoying. What if you change the type of a largely used variable? BTW, the proposal of the variable itself should be enough to know the type it is (i.e. a variable named "FileName" will never be of type "INTEGER", will it?)

And use long names (very long sometimes) for everything except few short ones as "Ndx", "Cnt" and few more (never one leter though), and a lot of comments.


(...) and if it is a class variable it is prefixed with an underscore _chrDelimiter or _blnRunning

it just helps me to know what to expect the value should be. after all, it is all preference if you are working on your project "el solo" The compiler doesn't care as long as you haven't made a grave mistake and called the wrong function or have declared something in local scope that overrides global scope and have forgotten to reference the global scope with Self.VarName In this case I use the "Borland convention" and use "f" (i.e. SELF.fVarName), but only in variables not in properties. I read it in a paper published by Borland itself.

WILL
08-06-2011, 11:08 PM
I stand on the more structured your code is the better off you are in the future. I look back at some of my code from 5 years ago and think to myself "Dang i sucked back then."
I think everyone goes through this. Each program or game project is a learning experience I feel.

gasdeveloper
16-06-2011, 09:38 PM
And I never, never, NEVER use hungarian notation (http://en.wikipedia.org/wiki/Hungarian_notation). That's true annoying. What if you change the type of a largely used variable? BTW, the proposal of the variable itself should be enough to know the type it is (i.e. a variable named "FileName" will never be of type "INTEGER", will it?)


In code I have written no, FileName will never be Integer however it might be something like TBESEString or widestring, or any other format that it could fit. Also, I have used many libraries where a variable or type is actually an int or cardinal or a word but named as though it contained data and not an index for the data.

And for changing the type of a largely used variable. Well My standard is I don't use variables outside of one unit if possible. So, normally I only have to change its name in a single file. And I love GREP and Search and Replace.

Its not any standard notation I follow. I just use the structure that I find easiest to read. As I said, I don't like the way I coded 5 years ago. It's possible I would like the way I code now, in 5 years. It all comes down to preferences, there is no de facto standard. And even if there is, who cares. Follow the "Shop Standards" and if you are so lucky maybe you are making the "Shop Standards" wherever you are working.

I really think it is a waste of time when you get with other programmers and no one codes alike. I would rather hate the formatting of the code and have to write code like that, then to have 5 different formatting standards on one project.

phibermon
21-06-2011, 08:55 PM
I tend to vary my notation depending on context for example, for a large number of type declerations that get used often, I'll shorten the terms but also include information pertaining to that type ie :

SInt8 - Signed 8bit Integer
UInt8 - Unsigned 8bit Integer etc
SInt16
UInt16
SInt32
UInt32
Float32
Float64

So this is similar to a lot of C stuff, OpenGL etc. I don't use classic hungarian notation simply because it's an old technique that isn't needed with modern code editors.

For class definitions and methods I tend to use the most descriptive terms (in CamelCase) and group together classes by name whenever it seems appropriate :

TJSpatialRegion
TJSpatialEntity
TJSpatialEntityController
TJSpatialEntityControllerAnnotation

I always use the prefix 'A' on variables in method declerations so there can be no confusion between private variables (F). class Properties exposed to end-users use no prefix.

FVelocityVector : TJVec3;
FSpatialController : TJSpatialController;

procedure TJSpatialEntity.SetVelocityVector(AVelocityVector : TJVec3);
procedure TJSpatialEntity.SetSpatialController(AspatialContr oller : TJSpatialController);
procedure TJSpatialRegion.AddSpatialEntity(ASpatialEntity : TJSpatialEntity);

property VelocityVector : TVec3 read GetVelocityVector write SetVelocityVector;

I think that naming conventions are important for either :

A) Adoption Speed - If you intend your code to be accessed by a large number of people, you'll want it to be as descriptive as possible.

B) Coding Speed - If it's just you or a small team and the source is closed then use whatever shorthand is appropriate in order to save on time writing/reading the code.

Very large code-bases require all coders to use the same system for notation if only to avoid adding additional complexity into already complex systems.


P.S I would not recommend using layout rules with the intention of making the language syntax easier to read! that's why we have syntax highlighters etc. If you're doing a whole bunch of keystrokes to bring code-completion in line with your own layout, you're just wasting time. Use the layout defined in your editors snippets. Questions of notation should be about understanding what your code does not how the language works.

Ñuño Martínez
22-06-2011, 08:27 AM
(...) I like your style. :)

Darkhog
01-06-2013, 11:21 AM
Note that this is written before reading actual article. Here are my thoughts on the subject.

I always try to keep my code readable, simply because I often "jump between projects" - I have three Pascal projects right now (game engine, Super Heli Land and DCPU-16-like virtual processor) and two RPG Maker ones (plus one on hiatus until I'll get more skilled with RM because of magnitude of it) and when I get bored with one project I am going to other. So often I have few month breaks from one project.

Because of it, I've learned to write easy to read code. For my identifiers (variables, procedures and functions) I'm using CamelCase (with first letter upper case), for constants it is all uppercase. Sometimes for procedures/functions I'm using underscore_notation, but only when code readability suffers from usage of CamelCase or when I'm writing some library and want to visually separate its name (example: DarkhogGui_DrawButton).

I also do lots of commenting. Even most insignificant and obvious line should be IMO commented, because after few months you won't know what it does.

SilverWarior
01-06-2013, 11:33 AM
I also do lots of commenting. Even most insignificant and obvious line should be IMO commented, because after few months you won't know what it does.

Commenting is verry important but I keep forgetting to coment my code myself >:(

pitfiend
02-06-2013, 07:10 AM
Commenting is verry important but I keep forgetting to coment my code myself >:(
Don't feel like an alien, it happens to many programmers, myself included. But well writen code is a good documentation in itself if you name your functions/procedures and types/const/variables/classes/properties with meaning names.

Darkhog
02-06-2013, 03:33 PM
Don't feel like an alien, it happens to many programmers, myself included.
It happens to me too. I usually put comments after I'm certain code is doing what is supposed to do.


But well writen code is a good documentation in itself if you name your functions/procedures and types/const/variables/classes/properties with meaning names.

Yeah, about that... I'm not big fan of "self documenting code". I had many times read code that was supposed to be "self documenting one" but wasn't easy to grasp (though easier than if variables were called "Variable1","Variable2", etc. and functions "Function1","Function2",...). And it was both Pascal and other language code (which includes so easy, at least for me, languages like C# or Java).

In my opinion nothing will help more than properly documented code. Even comments like "this function is supposed to do..." before function body are good.

Carver413
02-06-2013, 06:55 PM
I hate comments in the code,it just makes it harder to visualize the actual code. I really hate people who indent 8 char at a time, 2 is enough.

SilverWarior
02-06-2013, 07:26 PM
I hate comments in the code,it just makes it harder to visualize the actual code. I really hate people who indent 8 char at a time, 2 is enough.

I don't hate coments in the code unles they span through several lines. Those can realy make hadred to visualize the code.
The best thing to help bisualize the code are region definitions and code folding that is of course if they are used properly. It is to bad they are somwheat broken in Delphi. If you make any syntactical error all the code that is below that point gets unfolded automaticaly. This unfortunately makes code foldin almost uselsess in Delphi.
I myself use 4 char indents mosty 2 in type declarations only. The main reason for this is old practice from Delphi 6. Since Delphi 6 didn't support automaticly adding "end;" after every "begin" I dah to rite all those ends by myself. And since end is 4 characters long I kept 4 char indets as it alowed me to simply pres UP arrow key to get in place for writing the code inside the method I just started to write.

Carver413
02-06-2013, 11:23 PM
I hate code folders as well. to me they are simply a bandaid to an editor design that should have went away long ago. with the Explorer I have an editor design that allows me to qucikly move to where I want to work and see only what I am working on.

SilverWarior
03-06-2013, 05:15 AM
I don't think I quite folow what you wanna say.

Rodrigo Robles
04-06-2013, 12:37 AM
These days follow code conventions is just a obligation. People just not accept non-standard code anymore.
I believe the next step to code quality is to focus in a reusable design and eliminate redundancies. Today I see in many production projects redundant code in many levels - some people make ctrl+c and ctrl+v in many lines of code or even a entire unit to make a new form looks like the other.
Another problem is bad design - giant functions that do many things and are completely specialized and not-reusable.
Unnecessary coupling is very common in Delphi - specializing units that could be more generic and reusable.

Ñuño Martínez
11-01-2019, 10:15 AM
I don't know what "region definitions" are. Do you mean to use your home language (Spanish, French, German...) or what?

SilverWarior
11-01-2019, 03:35 PM
I don't know what "region definitions" are. Do you mean to use your home language (Spanish, French, German...) or what?

No Ñuño we are talking about this:
http://docwiki.embarcadero.com/RADStudio/Tokyo/en/Regions
http://wiki.freepascal.org/IDE_Window:_Editor_Options_Code_Folding#About_.7B. 25Region.7D

Ñuño Martínez
11-01-2019, 07:02 PM
Oooh! I see. Thanks for the tips, SilverWarrior.

I think I never used code folding. I know it exists but I never feel like I needed it. I'm not saying it isn't useful.

SilverWarior
15-01-2019, 04:50 PM
I think I never used code folding. I know it exists but I never feel like I needed it. I'm not saying it isn't useful.

Well if you use code folding features that Delphi offers you by default it basically boils down to just folding of type definitions, method implementations, and entire unit sections (uses section, interface section, implementation section, var and constant sections, etc.) you probably won't see many benefits. In fact in certain cases it might even hurt. For instance if you fold a method in implementation section it beings to look just like forward method declaration and could thus cause confusion since the only clue that code was folded is that minus sign at the beginning of the line. Some other coding tools at leas also add a vertical line to the line where code was folded to give more clear information that the code was folded.
But if you start using regions and thus add yourself more code folding points you will learn that it could actually be useful in certain scenarios. Especially if you have a tendency of writing long method or what I call "a mile long nested if clauses". In such cases code folding can come very useful.
In fact when I used code folding for the first time (with the help of regions) was to get heads and tails of some badly written code that I found on internet.