Forum


You must be a registered user to participate in this chat.

Clean Coding Standa…
 
Notifications
Clear all

Clean Coding Standards help!

21 Posts
5 Users
0 Reactions
2,057 Views
(@black-racoon)
Member Admin
Joined: 16 years ago
Posts: 2007
Topic starter  

Ok… so I have recently encountered the tragedy of messy previous code.. of which now I have ensured that it is all commented and tabbed where appropriate but how else do you make code ‘clean’.

Is there a certain way to name variables that is a global standard or anything. I just stick with one type and name all the vars like that, I’m not too sure how else you could make it clean or cleaner? Also another questions about functions.. if you only plan to say use a function twice is it best just to code it twice or copy/paste rather then make it a function? Is their a rule of thumb I should be following.

I just came to these questions since, looking back at previous code.. there is no way I was wanting to ever have to update it, it was so terribly messy, but that was some years ago, but still I would like my code to be as clean as possible, for myself and others if they picked up from where I left.

Kind Regards, BR


   
Quote
(@noobitup)
Noble Member
Joined: 15 years ago
Posts: 1380
 

Firstly BR, what language are you asking about?

Different languages have quite varied standards / things that make sense.

I deal with code quality / style at lot at work so I may be of some use here.

Test.


   
ReplyQuote
(@trigger-happy)
Noble Member
Joined: 16 years ago
Posts: 1460
 

Well the basic rules of coding are to have meaningful variables without having them span ages. So for example, no variables should be x, y, z etc. Also, names like temp can be confusing, does it mean a temporary variable or does it mean the temperature of something? You need to be descriptive and if you can’t it is good to have a comment saying what the variable is for.
Depending on what language you use, there are coding standards for them and how they like things spread out. So the number of tab spaces and whether or not to use slumpginCamelCase for variables and CamelCase for functions etc.
Refactoring is what you want to look up when dealing with replicated code. There is heaps of material on it and if you are doing any kind of programming at uni you should encounter it. Basically there are all sorts of ways to refactor code to make it cleaner and easier to read. If you are using the same code twice, yes put it in a function if possible as long as it is going to make it easier to understand. Comments should be the documentation of your code (and if you use Java, your comments actually do become your documentation through javadoc). So with comments, you should say what a function does and depending on the language you will either do pre and post conditions or you will say what params it takes and what it throws etc.
Commenting is a hard thing to do, people don’t want to read a story but personally I prefer more verbose comments than simple one liners for a function. For actual statements of code though that are complex, a line of comments is fine to describe what you are doing if it isn’t obvious. Loops are good to comment as you want to know what it is looping over and why because it isn’t initially obvious if they have badly named variables.
Here is an example of a function from a java assignment I had to do, it has comments for the function and then lines here and there saying what it does:

/**
	 * Initializes a new game clearing any previous game state.
	 * 
	 * The new game initialisation involves creating maxApplicant
	 * number of applicants each with a unique id and quality score obtained from the
	 * provided java.util.Random object.
	 * 
	 * @param maxApplicants a positive integer number of applicants to consider
	 * @param random a non-null java.util.Random number generator
	 * @throws HiringException thrown when invalid arguments are supplied
	 * 
	 */
	public void newGame(int maxApplicants, Random random) throws HiringException{
		//Check if applicants is above zero and that the random
		//seed is not null
		if (maxApplicants <= 0){
			throw new HiringException("Invalid number of applicants");
		} else{
			if (random == null){
				throw new HiringException("Invalid random seed");
			} else {
				//Initalise the game state
				gameStarted = true;
				applicants.clear();
				appCount = 0;
				applicantAccepted = false;
				randomOrder = random;
				appOrder = createOrder(maxApplicants);

				//Create an array of applicants the size of 
				//maxApplicants
				for (int index=0; index<maxApplicants; index++){
					Applicant newApplicant = new Applicant(index,random.nextDouble());
					applicants.add(newApplicant);
				}
				//Remove any null states at the end of the array
				applicants.trimToSize();
			}
		}
	}

Once you get coding a lot more (say at uni) you will see examples of good and bad coding/commenting and how they want it done. Otherwise as I said you can check out lots of guides on commenting and refactoring etc.
Hope that helps ๐Ÿ™‚

