Correct way to write code

What is the correct way to align code

  • (2 Pages)
  • +
  • 1
  • 2

17 Replies - 5164 Views - Last Post: 12 December 2009 - 03:54 PM

#1 7point8  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 25-October 08

Correct way to write code

Post icon  Posted 10 November 2008 - 03:12 AM

Hi,
Easy question here............
I have written some simple maths problems and simple logic they compile and execute properly. How should I present my work correctly?.So everything is aligned and easy to read etc.......

/**
 * program to calculate amount of bolts,nuts and washers andwarn if wrog amount entered.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class BobsBolts
{
	 public static void main (String args[]){ 
		 
		 int bolt, nut, washer;
		 
		  System.out.print("Enter number of bolts ");
		  bolt=UserInput.readInt();
		  System.out.print("Enter number of nuts ");
		  nut=UserInput.readInt();
		  System.out.print("Enter number of washers ");
		  washer=UserInput.readInt();
		  System.out.println();
		  if (nut>bolt){
		  System.out.println("Check order");
		}
		  else{
		  System.out.println("Order OK"); 
		}
		  bolt = ( int)(bolt*5);
		  nut = (int)(nut*3);
		  washer = (int)(washer*1);
		  System.out.println();
		  System.out.println ("Total price in pence is "+(bolt+nut+washer));
		 
		 
	}//end main
}//end class



Is This A Good Question/Topic? 0
  • +

Replies To: Correct way to write code

#2 g00se  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 2560
  • View blog
  • Posts: 10,692
  • Joined: 20-September 08

Re: Correct way to write code

Posted 10 November 2008 - 04:00 AM

Looks OK. A Java IDE will align your code automatically. If you're not using an IDE, you can use Jalopy to format your source
Was This Post Helpful? 1

#3 stauffski  Icon User is offline

  • D.I.C Head

Reputation: 27
  • View blog
  • Posts: 210
  • Joined: 03-November 07

Re: Correct way to write code

Posted 10 November 2008 - 06:48 AM

The following looks neat, and for the most part is commonly recognized as standard.

/**
 * program to calculate amount of bolts,nuts and washers and warn if wrong amount entered.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class BobsBolts{//indent under every brace
   public static void main (String[] args){//the brackets are most commonly placed before the variable
      int bolt, nut, washer;
      
      //group similar or cooperative lines of code
      System.out.print("Enter number of bolts ");
      bolt = UserInput.readInt();

      System.out.print("Enter number of nuts ");
      nut = UserInput.readInt();

      System.out.print("Enter number of washers ");
      washer = UserInput.readInt();

      System.out.println();

      if(nut > bolt){//space before and after every opperator
         System.out.println("Check order");
      }
      else{
         System.out.println("Order OK"); 
      }//blank line after brace if code follows

      bolt *= 5;//is the same as bolt = bolt * 5;
      nut *= 3;//no need for "(int)"
      //washer = (int)(washer*1); this does nothing

      System.out.println ("\nTotal price in pence is " + (bolt + nut + washer));
   }//no blank lines before brace
}//no blank lines between braces without code between them


Was This Post Helpful? 1

#4 TriggaMike  Icon User is offline

  • Using up all your 1's and 0's
  • member icon

Reputation: 85
  • View blog
  • Posts: 1,101
  • Joined: 26-September 08

Re: Correct way to write code

Posted 10 November 2008 - 10:25 AM

There are many ways to format your code. There is no one standard, but there are a few rules of thumb that most people abide by.

First remain constant. If you start doing something, stick with it.

Second is be comfortable with how you are programming. Everyone programs in their own way, there is no "Right" way, but there are plenty of WRONG ways.

Third, curly brackets, always do them the same way. Personally, I like to do my curly brackets like follows, and it also
shows how I format my variable names.

public class indentingExample 
{	//I like to have my brackets both line up, it is easier for me to keep track of
	public static void main(String[] args)
	{
		//Notice I always initialize my variables, helps prevent problems
		
		//I always start my variable names with lower case, and capitalize every word after that
		int thisIsHowINameVariables = 0;
		//With final variables I use all caps and use underscores between words
		final int FINAL_EXAMPLE = 0;
		
		if(true)
			System.out.print("You can do conditional statements and loops like this");
		if(true)
		{
			System.out.print("But I find it easier to keep track of things if you always" +
					"use block statements like this.");
			
		}
	}
}


Everyone has their own way of formatting that makes sense to them, and yeah, it can be annoying to look at other people's code, but using IDE's such as Eclipse can help, and can format codes into something that you find is easier to read.
Was This Post Helpful? 1

#5 gabehabe  Icon User is offline

  • GabehabeSwamp
  • member icon




Reputation: 1376
  • View blog
  • Posts: 10,951
  • Joined: 06-February 08

Re: Correct way to write code

Posted 10 November 2008 - 11:31 AM

Most will do it for you.

There is no right and wrong. But, I prefer to keep it to a 4-gap indentation. As for calling a function across multiple lines, I keep it lined up to the bracket.

Example from my most recent project: (C++)
BEGIN_EVENT_TABLE(TextSearch, wxFrame)
	EVT_BUTTON(NEXT, TextSearch::MoveToNext)
	EVT_BUTTON(PREVIOUS, TextSearch::MoveToPrevious)
	EVT_BUTTON(COPY, TextSearch::CopyToClipboard)
END_EVENT_TABLE()

TextSearch::TextSearch(vector <wxString> results) : wxFrame(NULL, wxID_ANY, wxT("Search Results"), wxDefaultPosition, wxSize(415, 280),
															wxMINIMIZE_BOX | wxCLOSE_BOX | wxSYSTEM_MENU | wxCLIP_CHILDREN | wxCAPTION) {
	this->mainPanel = new wxPanel(this, wxID_ANY);
	this->current = 1;
	this->library = results;
	ostringstream ostr;

	ostr << "Currently viewing #" << current << " of " << this->library.size() << " results";
	this->currentLabel = new wxStaticText(this->mainPanel, wxID_ANY, wxString::FromAscii(ostr.str().c_str()), wxPoint(110, 10));
	this->currentLabel->SetFont(wxFont(10, wxFONTFAMILY_SWISS, 0, wxFONTWEIGHT_LIGHT, false));

	this->previous = new wxButton(this->mainPanel, PREVIOUS, wxT("<< Previous"), wxPoint(110, 40));
	this->next = new wxButton(this->mainPanel, NEXT, wxT("Next >>"), wxPoint(220, 40));

	this->text = new wxTextCtrl(this->mainPanel, wxID_ANY, wxT(""), wxPoint(30, 75), wxSize(345, 125), wxTE_MULTILINE | wxTE_PROCESS_ENTER);

	this->copy = new wxButton(this->mainPanel, COPY, wxT("Copy to Clipboard"), wxPoint(149, 215));

	this->text->SetValue(this->library[0]);
}

Because this isn't language specific, I'm moving it to the corner cube. :)
Was This Post Helpful? 1

#6 Locke  Icon User is offline

  • Sarcasm Extraordinaire!
  • member icon

Reputation: 520
  • View blog
  • Posts: 5,596
  • Joined: 20-March 08

Re: Correct way to write code

Posted 10 November 2008 - 03:23 PM

View PostTriggaMike, on 10 Nov, 2008 - 09:25 AM, said:

There are many ways to format your code. There is no one standard, but there are a few rules of thumb that most people abide by.

First remain constant. If you start doing something, stick with it.

Second is be comfortable with how you are programming. Everyone programs in their own way, there is no "Right" way, but there are plenty of WRONG ways.

Third, curly brackets, always do them the same way. Personally, I like to do my curly brackets like follows, and it also
shows how I format my variable names.

public class indentingExample 
{	//I like to have my brackets both line up, it is easier for me to keep track of
	public static void main(String[] args)
	{
		//Notice I always initialize my variables, helps prevent problems
		
		//I always start my variable names with lower case, and capitalize every word after that
		int thisIsHowINameVariables = 0;
		//With final variables I use all caps and use underscores between words
		final int FINAL_EXAMPLE = 0;
		
		if(true)
			System.out.print("You can do conditional statements and loops like this");
		if(true)
		{
			System.out.print("But I find it easier to keep track of things if you always" +
					"use block statements like this.");
			
		}
	}
}


Everyone has their own way of formatting that makes sense to them, and yeah, it can be annoying to look at other people's code, but using IDE's such as Eclipse can help, and can format codes into something that you find is easier to read.


YES!!

I enjoy being around people that do it this way. It just looks more structured to me. :)
Was This Post Helpful? 1

#7 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5643
  • View blog
  • Posts: 12,359
  • Joined: 16-October 07

Re: Correct way to write code

Posted 10 November 2008 - 08:23 PM

View Post7point8, on 10 Nov, 2008 - 04:12 AM, said:

How should I present my work correctly?


You're asking for a programming jihad with this one. :P

Everyone does it a little different, there is no right way. You must be consistent. You must make it so you can visually scan your code and see how the logical chunks fall.

I often reorganize other people's code before I offer an answer, just so I can read it easier.

I like braces on the same line. In Java and C++ I like latest variable declaration possible, it makes scope implicit. In general, I avoid comments. ;)

/**
 * program to calculate amount of bolts,nuts and washers andwarn if wrog amount entered.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class BobsBolts {
	public static void main (String args[]) {
		System.out.print("Enter number of bolts ");
		int bolt = UserInput.readInt();
		
		System.out.print("Enter number of nuts ");
		int nut = UserInput.readInt();
		
		System.out.print("Enter number of washers ");
		int washer = UserInput.readInt();
		
		System.out.println();
		if (nut>bolt) {
			System.out.println("Check order");
		} else {
			System.out.println("Order OK"); 
		}
		
		bolt = bolt * 5; // not casting needed, implict
		nut *= 3; // shorter syntax, often good.
		// washer = (int)(washer*1); // that the hell are you doing?
		System.out.println();
		System.out.println ("Total price in pence is "+(bolt+nut+washer));
	} // if you have to tell what this is the end of, you have a bracket failure
}


Was This Post Helpful? 1

#8 born2c0de  Icon User is offline

  • printf("I'm a %XR",195936478);
  • member icon

Reputation: 180
  • View blog
  • Posts: 4,667
  • Joined: 26-November 04

Re: Correct way to write code

Posted 10 November 2008 - 11:40 PM

I prefer the Allman style of indentation with comments for the not-so-obvious blocks of code.
Was This Post Helpful? 0
  • +
  • -

#9 majs  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 42
  • Joined: 29-October 08

Re: Correct way to write code

Posted 13 November 2008 - 09:13 AM

I do my braces on the same line too. Apart from this, I follow the same way as TriggaMike, it's how I feel most comfortable and as already said on this thread, that's what matters most in my opinion. Getting use to the good practices will get you more comfortable programming in that manner however.
Was This Post Helpful? 0
  • +
  • -

#10 PostulateMan  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 2
  • View blog
  • Posts: 50
  • Joined: 14-September 08

Re: Correct way to write code

Posted 18 November 2008 - 10:05 AM

I agree with TriggaMike but for baavgai's reasons! I find it much easier to see the beginning of a block if it's started on it's own line. I also prefer copious amounts of comments and descriptive variables. If someone asks me for help with code they didn't comment, now I have to decipher not only what is going on, but what they thought their logic was doing.
Was This Post Helpful? 0
  • +
  • -

#11 pc_w12ard  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 9
  • View blog
  • Posts: 109
  • Joined: 21-November 08

Re: Correct way to write code

Posted 29 November 2008 - 12:33 AM

my Java IDE does my alignment and indentation for me. I use eclipse, so its just "select all" and "ctrl+ i" and bam its done.
Was This Post Helpful? 0
  • +
  • -

#12 mrmcpott  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 4
  • View blog
  • Posts: 95
  • Joined: 24-November 08

Re: Correct way to write code

Posted 29 November 2008 - 02:04 AM

Is there any language that is specific on the formatting?

:blink: :ph34r:
Was This Post Helpful? 0
  • +
  • -

#13 Tom9729  Icon User is offline

  • Segmentation fault
  • member icon

Reputation: 180
  • View blog
  • Posts: 2,641
  • Joined: 30-December 07

Re: Correct way to write code

Posted 29 November 2008 - 04:18 AM

View Postmrmcpott, on 29 Nov, 2008 - 04:04 AM, said:

Is there any language that is specific on the formatting?

:blink: :ph34r:

Lisp.

I would think Python as well.
Was This Post Helpful? 0
  • +
  • -

#14 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3089
  • View blog
  • Posts: 19,137
  • Joined: 14-September 07

Re: Correct way to write code

Posted 29 November 2008 - 07:37 AM

Yup, whitespace is significant in python. [indentation]
Was This Post Helpful? 0
  • +
  • -

#15 V.C. Sniper  Icon User is offline

  • D.I.C Head

Reputation: -1
  • View blog
  • Posts: 93
  • Joined: 17-August 09

Re: Correct way to write code

Posted 11 December 2009 - 03:57 PM

Allman style 43\/4R!!!

Old code from first C++ class:
void open_verify_input_files(ifstream& fi, string file_name)//opens input file 
{
	int useDefault;
	cout << "Do you want to use the default file?(Enter 0 for yes): ";
	cin >> useDefault;
	cout << endl;

	if (useDefault == 0)
		fi.open("f:\\Student_Scores.txt");
	else
	{
		fi.clear();
		cout << "Please enter Input file name: ";
		cin >> file_name;
		fi.open(file_name.c_str());
	
		while (!fi)//if input file not found, ask for another file
		{
			fi.clear();
			cout << "Input file not found." << endl << endl;
			cout << "Please enter another Input file name: ";
			cin >> file_name;
			fi.open(file_name.c_str());
		}
	}
}



The closing braces line up nicely with the opening braces! Looks so neat and nicely structured!!!

This post has been edited by V.C. Sniper: 11 December 2009 - 04:00 PM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2