Mixing up casing, but keeping it consistent - syntax

There is a general opinion that whatever casing style you pick for yourself, just make sure to be consistent with it. Let's say I want to mix it a bit, but still keep it technically consistent, such as camelCase for functions, and snake_case for variables. Is this still acceptable, or is this frowned upon?

You almost certainly want to keep to the industry standards for the language(s) you are using. Any teams you work with will most likely use these, and remaining consistent among your team greatly improves readability and maintainability.
If you are doing your own project, I would still recommend sticking to those standards. It's simply better to maintain the habit for when you do eventually work as part of a team.
Most industry naming conventions are as you describe. One case standard for variable names, another for function names, another for class and namespace, etc etc

Related

First time porting a library from one language to another

I am porting a library from C++ to Java. This is my first time and I am not sure
about what "porting" really means? Specifically, what if the author named a variable
as 'A' and I think that a better name would be 'B'. Same for methods, classes and namespaces.
Also, what if I think something can be done better? Does porting mean that I should try
to keep as much of the original code spirit as possible, but still allow myself freedom
to improve stuff?
Thanks
It doesn't necessarily have to be a one-to-one translation (and in many cases, it can't be done). Porting is just rewriting a piece of software in a different language/environment/etc. Sometimes porting will require you to tweak things and implement them in different ways altogether, so I think the last sentence of your post pretty much captures the gist of things.
I view it as comparable to translating a book from English to another language. There will be instances where judgment calls need to be made in terms of how to express the intent/function of the source material.
When porting from System A to System B, the world is your oyster. You can pretty much change anything if you believe it's an improvement. The only caveats to that are when dealing with interfaces. Say, you are porting an API, for example, it wouldn't be a good idea to name externally-available methods, as that would break something down the road. Tracing naming issues across multiple classes is a major pain.
As someone who's done a fair bit of porting from language to language, I would recommend sticking to implementation details first and foremost. A good engineering principle is to change one thing at any time. That way, when things don't run as expected, you'll know that it's your implementation that is to blame, and not some silly naming issue. And when you do come to renaming, I suppose it goes without saying, be very careful and backup often. This is one case where software versioning may save you hours of time.
When "porting" a library from one platform to another, you are porting functionality. You are not porting style of code. It isn't like in literature, where one must maintain the style of the piece, keeping in mind metaphors and iambic pentameter or what have you.

Should class members be sorted?