Cheers


   
ReplyQuote
(@black-racoon)
Member Admin
Joined: 16 years ago
Posts: 2007
Topic starter  

Firstly BR, what language are you asking about?

Different languages have quite varied standards / things that make sense.

I deal with code quality / style at lot at work so I may be of some use here.

Well I am currently, coding in php mysql javascript, web based development.

Also, I know this may be off topic but is there a reason why people refer to asp.net instead of php being a real development platform? PHP has many standards and is very very widely used, almost too much..

@Trigz. Thankyou, I have been one to use temp before, although I now try to avoid positions where storing a variable just as a temp location while another action happens instead of just using a function which allows for the direct implementation to occur. Once I finish this last piece of work I plan to move heavily over to C++/Java area of things to really get a broader experience, especially knowing that Uni will be covering them. The example was helpful, that is mostly how the comments are laid out throughout my projects currently.

I was told a while back not too comment to explain how your doing something but WHY your doing it, because good written code can explain what is happening on its own. Is this true or not for all instances?

Cheers, BR


   
ReplyQuote
(@noobitup)
Noble Member
Joined: 15 years ago
Posts: 1380
 

Okay BR, sounds like you are covering quite a bit of ground.

Probably one of the most important quotes I have heard in my professional programming career is that “Code is meant to be written once and read many times”. Readability is hugely important.

The advice I usually try to give is not to rely on your comments as much as giving the code meaningful (method / function / variable) names. Different languages enable you to different degrees to make code nice and readable. Some languages (SQL or basic scripting) don’t lend themselves to modularity and so sometimes you must sacrifice readability in order to get things done. More powerful languages (my experience is heavily java) allow you to be more verbose in your code.

In java I would encourage my devs to utilise method names as their comments e.g.

public void copyFileToRemoteServer() {
checkIfFileExists();
readFileIntoBuffer();
connectToRemoteServer();
performCopy();
checkFileCopiedSuccessfully();
closeRemoteConnection();
}

Now ignoring that there are a few holes in my example above, as you can see this code really doesn’t need much commenting. The important bit is that the methods all tell you what they are trying to do. Also, the code is split up into nice little modules. This modularity will enable you to unit test your program in little chunks. Alternatively I could have just written all that code inside the parent method, but then I would never be able to test each piece individually.

As I said different languages will restrict you in different ways from making your code as functional and readable at the same time, but its important to understand what you should be aiming for in order to get at least halfway there.

Re: using functions versus copying code twice. Almost always the answer to this is to use functions. There are reasons why you may prefer 2 copies for convenience, but the purist’s view is functions / methods + reuse pls.

Re: global variable naming standards. Sadly the answer here is pretty much no – there isn’t. Reasons are in some languages / environments it is necessary to decorate a variable to give it context. In SQL, we prefix parameters with @p_, where local variables we use @l_. This is necessary because our IDE (Interactive Development Environment) can’t tell us the difference through markup. In the old days before we had nice java IDEs, we used to prefix member variables with an underscore _ for the same reason. Now that code looks dated and our IDEs are smarter, so we don’t need those ugly underscores.

Some languages even come with automated code style checking / quality tools to help you keep your code in order. Java has checkstyle for this.

Re: php, I haven’t used it in anger, but my understanding is that it is pretty good at doing stuff like this bulletin board (rendering html / persisting data to databases), but for true enterprise level applications it falls a bit short (doesn’t have stuff like messaging capabilities / interoperability with other platforms). I work in a large bank and to the best of my knowledge there is zero php around our shop. asp.net on the other hand is a true enterprise platform, where php is good at one particular trick. Caveat: I am a java fanboi, not .net.

Just some random thoughts, fire away with other questions.

Test.


   
ReplyQuote
(@trigger-happy)
Noble Member
Joined: 16 years ago
Posts: 1460
 

