Click here to Skip to main content
15,886,074 members
Articles / Mobile Apps
Tip/Trick

How to Write Good Code

Rate me:
Please Sign up or sign in to vote.
4.87/5 (37 votes)
22 Nov 2015CPOL1 min read 44.2K   27   21
Each function should answer "how-what-why."

My first tip!

This is not a long tome on software architecture.  This is simply about how do to write good code. Code consists of functions, and this is what a function should look like (using C# style as an example):

// A comment describing why the function exists
void WhatTheFunctionDoes()
{
  ... how the function does what it says it does.
}

That's it! If you follow the "why-what-how" approach, the quality of your code will start to improve! Here's a real life example:

/// <summary>
/// The user can get an instance of a service implementing 
/// the specified interface, but only if the service is 
/// registered as supporting instance creation.
/// </summary>
public virtual T GetInstance<T>()
  where T : IService
{
  VerifyRegistered<T>();
  VerifyInstanceOption<T>();
  IService instance = CreateInstance<T>();
  instance.Initialize(this);

  return (T)instance;
}
  1. The "why" is clear -- we're supporting a need the programmer will have for creating service instances.
  2. The "what" is clear -- the function returns an instance of the specified generic type T.
  3. The "how" is clear -- there are four function calls that describe how this function works.

Here's a simple guideline for figuring out when to break a function apart into smaller functions:  

If your function has "how" fragments that would benefit from "how", "what" or "why" comments, then this is great indicator that you should move those fragment into separate functions where the the function name describes "what" and embodies "how."  In other words, when you could write a comment in the body of the code that answers one of those questions, you need to move that code into a function that answers the "what".

Recurse that process until the function's name answers "what" and the body of the function clearly describes "how", then for each function you created, write an intelligent "why" comment.

Now go forth and code better!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect Interacx
United States United States
Blog: https://marcclifton.wordpress.com/
Home Page: http://www.marcclifton.com
Research: http://www.higherorderprogramming.com/
GitHub: https://github.com/cliftonm

All my life I have been passionate about architecture / software design, as this is the cornerstone to a maintainable and extensible application. As such, I have enjoyed exploring some crazy ideas and discovering that they are not so crazy after all. I also love writing about my ideas and seeing the community response. As a consultant, I've enjoyed working in a wide range of industries such as aerospace, boatyard management, remote sensing, emergency services / data management, and casino operations. I've done a variety of pro-bono work non-profit organizations related to nature conservancy, drug recovery and women's health.

Comments and Discussions

 
Questionself-explainatority over commentation Pin
Mr.PoorEnglish14-Jan-16 1:16
Mr.PoorEnglish14-Jan-16 1:16 
as Joseph Webster mentioned in his comment[^], "one school" tries to ban commentation completely, and write full self-explainatory code instead.
And I agree with you both, that such can't always be achieved - in the real world Code cannot always be that self-explainatory.
Not always, but often it can!
And in such cases I am of "one school" - means: When code explains itself, then commentation disimproves it.
Applied to your sample, I would not explain in the comment, that GetInstance() gets an Instance.
Because a Programmer, who can't read that from the code itself, should not be allowed to read it at all Wink | ;)
Instead of that I would express another Must-Know about the Function more clearly, namely whether it can fail, and what will happen then.
So my comment of your Function would come out as:
C#
/// <summary> Exception on unregistered service or if it doesn't support instance creation. </summary>
public virtual T GetInstance<T>()
  where T : IService
{ //...
(While I assume, the Function is located in a class (self-explainatory) named as "ServiceManager" or something similar.)

What I want to say: Your 3 Questions are wonderful and of category "mustbe satisfied".
But additionally I recommend to focus Commentation very strong only on the non-self-explainatory parts of code.

modified 14-Jan-16 7:26am.

GeneralI like the "why" part Pin
flyingxu10-Dec-15 14:01
flyingxu10-Dec-15 14:01 
QuestionUse of comments Pin
Joseph Webster, CISSP2-Dec-15 11:49
Joseph Webster, CISSP2-Dec-15 11:49 
AnswerRe: Use of comments Pin
Marc Clifton3-Dec-15 3:09
mvaMarc Clifton3-Dec-15 3:09 
QuestionOne more improvement Pin
wraithnath26-Nov-15 3:29
wraithnath26-Nov-15 3:29 
PraiseNice job Pin
Member 466290325-Nov-15 20:50
professionalMember 466290325-Nov-15 20:50 
QuestionWriting good functions Pin
Member-243269624-Nov-15 3:11
Member-243269624-Nov-15 3:11 
Question"wherefore", "what", "how", "why so and not otherwise" are four questions to any function (class/method/module) before its creation. Pin
DimaZavr23-Nov-15 5:45
DimaZavr23-Nov-15 5:45 
AnswerRe: "wherefore", "what", "how", "why so and not otherwise" are four questions to any function (class/method/module) before its creation. Pin
flyingxu10-Dec-15 14:04
flyingxu10-Dec-15 14:04 
Questioncomment Pin
KhabirSoft23-Nov-15 5:28
KhabirSoft23-Nov-15 5:28 
GeneralMy vote of 5 Pin
Santhakumar M23-Nov-15 3:08
professionalSanthakumar M23-Nov-15 3:08 
PraiseNice Pin
Simon_Whale23-Nov-15 0:18
Simon_Whale23-Nov-15 0:18 
PraiseMy vote of 5 Pin
Liju Sankar22-Nov-15 18:01
professionalLiju Sankar22-Nov-15 18:01 
GeneralMy vote of 5 Pin
JayantaChatterjee22-Nov-15 17:02
professionalJayantaChatterjee22-Nov-15 17:02 
QuestionCoding better Pin
Vivi Chellappa22-Nov-15 16:00
professionalVivi Chellappa22-Nov-15 16:00 
SuggestionNitpicky, but... Pin
wvdhouten22-Nov-15 13:00
wvdhouten22-Nov-15 13:00 
GeneralRe: Nitpicky, but... Pin
Marc Clifton23-Nov-15 3:47
mvaMarc Clifton23-Nov-15 3:47 
GeneralRe: Nitpicky, but... Pin
wvdhouten23-Nov-15 4:03
wvdhouten23-Nov-15 4:03 
GeneralRe: Nitpicky, but... Pin
wvdhouten23-Nov-15 4:07
wvdhouten23-Nov-15 4:07 
GeneralRe: Nitpicky, but... Pin
Yusuf23-Nov-15 5:36
Yusuf23-Nov-15 5:36 
PraiseMy vote of 5 Pin
Afzaal Ahmad Zeeshan22-Nov-15 9:01
professionalAfzaal Ahmad Zeeshan22-Nov-15 9:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.