A naming convention that works with IntelliSense - c#

I started naming my class instant variables like this:
Car car;
The reason being that I think a car is a perfect description for a variable and I don't need to add additional information.
This worked great for me and I was very happy, but there is one issue that drives me crazy. It messes with the IntelliSense if I want to do the type it may go for the private variable and vice versa.
I've seen people do:
Car myCar;
I'm not crazy about it, but it probably would work.
Any ideas about how to do this better?
I would like to add that this mainly applies to instances of classes created inside of methods.

There are two things I would point out when seeing such code.
You obviously don't have a naming convention for variables. I think such a convention is very useful, especially for distinguishing Properties, member-variables and local variables.
Common Conventions in the .NET ecosystem are:
_privateVariable (Used by Microsoft
and a lot of designer generated code,
e.g. linq2sql)
m_privateVariable (Also used by Microsoft, I think TypedDatasets are
generated using this convention, but I'm not sure.)
Properties always use PascalCaseAndNoExtras
loacl varaibles are always camelcaseAndNoExtras
The second thing is about naming a variable like the class at all. I think it is better not to use the name of the class as a variable name. A good variable name should convey the type and the meaning of a variable in the scope the variable is present.
E.g. if you wanted to display information about a car a customer likes to rent you would rather name your variable m_CarToRent instead of m_Car.

You also can use this keyword this.car. It will solve your intellisense issue.
I myself prefer what Daniel suggested to use underscore like _car.

Some people, like me, use _Car for private member variables.

One of the good practices would be:
public class Driver
{
private Car _car;
public Car Car { get { return _car; } }
public Driver(Car car)
{
_car = car;
}
}
_ would mean, the clients of the class don't see this one, and it's better then 'm_' because it does not add anything to just '_' or 'my', because "my" is already an assumption of the usage.
As a guidance, you can try installing Resharper http://www.jetbrains.com/resharper/ and you will soon get used to a good naming convention.
Before i tried it, i was always changing my naming convention styles, and could not get rid of the awkward 'this' keyword here and there.

I will typically use "current" in front of the (local) variable, especially if it's in a loop.
Car currentCar = new Car();
And
foreach( var currentCar in CarList ) {
currentCar.Xxxx();
}
I find this helps with readability, but it's completely subjective.

The first approach is to use prefixes. I use prefixes such as m, e, v, i, p (MemberVariable, Event, Volatile, Index/Iterator, Pointer), etc which allows me to see these different usages of variable grouped nicely in intellisense lists, as well as understand instantly how a variable should be used just from its name. I really don't understand why some people don't do this - it is a long proven approach to speed up coding and make programming easier and less error prone (especially with pointers and pointers to pointers). Over the years I've see a lot of avoidable bugs from programmers on my team who refused to follow these simple conventions.
The second is to differentiate type names and instances better.
Using Car car, or even worse, a property: Car Car {get;set;} as you rightly point out is rather confusing. It's long been accepted that differentiating names based only on case is a bad thing to do, and having two names that are identical (type, property) is even worse.
But there are approaches that can be applied to avoid this (especially for parameters/locals where you may not be using prefixes):
Use synonyms: Vehicle car;.
Use general (type) and context-specific (instance) terms Vehicle licensedVehicle. This helps your instance code describe not just that something is a car, but what form of car you expect it to be
Lastly, things can get worse as you augment your code in the future. Bear in mind what happens when you build a class hierarchy with vague (effectively "non-scalable") naming:
You start off with names like Vehicle.Type. This seems logical: The type of the vehicle (private, passenger, light-goods, heavy-goods). Then you add derived classes Car, Bus, Truck. For a Bus (Type=passenger) you want to add a "Type" (minibus, coach, double-decker). So now you have base class Vehicle.Type and derived class Bus.Type that mean completely different things. Avoiding use of the generic term "Type" in both cases by calling them (for example) Vehicle.VehicleType and Bus.BusType clarifies things immensely, and eliminates any chance of programmers mixing them up.
(This isn't a great example, as I've based it on the Car naming idea, but hopefully it gets across the general point - good, specific, descriptive naming minimises the confusion that users of your class and maintainers of your code will face in future)

Not only is that confusing to VS, but also it borders on being confusing conceptually. Car should be something like Accord, Celica, or Mini and the instance myCar, car1, etc. :-)