I agree with noob on the function list within reason. How many functions is too many noob? I like bundling things together into a function if the flow of logic makes sense to put it there. Having a function for every atomic move is good for scaling and modularity but it can get out of control pretty quickly. Too many helper functions also can lead to functions getting used for purposes that they sometimes aren’t built for making a whole lot of mess if you have to change that function for it’s intended use but not breaking compatibility with the noob that decided to use it for something else.
But in general, functions are good and I tend to wrap as much code into functions to aid in testing.

“Code is meant to be written once and read many times”

Very good quote, you hear it a lot and for good reasons ๐Ÿ™‚
On the flipside though with nooby, I tend to prefer comments there rather than relying on people’s ability to pick good function names. People are inherently stupid and what makes perfect sense to one coder doesn’t always make the same sense to another. Comments about what it is and why it is there makes readability easy. Besides, those who don’t like comments can simply collapse them (in any decent IDE) and everyone is happy.

Cheers


   
ReplyQuote
(@noobitup)
Noble Member
Joined: 15 years ago
Posts: 1380
 

Yep, like with almost anything with computers you can go too far in a certain direction. I guess my point is more modularisation rather than the specific implementation of how you do it (methods / functions whatever). Modularity is the goal and you certainly can make things too modular. Modularity gives benefits around testability and also reuse / readability most times.

I like to try to break the code down into meaningful chunks (that was the intention of my example). Certainly some of those methods could be bundled up together, and some of them could probably be split up further. It really comes down to what is a happy medium. It has to make sense to a reasonable human.

Test.


   
ReplyQuote
(@black-racoon)
Member Admin
Joined: 16 years ago
Posts: 2007
Topic starter  

Thankyou both VERY MUCH! I guess Ill get more into the habit of using functions and “chunking” my code to make it simpler in general.

I have a few other questions not really related to Coding Standards however..

1. If you do a job for a small business and they continue to call upon you do you charge them for the extra work or should a Coder set up a 12 month contract before hand and say, I will give you free updates for 12 months (as I have seen by quite a few coders). But if someone wants a large update it could mean hours of work… especially if you haven’t revisited the code for 6 months since.. Or does it depend on the amount you charge?

2. How much do coders charge per an hourly charge? I tried having a look around at php /mysql / javascript / ajax coders and I have seen so many charge 10 an hour… (online sites mostly)? I don’t see how coding as a web developer for that kind of a price is worth it… may as well work as a packer or at Mc Donalds seriously? How do you work out how much to charge per hour for a job, or can you only really justify that based on experience with programming in that language.

3. What is programming jobs like…. everywhere I freakin look there are programmers of all kinds scourging the earth of any possible jobs left :P. Job availability in these areas..

4. Why is .net such a growing area. What makes the differnce between Visual Basic and visual basic.net is it just dotnet with the coding standard as the original language I am unsure of that?

Kind Regards, BR – Sorry to inundate you guys with so many questions.


   
ReplyQuote
(@nelots)
Noble Member
Joined: 16 years ago
Posts: 2047
 

@BR

1. Before commencing any project you should make a contract specifying the requirements and any additional support that you may offer the client.
As for you query on additional work, include a schedule of fees to your contract so your client is aware of any additional charges. In general if the works required is small, charge hourly rates and if its a major update then re-negotiate a new contract.

2. Coders can charge anything for their hourly rate but it is primarily based on their qualifications and experience in the field.
What you need to know is that clients will have the mindset of “You get what you pay for.” Meaning medium to big businesses will not consider using your services unless you charge the big bucks and only small businesses will delve into the lower end of the market.
Finally the hourly rate you’ve seen is that low due to the fact that there are too many amateur(nerds in their parents basement) coders out there who drive the average asking price so low. It’s simple economics really, the good old demand and supply curve shit.

Your an inbecile full stop.

noobItUp <> sorry I started playing with butz again


   
ReplyQuote
(@trigger-happy)
Noble Member
Joined: 16 years ago
Posts: 1460
 

