Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code style for private methods in C# [closed]

I just found out, that it seems a common pattern to use UpperFirstLetterPascalCase() for private methods. I for myself, find this completely inconsistent with naming rules of private instance fields and variables and I find it difficult to read/debug, too.

I would want to ask, why using a first upper letter for methods could be a better choice than a first lower doThis()? Just out of curiosity...

like image 794
Jan Avatar asked May 03 '10 14:05

Jan


People also ask

Are private methods a code smell?

Private methods aren't a code smell. If a method can be made private, it should be made private. Making a method public when it doesn't need to be brings no advantage and only creates a liability. Do test private methods, but only indirectly through their public interfaces.

Where do you put private methods?

Martin advises coders to always put member variables at the top of the class (constants first, then private members) and methods should be ordered in such a way so that they read like a story that doesn't cause the reader to need to jump around the code too much.

Should methods be lowercase?

Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized. Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter.


1 Answers

All method names in C# start with an upper-case letter by convention. All property names do so too. Only private fields, local variables and parameters to methods start with a lower-case letter (AFAIR).

It's a convention so asking for a »why« is a little misplaced. It's probably akin to asking »Why does the Java coding convention prefer lower-case letters for everything except classes?«—answers to such questions are usually »Because someone, somewhere, once decided that it'd be a good idea to do so«. The rest then merely is history—or convention and you either follow it or you don't (in which case you make the lives of people reading your code harder).

ETA: As said in a comment already, (imho) the answer to the question »why?« usually leads to what the language designers (or the people coming up with the convention) considered to be important aspects to be covered by the convention. In Java it's clearly a case of visually distinguishing classes (PascalCase), variables/fields (camelCase) and properties (get~()/set~()). For .NET there obviously was a need of immediately telling classes and interfaces apart (something I consider pretty nice to have too) and visually distinguishing property (PascalCase) and field (camelCase) access.

Usually in such scenarios all things not initially considered important for the convention fall short in obviousness.

like image 172
Joey Avatar answered Sep 18 '22 15:09

Joey