On a new project with a new team, should we enforce to sort the members of the classes automatically in a specific order (e.g. by modifier and alphabet) prior to check-in?
The alternative is to let each developer group the members as he thinks. And since everyone has a different opinion of what is related and how the grouping should be, this pretty much comes down to random order.
So what are the pros and cons of having them sorted automatically? Is this bound to a specific IDE/development-process/build-process/language? What else do we have to consider?
Edit to foster more answers:
I once was in a project where we had to maintain several branches. Because of the inability of the RCS to support this appropriately (SVN by the time), we had to manually move classes and methods from one branch to another and than merge back again (most RCS can maintain a subset-superset-relation only in one direction). Because the methods could appear anywhere in the class in any order, merging was a nightmare. Enforcing automatic sorting of members right from the beginning would have avoided much of the pain.
On the other hand, if working in a long existing project without automatic sort order, it can be a bad idea to enforce this. Moving all the members around is basically the same as throwing away the versioning up to this point, because comparing files with older versions via diff will be no good anymore for the same reason that merging in the other project was a pain.
Same goes if refactoring is due. When methods are renamed they will also be moved, making a diff of two versions practically pointless. With different names AND different places, it is difficult to recognize methods again.
Given that your IDE can sort your members the way you prefer, I'd personally avoid a global company policy on the matter.
I think rules-for-rules-sake are an important factor in de-motivating a team. As programmers we have a certain mindset, a certain way of seeing the world. Practicality and pragmatism are often valued higher by many programmers than policy.
If it's a quick click of a couple of menu items to have the code look the way you want it to when it's your turn to look at it, I'd stick with those few clicks. (and make this into a quick keyboard shortcut for your convenience)
I like to have a consistent code layout, but I have learned the hard way that anything which only touches the topic of "coding style" always leads to endless discussions and can waste a lot of time. It is not worth it.
Far more important is to make decisions on other topics (architecture and design, tests, how to communicate).
Usually I tend to assume that related members will be grouped together over time. I see no advantage in using an alphabetical sort order, because that is what the IDE can do for me.
Renaming, moving code, deleting green code, adding comments is nothing I like to see mixed with other changes. That is why I usually split it into two changes - one, that updates the "code layout/style" and another, which changes the behaviour of the program.
In my case... I consider usefull to order by access level. I follow the StyleCop rules (.net but valid in any other languaje)
Public
Internal
Protected Internal
Protected
Private
static
non-static
Inside of this groups... I've some randomness, but I always put things like Id's or unique identificator first.
I'm not saying this is the better good practice in the word, but at least people know where to look for things.
Depending of the lenguaje and the IDE you choose, maybe you could be lucky and find a tool that rearange the code for you based on your owns preferences. (Resharper, in my case, It's a good help)
I consider sorting of class members useful if it results in better readability of code. A sorting scheme should not be too strict but strict enough to add to better code readability. I prefer this sorting scheme:
static fields
instance fields
constructor
methods
Each method that calls another method (mostly private) the called method should be below the calling method.
As pointed out above the only reason to order class members should be better readability because you write code once but read it a hundred times, so having an accepted (by the team) order system can boost productivity.
Ordering code to work around inabilities of RCS will not per se lead to better readability and thus will not boost productivity. In most cases such an ordering method will fail. I'm in doubt if an alphabetic order method could lead to better readability.

Is this backwards naming convention a bad idea (ie. contrary to industry standards)?

I've always reversed names so that they naturally group in intellisense. I am wondering if this is a bad idea.
For example, I run a pet store and I have invoicing pages add, edit, delete, and store pages display, preview, edit. To get the URL for these, I would call the methods (in a suitable class like GlobalUrls.cs
InvoicingAddUrl()
InvoicingEditUrl()
InvoicingDeleteUrl()
StoreDisplayUrl()
StorePreviewUrl()
StoreEditUrl()
This groups them nicely in intellisense. More logical naming would be:
AddInvoiceUrl()
EditInvoiceUrl()
DeleteInvoiceUrl()
DisplayStoreUrl()
PreviewStoreUrl()
EditStoreUrl()
Is it better (better being, more of an industry standard way) to group them for intellisense, or logically?
Grouping in Intellisense is just one factor in creating a naming scheme, but logically grouping by category rather than function is a common practice as well.
Most naming "conventions" dictate usage of characters, casing, underscores, etc. I think it is a matter of personal preference (company, team or otherwise) as to whether you use NounVerb or VerbNoun formatting for your method names.
Here are some resources:
Microsoft - General Naming Conventions
Wikibooks C# Programming/Naming
Akadia .NET Naming Conventions
Related questions:
Naming Conventions - Guidelines for Verbs, Nouns and English Grammar Usage
Do vs. Run vs. Execute vs. Perform verbs
Events - naming convention and style
Check out how the military names things. For example, MREs are Meals, Ready to Eat. They do this because of sort order, efficiency and not making mistakes. They are ready to ignore the standard naming conventions of the language (i.e., English) used outside of their organization because they are not impressed with the quality of operations outside of their organization. In the military, the quality of operations is literally a matter of life and death. Also, by doing things their own way they have a way of identifying who is inside and who is outside of the organization. Anyone unable or unwilling to learn the military way, which is different but not impossibly difficult, is not their first choice for recruitment or promotion.
So, if you are impressed with the standard quality of software out there, then by all means keep doing what everyone else is doing. But, if you wish to do better than you have in the past, or better than your competitor, then I suggest looking at other fields for lessons learned the hard way, such as the military. Then make some choices for your organization, that are not impossible but are for you and your competitiveness. You can choose big-endian names (most significant information comes last) or the military-style little-endian names (most significant information comes first), or you can use the dominant style your competitors probably use, which is doing whatever you feel like whenever you feel like it.
Personally, I prefer little-endian Hungarian (Apps) naming, which was widely seen as superior when it first came out, but then lost favor because Hungarian (Sys) naming destroyed the advantage due to a mistranslation of the basic idea, and because of rampant abbreviations. The original intent was to start a name with what kind of a thing it is, then become increasingly specific until you end with a unique qualification. This is also the order that most array dimensions and object qualifiers are in, so in most languages little-endian naming flows into the larger scheme of the language.
You are on to something. Forward, march.
It's not intrinsically bad. It has the upside of being easier to identify the type while scanning, and groups the options together in Intellisense like you said. As long as you and everyone else on your team picks a way of doing things and stays consistent about it there shouldn't be any big problems.
Based on the methods listed, you might be able to refactor Invoicing and Store out into their own classes, which would be closer to the mythical "industry standard" way.
That said, whatever your programming team can agree on for naming convention should be fine. The important thing is to be consistent within the project.
I don't think it's a good idea to develop a coding standard around a tool (as least not as the first consideration). Even though most IDEs will have Intellisense these days, and most people will be using said IDEs, I think that first and foremost a coding standard should be about making the code legible and navigable on its own merits.
I would opt for most logical naming, personally. When I write code and I have some object I'm about to call a member function on, I'm usually thinking about what member function to call based on the action I'm about to do, because I already know the object I'm manipulating. So my first impulse would be to start typing "Add" if I wanted to add something, and see what Intellisense showed me. This is, of course, subjective.
I have never actually seen anybody using your alphabetical, Intellisense grouping anywhere -- at least not in code that is not worth using as a basis for comparison because it was so horrid in other ways.
That said, if it's your standard, do what you want -- consistency is the important part.

Why is tightly coupled bad but strongly typed good?

I am struggling to see the real-world benefits of loosely coupled code. Why spend so much effort making something flexible to work with a variety of other objects? If you know what you need to achieve, why not code specifically for that purpose?
To me, this is similar to creating untyped variables: it makes it very flexible, but opens itself to problems because perhaps an unexpected value is passed in. It also makes it harder to read, because you do not explicitly know what is being passed in.
Yet I feel like strongly typed is encouraged, but loosely coupling is bad.
EDIT: I feel either my interpretation of loose coupling is off or others are reading it the wrong way.
Strong coupling to me is when a class references a concrete instance of another class. Loose coupling is when a class references an interface that another class can implement.
My question then is why not specifically call a concrete instance/definition of a class? I analogize that to specifically defining the variable type you need.
I've been doing some reading on Dependency Injection, and they seem to make it out as fact that loose coupling better design.
First of all, you're comparing apples to oranges, so let me try to explain this from two perspectives. Typing refers to how operations on values/variables are performed and if they are allowed. Coupling, as opposed to cohesion, refers to the architecture of a piece (or several pieces) of software. The two aren't directly related at all.
Strong vs Weak Typing
A strongly typed language is (usually) a good thing because behavior is well defined. Take these two examples, from Wikipedia:
Weak typing:
a = 2
b = '2'
concatenate(a, b) # Returns '22'
add(a, b) # Returns 4
The above can be slightly confusing and not-so-well-defined because some languages may use the ASCII (maybe hex, maybe octal, etc) numerical values for addition or concatenation, so there's a lot of room open for mistakes. Also, it's hard to see if a is originally an integer or a string (this may be important, but the language doesn't really care).
Strongly typed:
a = 2
b = '2'
#concatenate(a, b) # Type Error
#add(a, b) # Type Error
concatenate(str(a), b) # Returns '22'
add(a, int(b)) # Returns 4
As you can see here, everything is more explicit, you know what variables are and also when you're changing the types of any variables.
Wikipedia says:
The advantage claimed of weak typing
is that it requires less effort on the
part of the programmer than, because
the compiler or interpreter implicitly
performs certain kinds of conversions.
However, one claimed disadvantage is
that weakly typed programming systems
catch fewer errors at compile time and
some of these might still remain after
testing has been completed. Two
commonly used languages that support
many kinds of implicit conversion are
C and C++, and it is sometimes claimed
that these are weakly typed languages.
However, others argue that these
languages place enough restrictions on
how operands of different types can be
mixed, that the two should be regarded
as strongly typed languages.
Strong vs weak typing both have their advantages and disadvantages and neither is good or bad. It's important to understand the differences and similarities.
Loose vs Tight Coupling
Straight from Wikipedia:
In computer science, coupling or
dependency is the degree to which each
program module relies on each one of
the other modules.
Coupling is usually contrasted with
cohesion. Low coupling often
correlates with high cohesion, and
vice versa. The software quality
metrics of coupling and cohesion were
invented by Larry Constantine, an
original developer of Structured
Design who was also an early proponent
of these concepts (see also SSADM).
Low coupling is often a sign of a
well-structured computer system and a
good design, and when combined with
high cohesion, supports the general
goals of high readability and
maintainability.
In short, low coupling is a sign of very tight, readable and maintainable code. High coupling is preferred when dealing with massive APIs or large projects where different parts interact to form a whole. Neither is good or bad. Some projects should be tightly coupled, i.e. an embedded operating system. Others should be loosely coupled, i.e. a website CMS.
Hopefully I've shed some light here :)
The question is right to point out that weak/dynamic typing is indeed a logical extension of the concept of loose coupling, and it is inconsistent for programmers to favor one but not the other.
Loose coupling has become something of a buzzword, with many programmers unnecessarily implementing interfaces and dependency injection patterns -- or, more often than not, their own garbled versions of these patterns -- based on the possibility of some amorphous future change in requirements. There is no hiding the fact that this introduces extra complexity and makes code less maintainable for future developers. The only benefit is if this anticipatory loose coupling happens to make a future change in requirements easier to implement, or promote code reuse. Often, however, requirements changes involve enough layers of the system, from UI down to storage, that the loose coupling doesn't improve the robustness of the design at all, and makes certain types of trivial changes more tedious.
You're right that loose coupling is almost universally considered "good" in programming. To understand why, let's look at one definition of tight coupling:
You say that A is tightly coupled to B if A must change just because B changed.
This is a scale that goes from "completely decoupled" (even if B disappeared, A would stay the same) to "loosely coupled" (certain changes to B might affect A, but most evolutionary changes wouldn't), to "very tightly coupled" (most changes to B would deeply affect A).
In OOP we use a lot of techniques to get less coupling - for example, encapsulation helps decouple client code from the internal details of a class. Also, if you depend on an interface then you don't generally have to worry as much about changes to concrete classes that implement the interface.
On a side note, you're right that typing and coupling are related. In particular, stronger and more static typing tend to increase coupling. For example, in dynamic languages you can sometimes substitute a string for an array, based on the notion that a string can be seen as an array of characters. In Java you can't, because arrays and strings are unrelated. This means that if B used to return an array and now returns a string, it's guaranteed to break its clients (just one simple contrived example, but you can come up with many more that are both more complex and more compelling). So, stronger typing and more static typing are both trade-offs. While stronger typing is generally considered good, favouring static versus dynamic typing is largely a matter of context and personal tastes: try setting up a debate between Python programmers and Java programmers if you want a good fight.
So finally we can go back to your original question: why is loose coupling generally considered good? Because of unforeseen changes. When you write the system, you cannot possibly know which directions it will eventually evolve in two months, or maybe two hours. This happens both because requirements change over time, and because you don't generally understand the system completely until after you've written it. If your entire system is very tightly coupled (a situation that's sometimes referred to as "the Big Ball of Mud"), then any change in every part of the system will eventually ripple through every other part of the system (the definition of "very tight coupling"). This makes for very inflexible systems that eventually crystallize into a rigid, unmaintanable blob. If you had 100% foresight the moment you start working on a system, then you wouldn't need to decouple.
On the other hand, as you observe, decoupling has a cost because it adds complexity. Simpler systems are easier to change, so the challenge for a programmer is striking a balance between simple and flexible. Tight coupling often (not always) makes a system simpler at the cost of making it more rigid. Most developers underestimate future needs for changes, so the common heuristic is to make the system less coupled than you're tempted to, as long as this doesn't make it overly complex.
Strongly typed is good because it prevents hard to find bugs by throwing compile-time errors rather than run-time errors.
Tightly coupled code is bad because when you think you "know what you need to achieve", you are often wrong, or you don't know everything you need to know yet.
i.e. you might later find out that something you've already done could be used in another part of your code. Then maybe you decide to tightly couple 2 different versions of the same code. Then later you have to make a slight change in a business rule and you have to alter 2 different sets of tightly coupled code, and maybe you will get them both correct, which at best will take you twice as long... or at worst you will introduce a bug in one, but not in the other, and it goes undetected for a while, and then you find yourself in a real pickle.
Or maybe your business is growing much faster than you expected, and you need to offload some database components to a load-balancing system, so now you have to re-engineer everything that is tightly coupled to the existing database system to use the new system.
In a nutshell, loose coupling makes for software that is much easier to scale, maintain, and adapt to ever-changing conditions and requirements.
EDIT: I feel either my interpretation
of loose coupling is off or others are
reading it the wrong way. Strong
coupling to me is when a class
references a concrete instance of
another class. Loose coupling is when
a class references an interface that
another class can implement.
My question then is why not
specifically call a concrete
instance/definition of a class? I
analogize that to specifically
defining the variable type you need.
I've been doing some reading on
Dependency Injection, and they seem to
make it out as fact that loose
coupling better design.
I'm not really sure what your confusion is here. Let's say for instance that you have an application that makes heavy use of a database. You have 100 different parts of your application that need to make database queries. Now, you could use MySQL++ in 100 different locations, or you can create a separate interface that calls MySQL++, and reference that interface in 100 different places.
Now your customer says that he wants to use SQL Server instead of MySQL.
Which scenario do you think is going to be easier to adapt? Rewriting the code in 100 different places, or rewriting the code in 1 place?
Okay... now you say that maybe rewriting it in 100 different places isn't THAT bad.
So... now your customer says that he needs to use MySQL in some locations, and SQL Server in other locations, and Oracle in yet other locations.
Now what do you do?
In a loosely coupled world, you can have 3 separate database components that all share the same interface with different implementations. In a tightly coupled world, you'd have 100 sets of switch statements strewn with 3 different levels of complexity.
If you know what you need to achieve, why not code specifically for that purpose.
Short answer: You almost never know exactly what you need to achieve. Requirements change, and if your code is loosely coupled in the first place, it will be less of a nightmare to adapt.
Yet I feel like strongly typed is encouraged, but loosely coupling is bad.
I don't think it is fair to say that strong typing is good or encouraged. Certainly lots of people prefer strongly typed languages because it comes with compile-time checking. But plenty of people would say that weak typing is good. It sounds like since you've heard "strong" is good, how can "loose" be good too. The merits of a language's typing system isn't even in the realm of a similar concept as class design.
Side note: don't confuse strong and static typing
strong typing will help reduce errors while typically aiding performance. the more information the code-generation tools can gather about acceptable value ranges for variables, the more these tools can do to generate fast code.
when combined with type inference and feature's like traits (perl6 and others) or type classes (haskell), strongly typed code can continue to be compact and elegant.
I think that tight/loose coupling (to me: Interface declaration and assignment of an object instance) is related to the Liskov Principle. Using loose coupling enables some of the advantages of the Liskov Principle.
However, as soon as instanceof, cast or copying operations are executed, the usage of loose coupling starts being questionable. Furthermore, for local variables withing a method or block, it is non-sense.
If any modification done in our function, which is in a derived class, will change the code in the base abstract class, then this shows the full dependency and it means this is tight coupled.
If we don't write or recompile the code again then it showes the less dependency, hence it is loose coupled.

Do you think a software company should impose developers a coding-style? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
If you think it shouldn't, explain why.
If yes, how deep should the guidelines be in your opinion? For example, indentation of code should be included?
I think a team (rather than a company) need to agree on a set of guidelines for reasonably consistent style. It makes it more straightforward for maintenance.
How deep? As shallow as you can agree on. The shorter and clearer it is the more likely it is that all the team members can agree to it and will abide by it.
You want everybody reading and writing code in a standard way. There are two ways you can achieve this:
Clone a single developer several times and make sure they all go through the same training. Hopefully they should all be able to write the same codebase.
Give your existing developers explicit instruction on what you require. Tabs or spaces for indentation. Where braces sit. How to comment. Version-control commit guidelines.
The more you leave undefined, the higher the probability one of the developers will clash on style.
The company should impose that some style should be followed. What style that is and how deep the guidelines are should be decided collectively by the developer community in the company.
I'd definitely lay down guidelines on braces, indentation, naming etc...
You write code for readability and maintainability. Always assume someone else is going to read your code.
There are tools that will auto magically format your code , and you can mandate that everyone uses the tool.
If you are on .Net look at stylecop, fxcop and Resharper
Do you think a software company should impose developers a coding-style?
Not in a top-down manner. Developers in a software company should agree on a common coding style.
If yes, how deep should the guidelines be in your opinion?
They should only describe the differences from well-known conventions, trying to keep the deviation minimal. This is easy for languages like Python or Java, somewhat blurry for C/C++, and almost impossible for Perl and Ruby.
For example, indentation of code should be included?
Yes, it makes code much more readable. Keep indentation consistent in terms of spaces vs tabs and (if you opt for spaces) number of space characters. Also, agree on a margin (e.g. 76 chars or 120 chars) for long lines.
Yes, but within reason.
All modern IDEs offer one-keystroke code pretty-print, so the "indentation" point is quite irrelevant, in my opinion.
What is more important is to establish best practices: for example, use as little "out" or "ref" parameters as possible... In this example, you have 2 advantages: improves readability and also fixes a lot of mistakes (a lot of out parameters is a code smell and should probably be refactored).
Going beyond that is, in my honest opinion, a bit "anal" and unnecessarily annoying for the devs.
Good point by Hamish Smith:
Style is quite different from best
practices. It's a shame that 'coding
standards' tend to roll the two
together. If people could keep the
style part to a minimum and
concentrate on best practices that
would probably add more value.
I don't believe a dev team should have style guidelines they must follow as a general rule. There are exceptions, for example the use of <> vs. "" in #include statements, but these exceptions should come from necessity.
The most common reason I hear people use to explain why style guidelines are necessary is that code written in a common style is easier to maintain that code written in individual styles. I disagree. A professional programmer isn't going to be bogged down when they see this:
for( int n = 0; n < 42; ++42 ) {
// blah
}
...when they are used to seeing this:
for(int n = 0; n < 42; ++42 )
{
// blah
}
Moreover, I have found it's actually easier to maintain code in some cases if you can identify the programmer who wrote the original code by simply recognizing their style. Go ask them why they implemented the gizmo in such a convoluted way in 10 minutes instead of spending the better part of a day figuring out the very technical reason why they did something unexpected. True, the programmer should have commented the code to explain their reasoning, but in the real world programmers often don't.
Finally, if it takes Joe 10 minutes backspacing & moving his curly braces so that Bill can spend 3 fewer seconds looking at the code, did it really save any time to make Bill do something that doesn't come natural to him?
I believe having a consistent codebase is important. It increases the maintainability of ur code. If everyone expects the same kind of code, they can easily read and understand it.
Besides it is not much of a hassle given today's IDEs and their autoformatting capabilities.
P.S:
I have this annoying habit of putting my braces on the next line :). No one else seems to like it
I think that programmers should be able to adapt to the style of other programmers. If a new programmer is unable to adapt, that usually means that the new programmer is too stubborn to use the style of the company. It would be nice if we could all do our own thing; however, if we all code along some bast guideline, it makes debugging and maintenance easier. This is only true if the standard is well thought out and not too restrictive.
While I don't agree with everything, this book contains an excellent starting point for standards
The best solution would be for IDEs to regard such formatting as meta data. For example, the opening curly brace position (current line or next line), indentation and white space around operators should be configurable without changing the source file.
In my opinion I think it's highly necessary with standards and style guides. Because when your code-base grows you will want to have it consistent.
As a side note, that is why I love Python; because it already imposes quite a lot of rules on how to structure your applications and such. Compare that with Perl, Ruby or whatever where you have an extreme freedom(which isn't that good in this case).
There are plenty of good reasons for the standards to define the way the applications are developed and the way the code should look like. For example when everyone use the same standard an automatic style-checker could be used as a part of the project CI.
Using the same standards improve code readability and helps to reduce the tension between team members about re-factoring the same code in different ways.
Therefore:
All the code developed by the particular team should follow precisely the same standard.
All the code developed for a particular project should follow precisely the same standard.
It is desirable that teams belonging to the same company use the same standard.
In an outsourcing company an exception could be made for a team working for a customer if the customer wants to enforce a standard of their own. In this case the team adopts the customer's standard which could be incompatible with the one used by their company.
Like others have mentioned, I think it needs to be by engineering or by the team--the company (i.e. business units) should not be involved in that sort of decision.
But one other thing I'd add is any rules that are implemented should be enforced by tools and not by people. Worst case scenario, IMO, is some over-zealous grammar snob (yes, we exist; I know because we can smell our own) writes some documentation outlining a set of coding guidelines which absolutely nobody actually reads or follows. They become obsolete over time, and as new people are added to the team and old people leave, they simply become stale.
Then, some conflict arises, and someone is put in the uncomfortable position of having to confront someone else about coding style--this sort of confrontation should be done by tools and not by people. In short, this method of enforcement is the least desirable, in my opinion, because it is far too easy to ignore and simply begs programmers to argue about stupid things.
A better option (again, IMO) is to have warnings thrown at compile time (or something similar), so long as your build environment supports this. It's not hard to configure this in VS.NET, but I'm unaware of other development environments that have similar features.
Style guidelines are extremely important, whether they're for design or development, because they speed the communication and performance of people who work collaboratively (or even alone, sequentially, as when picking up the pieces of an old project). Not having a system of convention within a company is just asking people to be as unproductive as they can. Most projects require collaboration, and even those that don't can be vulnerable to our natural desire to exercise our programming chops and keep current. Our desire to learn gets in the way of our consistency - which is a good thing in and of itself, but can drive a new employee crazy trying to learn the systems they're jumping in on.
Like any other system that's meant for good and not evil, the real power of the guide lies in the hands of its people. The developers themselves will determine what the essential and useful parts are and then, hopefully, use them.
Like the law. Or the English language.
Style guides should be as deep as they want to be - if it comes up in the brainstorm session, it should be included. It's odd how you worded the question because at the end of the day there is no way to "impose" a style guide because it's only a GUIDE.
RTFM, then glean the good stuff and get on with it.
Yes, I think companies should. Developer may need to get used to the coding-style but in my opinion a good programmer should be able to work with any coding style. As Midhat said: It is important to have a consistent codebase.
I think this is also important for opensource projects, there is no supervisor to tell you how to write your code but many languages have specifications on how naming and organisation of your code should be. This helps a lot when integrating opensource components into your project.
Sure, guidelines are good, and unless it's badly-used Hungarian notation (ha!), it'll probably improve consistency and make reading other people's code easier. The guidelines should just be guidelines though, not strict rules enforced on programmers. You could tell me where to put my braces or not to use names like temp, but what you can't do is force me to have spaces around index values in array brackets (they tried once...)
Yes.
Coding standards are a common way of ensuring that code within a certain organization will follow the Principle of Least Surprise: consistency in standards starting from variable naming to indentation to curly brace use.
Coders having their own styles and their own standards will only produce a code-base that is inconsistent, confusing, and frustrating to read, especially on larger projects.
These are the coding standards for a company I used to work for. They're well defined, and, while it took me a while to get used to them, meant that the code was readable by all of us, and uniform all the way through.
I do think coding standards are important within a company, if none are set, there are going to be clashes between developers, and issues with readability.
Having the code uniform all the way through presents a better code to the end user (so it looks as if it's written by one person - which, from an End Users point of view, it should - that person being "the company" and it also helps with readability within the team...
A common coding style promotes consistency and makes it easy for different people to easily understand, maintain and expand the whole code base, not only their own pieces. It also makes it easier for new people to learn the code faster. Thus, any team should have a guidelines on how the code is expected to be written.
Important guidelines include (in no particular order):
whitespace and indentation
standard comments - file, class or method headers
naming convention - classes, interfaces, variables, namespaces, files
code annotations
project organization - folder structures, binaries
standard libraries - what templates, generics, containers and so on to use
error handling - exceptions, hresults, error codes
threading and synchronization
Also, be wary of programmers that can't or won't adapt to the style of the team, no matter how bright they might be. If they don't play by one of the team rules, they probably won't play by other team rules as well.
I would agree that consistency is key. You can't rely on IDE pretty-printing to save the day, because some of your developers may not like using an IDE, and because when you're trawling through a code base of thousands of source files, it's simply not feasible to pretty print all the files when you start working on them, and perform a roll-back afterwards so your VCS doesn't try to commit back all the changes (clogging the repository with needless updates that burden everyone).
I would suggest standardizing at least the following (in decreasing order of importance):
Whitespace (it's easiest if you choose a style that conforms to the automatic pretty-printing of some shared tool)
Naming (files and folders, classes, functions, variables, ...)
Commenting (using a format that allows automatic documentation generation)
My opinion:
Some basic rules are good as it helps everyone to read and maintain the code
Too many rules are bad as it stops developers innovating with clearer ways of laying out code
Individual style can be useful to determine the history of a code file. Diff/blame tools can be used but the hint is still useful
Modern IDEs let you define a formatting template. If there is a corporate standard, then develop a configuration file that defines all the formatting values you care about and make sure everyone runs the formatter before they check in their code. If you want to be even more rigorous about it you could add a commit hook for your version control system to indent the code before it is accepted.
Yes in terms of using a common naming standard as well as a common layout of classes and code behind files. Everything else is open.
Every company should. Consistent coding style ensures higher readibility and maintainability of the codebase across whole your team.
The shop I work at does not have a unified coding standard, and I can say we (as a team) vastly suffer from that. When there is no will from the individuals (like in case of some of my colleagues), the team leader has to bang his fist on the table and impose some form of standardised coding guidelines.
Ever language has general standards that are used by the community. You should follow those as well as possible so that your code can be maintained by other people used to the language, but there's no need to be dictatorial about it.
The creation of an official standard is wrong because a company coding standard is usually too rigid, and unable to flow with the general community using the language.
If you're having a problem with a team member really be out there in coding style, that's an excellent thing for the group to gently suggest is not a good idea at a code review.
Coding standards: YES. For reasons already covered in this thread.
Styling standards: NO. Your readable, is my bewildering junk, and vice versa. Good commenting and code factoring have a far greater benefit. Also gnu indent.
I like Ilya's answer because it incorporates the importance of readability, and the use of continuous integration as the enforcement mechanism. Hibri mentioned FxCop, and I think its use in the build process as one of the criteria for determining whether a build passes or fails would be more flexible and effective than merely documenting a standard.
I entirely agree that coding standards should be applied, and that it should almost always be at the team level. However there are a couple of exceptions.
If the team is writing code that is to be used by other teams (and here I mean that other teams will have to look at the source, not just use it as a library) then there are benefits to making common standards across all the teams using it. Similarly if the policy of the company is to frequently move programmers from one team to another, or is in a position where one team frequently wants to reuse code from another team then it is probably best to impose standards across the company.
There are two types of conventions.
Type A conventions: "please do these, it is better"
and Type B: "please drive on the right hand side of the road", while it is okay to drive on the other side, as long as everyone does the same way.
There's no such thing as a separate team. All code in a good firm is connected somehow, and style should be consistent. It's easier to get yourself used to one new style than to twenty different styles.
Also, a new developer should be able to respect the practices of existing codebase and to follow them.

Resources