Good point nooby ๐Ÿ™‚
I think you have to go by ear on each project as different requirements mean different things, I guess the point to make from both of us is that ensuring you don’t replicate code is a good thing and readability is the key to any programming across any language. Standards and practices change across languages and workplaces so you are generally bound to the code that you are already given to how you will create it. If it is your own code you can create whatever standard of doing things you want, just make sure it is logical and readable.
As for the payrates thing, as butz said, you negotiate a contract for the job and generally have a price set for the whole project and then charge by the hour for maintenance work. Never agree to do updates for free for 12 months, they might want you to redesign a whole new site for all you know. You could start out with a larger per hour rate but if it is something small perhaps do it out of goodwill etc if they are likely to come back to you with more work. On the flipside, if you charge too much they might just get someone else to do the little things but it might not be worth your time anyway. I guess it is up to you and what you want to do.
.net is big because MS was smart enough to market it and get it out there to be snapped up by the masses. I guess the good thing about it is that people who are familiar with the traditional languages, (aka C# for those coming from OO places) are able to make their applications on the web as they can write in things like C# instead of php which is a rather unstructured language from what I remember.
Those 10 dollar an hour coders are the guys you don’t want to compete with, who knows what kind of crap they might come out with. I am sure any serious business would be smart enough not to touch those with a ten foot pole. A lot of companies that want to get something done on the cheap with a chance of it still working send out a position to universities and market it as “work experience” and either pay really low or get it done for free by students who think it is a break into the industry.

Cheers


   
ReplyQuote
(@antagonist)
Noble Member
Joined: 15 years ago
Posts: 1007
 

my aunty used to be a sub contracted computer engineer for NASA in the early 80s.. and she was charge $700 and hour back then… so i dread to think what high end computer nerds earn these days..

she now runs the entire bankwest computer system.. and does EXTREMELY fucking well for herself…

Ulti has hacked since the down of time, and he is still mad that nobody will be his friend.


   
ReplyQuote
(@black-racoon)
Member Admin
Joined: 16 years ago
Posts: 2007
Topic starter  

amateur(nerds in their parents basement)….

well I’m upstairs so its not quite a basement.. and I’m not exactly a nerd.. My point is to move away from the sub crappy standard that exists out there for php/sql anyway. I’m not saying there aren’t excellent coders out there.. but it just seems that php is a language that anyone can do..

@Trigger

Well I have never quite set up a contract.. its more just call on work.

New Question

I have recently encountered an issue where automation of a small business would in my opinion face to face with the client, would be easiest for me to understand their business.. My Question is whether I just request they come in and have some red tea and discuss the process’s in the their business that can be automated. OR, should I just try and communicate as much as possible via email/telephone? Should I pherhaps just research the working of a business and try to understand what they are exactly dealing with myself?

Kind Regards, BR


   
ReplyQuote
(@trigger-happy)
Noble Member
Joined: 16 years ago
Posts: 1460
 

Best to go in if you can. Nothing beats having a look around yourself to get the gears moving in your head. Failing that, all documentation pertaining to what you are working with is needed.
You are embarking on automating a business are you? What kind of automation are you dealing with here?

Cheers


   
ReplyQuote
(@black-racoon)
Member Admin
Joined: 16 years ago
Posts: 2007
Topic starter  

Well… Generating some CSV stuff for them so it will happily slide into MYOB for them.. all information form a databases and then to be able to have all like class rolls or such to print out to make life easier I’m assuming so basically automating the stuff they had to do manually before via input. I found out though that you can never automate everything. Something always requires some sort of manual input at the end, just the amount can be reduced.

Cheers, BR


   
ReplyQuote
(@nelots)
Noble Member
Joined: 16 years ago
Posts: 2047
 

I have recently encountered an issue where automation of a small business would in my opinion face to face with the client, would be easiest for me to understand their business.. My Question is whether I just request they come in and have some red tea and discuss the process’s in the their business that can be automated. OR, should I just try and communicate as much as possible via email/telephone? Should I pherhaps just research the working of a business and try to understand what they are exactly dealing with myself?
Kind Regards, BR

In that situation you must always visit the clients premises to understand the daily operations of their staff and plan a detailed IPO before starting the actual coding process.
You should always research the clients inner business and work around what they’re use to, also canvas the office to see what the operators are expecting, ideas or possible modifications they may require.

Your an inbecile full stop.

noobItUp <> sorry I started playing with butz again


   
ReplyQuote
Page 1 / 2
Share: