Learning C# - Clean coding

eg:
class Test {
  static void Main(){
    System.console.WriteLine(“Welcome to C# Training”);
  }
}


http://programmers.stackexchange.com/questions/133015/private-variable-vs-property
When setting a value to a variable inside of a class most of the time we are presented with two options:
private string myValue;
public string MyValue { get { return myValue; } set { myValue = value; } }


Is there a convention that determines how we should assign values to variables inside of our classes?
I would take it a step further, and bring it to 3 cases. Although there are variations on each, this is the rules I use the majority of the time when C# programming.
In case 2&3, always go to the Property Accessor (not the field variable). And in case 1, you are saved from even having to make this choice.
1.) Immutable property (passed in to constructor, or created at construction time). In this case, I use a field variable, with a read-only property. I choose this over a private setter, since a private setter does not guarantee immutability.
public class Abc {
private readonly int foo;
public Abc(int fooToUse){ foo = fooToUse; }
public int Foo { get{ return foo; } }
}


2.) POCO variable. A simple variable that can get/set at any public/private scope. In this case I would just use an automatic property.
public class Abc { public int Foo {get; set;} }
3.) ViewModel binding properties. For classes that support INotifyPropertyChanged, I think you need a private, backing field variable.
public class Abc : INotifyPropertyChanged {
private int foo;
public int Foo { get { return foo; } set { foo = value; OnPropertyChanged("foo"); } } }


There are a couple instances where the so-called "older" style is still required:
A: Immutable types using language-provided immutability. The readonly modifier in C# freezes that value after construction. There's no way to mimic this with automatically-implemented properties (yet).
public sealed class FooBarBazInator {
private readonly double foo;
public FooBarBazInator(double foo) { this.foo = foo; }
public double Foo { get { return this.foo; } }
}


B: Your getters/setters have any logic whatsoever. WPF and Silverlight (and similar) code that are data-bound to your classes will implement INotifyPropertyChanged like so:
public class FooBarBazInator : INotifyPropertyChanged {
private double foo;
public event PropertyChangedEventHandler PropertyChanged;
public double Foo {
get { return this.foo; }
set { this.foo = value; this.RaisePropertyChanged("Foo"); } }
private void RaisePropertyChanged(string propertyName)
{
var propertyChanged = this.PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Other than those, I'd say use the new style. Keeps your code concise and offers less surface area for bugs to creep in. Plus, if it ever needs to change to include logic, it won't be signature-incompatible.
Using C# Linq

Dirty 

List<User> matchingUsers = new List<User>();
foreach (var user in users)
{
   if (user.AccounBalance < minimumAccountBalance && user.Status == Status.Active)
   {
        matchingUsers.Add(user);
   }
}
return matchingUsers;

Clean
return users
     .Where(u => u.AccountBalance < minimumAccountBalance)
     .Where(u => u.Status == Status.Active);

Dirty 

if (fileExtension == "mp4" ||
    fileExtension == "mpg"  ||
    fileExtension == "avi")
  && (isAdmin || isActiveFile);

Clean
if (ValidFileRequest(fileExtension, active))

private bool ValidFileRequest(string fileExtension, bool isActiveFile, bool isAdmin)
{
   var validFileExtensions = new List<string>() {"mp4", "mpg", "avi"};
   bool validFileType = validFileExtensions.Contains(fileExtension);
   bool userIsAllowedToViewFile = isActiveFile || isAdmin;

   return validFileType && userIsAllowedToViewFile;
}

Nullable<T> Usage Guidelines - http://blogs.msdn.com/b/kcwalina/archive/2008/07/16/nullable.aspx


Note that C# provides special support for Nullable<T> in the form of language aliases for Nullable types, lifted operators, and the new coalescing operator.
int? x = null; //
long? d = x; // calls cast operator from Int32 to Int64
Console.WriteLine(d??10); // coalescing; prints 10 because d == null

CONSIDER using Nullable<T> to represent values that might not be present (i.e. optional values). For example, use it when returning a strongly typed record from a database with a property representing an optional table column. 
ý Do NOT use Nullable<T> unless you would use a reference type in a similar manner, taking advantage of the fact that reference type values can be null.
For example, you would not use null to represent optional parameters.
// bad design
public class Foo {
   public Foo(string name, int? id);
}

// good design
public class Foo {
   public Foo(string name, int id);
   public Foo(string name);
}

ý AVOID using Nullable<bool> to represent a general three-state value.
Nullable<bool> should only be used to represent truly optional Boolean values: true, false, and not available. If you simply want to represent three states (e.g. yes, no, cancel), consider using an enum.
ý AVOID using System.DBNull. Prefer Nullable<T> instead.

Comments

Popular posts from this blog

API design best practices

DB Connection Issues

Reading Excel Sheet on client side and processing it