Related

What is the name of this bad practice / anti-pattern?

I'm trying to explain to my team why this is bad practice, and am looking for an anti-pattern reference to help in my explanation. This is a very large enterprise app, so here's a simple example to illustrate what was implemented:
public void ControlStuff()
{
var listOfThings = LoadThings();
var listOfThingsThatSupportX = new string[] {"ThingA","ThingB", "ThingC"};
foreach (var thing in listOfThings)
{
if(listOfThingsThatSupportX.Contains(thing.Name))
{
DoSomething();
}
}
}
I'm suggesting that we add a property to the 'Things' base class to tell us if it supports X, since the Thing subclass will need to implement the functionality in question. Something like this:
public void ControlStuff()
{
var listOfThings = LoadThings();
foreach (var thing in listOfThings)
{
if (thing.SupportsX)
{
DoSomething();
}
}
}
class ThingBase
{
public virtual bool SupportsX { get { return false; } }
}
class ThingA : ThingBase
{
public override bool SupportsX { get { return true; } }
}
class ThingB : ThingBase
{
}
So, it's pretty obvious why the first approach is bad practice, but what's this called? Also, is there a pattern better suited to this problem than the one I'm suggesting?
Normally a better approach (IMHO) would be to use interfaces instead of inheritance
then it is just a matter of checking whether the object has implemented the interface or not.
I think the anti-pattern name is hard-coding :)
Whether there should be a ThingBase.supportsX depends at least somewhat on what X is. In rare cases that knowledge might be in ControlStuff() only.
More usually though, X might be one of set of things in which case ThingBase might need to expose its capabilities using ThingBase.supports(ThingBaseProperty) or some such.
IMO the fundamental design principle at play here is encapsulation. In your proposed solution you have encapsulated the logic inside of the Thing class, where as in the original code the logic leaks out into the callers.
It also violates the Open-Closed principle, since if you want to add new subclasses that support X you now need to go and modify anywhere that contains that hard-coded list. With your solution you just add the new class, override the method and you're done.
Don't know about a name (doubt such exists) but think of each "Thing" as a car - some cars have Cruise Control system and others do not have.
Now you have fleet of cars you manage and want to know which have cruise control.
Using the first approach is like finding list of all car models which have cruise control, then go car by car and search for each in that list - if there it means the car has cruise control, otherwise it doesn't have. Cumbersome, right?
Using the second approach means that each car that has cruise control come with a sticker saying "I has cruise control" and you just have to look for that sticker, without relying on external source to bring you information.
Not very technical explanation, but simple and to the point.
There is a perfectly reasonable situation where this coding practice makes sense. It might not be an issue of which things actually support X (where of course an interface on each thing would be better), but rather which things that support X are ones that you want to enable. The label for what you see is then simply configuration, presently hard-coded, and the improvement on this is to move it eventually to a configuration file or otherwise. Before you persuade your team to change it I would check this is not the intention of the code you have paraphrased.
The Writing Too Much Code Anti-Pattern. It makes it harder to read and understand.
As has been pointed out already it would be better to use an interface.
Basically the programmers are not taking advantage of Object-Oriented Principles and instead doing things using procedural code. Every time we reach for the 'if' statement we should ask ourselves if we shouldn't be using an OO concept instead of writing more procedural code.
It is just a bad code, it does not have a name for it (it doesn't even have an OO design). But the argument could be that the first code does not fallow Open Close Principle. What happens when list of supported things change? You have to rewrite the method you're using.
But the same thing happens when you use the second code snippet. Lets say the supporting rule changes, you'd have to go to the each of the methods and rewrite them. I'd suggest you to have an abstract Support Class and pass different support rules when they change.
I don't think it has a name but maybe check the master list at http://en.wikipedia.org/wiki/Anti-pattern knows? http://en.wikipedia.org/wiki/Hard_code probably looks the closer.
I think that your example probably doesn't have a name - whereas your proposed solution does it is called Composite.
http://www.dofactory.com/Patterns/PatternComposite.aspx
Since you don't show what the code really is for it's hard to give you a robust sulotion. Here is one that doesn't use any if clauses at all.
// invoked to map different kinds of items to different features
public void BootStrap
{
featureService.Register(typeof(MyItem), new CustomFeature());
}
// your code without any ifs.
public void ControlStuff()
{
var listOfThings = LoadThings();
foreach (var thing in listOfThings)
{
thing.InvokeFeatures();
}
}
// your object
interface IItem
{
public ICollection<IFeature> Features {get;set;}
public void InvokeFeatues()
{
foreach (var feature in Features)
feature.Invoke(this);
}
}
// a feature that can be invoked on an item
interface IFeature
{
void Invoke(IItem container);
}
// the "glue"
public class FeatureService
{
void Register(Type itemType, IFeature feature)
{
_features.Add(itemType, feature);
}
void ApplyFeatures<T>(T item) where T : IItem
{
item.Features = _features.FindFor(typof(T));
}
}
I would call it a Failure to Encapsulate. It's a made up term, but it is real and seen quite often
A lot of people forget that encasulation is not just the hiding of data withing an object, it is also the hiding of behavior within that object, or more specifically, the hiding of how the behavior of an object is implemented.
By having an external DoSomething(), which is required for the correct program operation, you create a lot of issues. You cannot reasonably use inheritence in your list of things. If you change the signature of the "thing", in this case the string, the behavior doesn't follow. You need to modify this external class to add it's behaviour (invoking DoSomething() back to the derived thing.
I would offer the "improved" solution, which is to have a list of Thing objects, with a method that implements DoSomething(), which acts as a NOOP for the things that do nothing. This localizes the behavior of the thing within itself, and the maintenance of a special matching list becomes unnecessary.
If it were one string, I might call it a "magic string". In this case, I would consider "magic string array".
I don't know if there is a 'pattern' for writing code that is not maintainable or reusable. Why can't you just give them the reason?
In order to me the best is to explain that in term of computational complexity. Draw two chart showing the number of operation required in term of count(listOfThingsThatSupportX ) and count(listOfThings ) and compare with the solution you propose.
Instead of using interfaces, you could use attributes. They would probably describe that the object should be 'tagged' as this sort of object, even if tagging it as such doesn't introduce any additional functionality. I.e. an object being described as 'Thing A' doesn't mean that all 'Thing A's have a specific interface, it's just important that they are a 'Thing A'. That seems like the job of attributes more than interfaces.

Translating one object to another via an extension method - looking for alternate solutions

This may be a bit of an odd question, and what I have in place now works, but it feels a bit strange to me and I wonder it's because of poor design/architecture. Any thoughts here would be appreciated.
The initial design is in a code base I inherited from someone else. We have a linq-to-sql class (auto generated in the dbml's designer file).
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.ARCustomers")]
public partial class ARCustomer : INotifyPropertyChanging, INotifyPropertyChanged
{
// variables
// extensibility method defs
// ctor
// properties
// etc.
}
Then another class class called ArCustomer (notice the lower case "r") that is an extended version of the auto-generated class. When I say extended, I mean it has all the properies of the LINQ class, plus a few more that requires some logic to populate.
There are a lot of places in code that we want to take an ARCustomer and turn it into an ArCustomer. So I wrote an extension method (this is what felt strange) on the ArCustomer class.
public static ArCustomer FromDatacontextObject(this ArCustomer customer, ARCustomer datacontextObject)
{
var arCustomer = new ArCustomer();
arCustomer.Id = datacontextObject.ProjectID;
// more of the same
// now populate the other fields that don't exist on the datacontextObject
return arCustomer;
}
It's called as such.
var customerfromDb = accountReceivableRepository.GetCurCustomer(arId);
ArCustomer customer = new ArCustomer();
customer = customer.FromDatacontextObject(customerfromDb);
This feels wrong to me, but I don't know of any better alternatives off the top of my head. (Would a partial class that contains the extended properties work? Populate them in it's constructor?) Or maybe it's fine... I'm interested in a few things...
Am I right in feeling that this is wrong/odd/bad?
Specifically, what are the cons to be found in the solution I've implemented? I feel like one is that I scratch my head too often trying to differentiate between the two classes and figure out which is which.
Are their any pros?
Any better solutions (and why they're better)?
(Unrelated - I hope this kind of question is OK for stack overflow. I almost feel like I'm asking for a mini code review, which can be subjective; on the other hand, I tried to ask some concrete questions and feel I must not be the only developer to have ran into a situation like this ("I have one object and need to turn it into another"), so hopefully there is something to be gained from leaving the thread open).
Thanks guys!
Your instincts serve you well.
Having two classes with the same name (differing only be case) is technically allowed by the C# compiler, but it is a bad idea. Also, it is not CLS compliant.
It is a bad idea for the exact reason that you already stated: readability. Don't underestimate the importance of readability. Personally it is my number one measure of code quality. Readable code tends to have fewer bugs, and is easier to debug/maintain.
The classes generated by LINQ to SQL are already partial classes. You can add a separate code file to define any extra parts that you want. And, this is the preferred method to accomplish what you are describing. It is easier to maintain and understand.
Alternatively, you could create a "ViewModel" class that contains the ARCustomer. (This depends on your architecture).
If you change the extension method to extend the database object you have a more natural API IMO
public static ArCustomer ToDomainObject(this ARCustomer datacontextObject)
{
var arCustomer = new ArCustomer();
arCustomer.Id = datacontextObject.ProjectID;
// more of the same
// now populate the other fields that don't exist on the datacontextObject
return arCustomer;
}
then the data access code looks like this
var customerfromDb = accountReceivableRepository.GetCurCustomer(arId);
ArCustomer customer = customerfromDb.ToDomainObject();
Few days ago I had the same problem. And I did find some discussions on this topic.
These threads might help: Thread one, Thread two
As I figured out, there is no better way to do what you are doing. However, you might try to use reflection to iterate through all the fields in parent object to copy them to relevant fields in child object. Some example code here, And discussion here.
For my problem, ended up going field by field manually, as some of the fields I needed to be deeply cloned, some had to be copied only by reference.

Why aren't all fields/properties/methods public?

I know this may sound stupid, but i really want to know :)
im learning c# currently,
and as you know you need to set "object"(button,label,text,variable, etc.) public or whatever you like.
However, you still need to write a code like this:
// my point is you cant just type label1.text you need to type class.label1.text
// so there is no chance of getting bugged
//because there is label1 in each of forms/classes
class Classlol = new class();
classlol.label1.blabla
So what's the point of making it unreachable in other forms ? why every thing isnt public or its not public by default ?
Thanks.
Simply speaking, pretty much the same reason that you wear clothes. Not everything should be exposed to the public at all times. Selected things need to be public so that others can interact with them, but other things are private and should be kept internal to that class.
Although, I probably shouldn't have used the word internal there in that last sentence, because there's a third option: the internal access modifier. The name used in VB.NET (Friend) is probably clearer. This indicates that a piece of data should be visible to all of the other classes within a single assembly, but hidden from outside. A similar analogy applies: there are things that you might share with your closest friends, but still don't want to be public.
There are other more complicated reasons, like to enable information hiding, to maximize the separation between a particular class and the rest of an application, and to maintain a consistent public interface even though implementation details may have been changed between versions, all of which contribute to good object-oriented design. If you really want to understand the nitty-gritty, I suggest picking up a good book on object-oriented programming. It's very difficult, if not impossible, to master an object-oriented language like C# without a solid understanding of the fundamentals.
Things aren't public by default because they might contain sensitive information, or at least information that you don't want to expose as part of the class's public interface. Making something public is a bigger decision with more risks than simply making it private, so you are forced to make that decision explicitly.
The point of using classes is to be able to separate your code into logically related pieces. This makes your code easier to understand and maintain.
For example, if you need to modify code in a class, you can focus more on the way that class functions and less on other parts of your project. However, public members of your class limit this separation somewhat because, if you modify a public member, that can affect other parts of your project.
Keeping as much of your class private as possible (while still usable from your application) maximizes the separation between it and the rest of your application. It makes it easier to think about only the logic in the class you are working on, and it allows you to modify those private members without having to think what other parts of your application might be affected.
I suggest that you read more about abstraction in object oriented programming. Maybe the Wikipedia article on abstraction is a good place to start.
EDIT: Konrad is absolutely right, abstraction does not automatically imply "hiding" information. You could say that it's the role of encapsulation in object oriented programming.
I guess what I wanted to say is that this question is not specific to C#, but rather begs for a bit of reading on general object oriented programming principles.
The default access modifier is internal which means it's public inside the same assembly and private outside the assembly.
If you want to expose certain data as public, for example text of some Label, the best practice is creating public readonly property like this:
public string LabelText
{
get { return MyLabel.Text; }
}
To access it you'll have to use such code:
string text = classInstance.LabelText;
This way the Label itself is not public, but its text can be read by everyone.

Should I use (otherwise optimal) class names that conflict with the .NET BCL's names?

This situation probably is not entirely uncommon to some of you: you have some functionality to put in a class but the perfect name (*) for that class is taken by one of the classes in the System namespace or other namespace/class that's not yours but you're using/importing.
(*) By perfect I mean small, concise and clear names.
For instance I have an Utils class that has a Diagnostics (mostly debug utils) class and a Drawing class. I could:
have a DrawingUtils class and a DiagnosticsUtils class, but that just smells like bad structure.
pick a thesaurus and be done with an worse, longer or awkward name that's casually still not taken.
Write class names in my native language instead of English.
Ask the smart guys at StackOverflow.
I think options 1-3 aren't promising :(
EDIT:
Since my chosen answer doesn't address the problem definitively (neither I do), what I'd recommend for people facing the same situation is to ask yourselves: Will you frequently use the conflicting BCL class/namespace? If no, then let your name conflict (as I did with Diagnostics). If yes, add a word that limits the possibilities of your class/namespace.
In practice, this means:
"Drawing": Something that draws.
"MyCustomControlDrawing": Something that draws only on MyCustomControl. e.g.: "WidgetDrawing".
EDIT2:
Another solution to take a look next time: Extension Methods (courtesy of Lawnmower).
I don't see any issue with keeping the names Drawing, Diagnostics etc. That's one of the purposes of namespaces, to resolve naming conflicts.
The beauty of namespaces is that they allow you to create classes with identical names. You can assign an alias to a namespace when you import it into your file with a using statement.
using MyAlias = My.Custom.Namespace;
this will keep your classes separate from Microsoft's.
you can then reference your classes as
MyAlias.Diagnostics
or you could alternatively assign an alias to Microsoft's namespace, but I wouldn't recommend this because it would confuse other developers.
To me, it really isn't worth the hassle of purposefully writing conflicting class names. You'll confuse other developers who aren't familiar with your codebase, because they will be expecting to use BCL classes but end up with yours instead (or vice versa). Then, you just waste their time when they have to write specific using aliases.
Honestly, coming up meaningful identifier names is a useful skill, but it isn't worth delaying your development. If you can't come up with something good quickly, settle for something mediocre and move on. There is little value in toiling over the names. I dare say there are more productive things you could be doing.
EDIT: I also don't believe that "small" is a component of a "perfect" identifier. Concise and clear, for sure, but if it takes a longer name to convey the purpose of a particular construct, so be it. We have intellisense, after all.
Use namespaces to disambiguate your classes from the classes in other namespaces. Either use fully qualified names or a using statement that tells the compile what you need:
using Type = MyReallyCoolCustomReflector.Type;
Now if you want to still use the Type class from the System namespace:
System.Type sysType = anObject.GetType();
Generally I try to avoid name duplicates but this doesn't always work out that way. I also like simple, readable and maintainable code. So as often it is a trade-off decision.
Well, if you want to avoid a namespace collision there are a couple of things you can do:
Don't collide, instead choose a unique name.
Example:
If you are creating a Math class you can name yours CamiloMartin.MathHelper
Use the long namespace to distinguish between collissions.
Example:
public class MyClass
{
public int SomeCalculation(int a, int b)
{
return MyNamespace.Math.SomeFunc(a, b);
}
}
Using an alias to differentiate.
Example:
using System.Math;
using SuperMath = MyNamespace.Math;
namespace MyNamespace
{
public class MyClass
{
public int SomeCalc(int a, int b)
{
int result = Math.abs(a);
result = SuperMath::SomeFunc(a, b);
return result;
}
}
}
Just for the record: .NET framework doesn't have neither Utils nor Diagnostics class. (But does have System.Diagnostics namespace.)
Personally I don't like general-purpose classes like Utils because their methods are not very discoverable (and usually either too general or too specific), therefore I would justify their use only as for internal classes.
As for the rest -- I agree with others on that namespaces are convenient. (Although I would thought twice to name the class if there is already a class in System with the same name, not because of name conflicts, but rather because the reason why I can't use 'original' class could mean that the class I'm about to create is semantically different.)
Often its possible to choose a more specific name. Take Utils for example. Absolutely everything can be called a utilitiy. For the reader of your code this classname is worthless.
Often utility classes are a collection of methods that didn't really fit anywhere else. Try to place them where they belong, or group them by some criteria, then use the group as a classname. Such grouping is in my experience always possible.
In general:
That's what we are doing (hey, we can refactor it later)
Used it once or twice but only on important classes. Especially useful if you don't know the 'perfect' name yet.
don't even think about this...
Using namespace aliases is no fun. So I avoid it if I can.

Are there any plans for "extension properties" in a future version of C#?

I've thought of this before and it came to mind again when reading this question.
Are there any plans for "extension properties" in a future version of C#?
It seems to me they might be pretty stright-forward to implement with a little more "compiler magic". For example, using get_ and set_ prefixes on extension method names would turn that method into an extension property:
public class Foo
{
public string Text { get; set; }
}
public static class FooExtensions
{
public static string get_Name(this Foo foo)
{
return foo.Text;
}
public static void set_Name(this Foo foo, string value)
{
foo.Text = value;
}
}
Are there any technical restrictions which would prevent this? Would this create too much stuff going on behind the scenes? Not important enough to be worth the effort?
The official site for feature requests is http://connect.microsoft.com/VisualStudio.
There has already been a request for extension properties here.
Microsoft's answer on 7/29/2008 included the following:
Extension properties are a common
request, and we actually got quite far
with a design for the next version of
the language, but ultimately had to
scrap it because of various
difficulties. It is still on our
radar.
Generally I think this would encourage poor practice.
Properties are supposed to represent some kind of state about the object in question, whereas methods should represent units of work. But many developers tend to put computationally intensive or relatively long-running code in the getters and setters where they would be much more appropriate as methods.
Extending an object is not the same as deriving from it. If you need to add properties, from a philosophical perspective you're talking about needing to add stateful information to the object. That should be done by deriving from the class.
Although I don't think what you're proposing is a good idea, you can get pretty much the same thing with the upcoming dynamic type in C# 4. Part of what is planned is to allow new properties and methods to be added at runtime to existing objects and types. One difference is that you won't have the compile-time checking of an extension property.
There might be something to be said about that kind of trick.
Just look at Attached properties in WPF. They do give tremendous power for declarative behavior attachment. But I'm not sure what that would look like outside of a declarative context...
I'm not sure how that would work. Extensions have to be static, so the property itself would have to static. The means whatever you use to back these properties would also be static. But expect your planned use for these expects them to be associated with the instances indicated by the this keyword rather than the type itself.
"Extension properties" are available today via inheritance. Adding such a beast would encourage poor oop practices and generaly be more trouble than its worth.

Categories