Mutable and Immutable Value Type and Reference Type

Point 1:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestingStructImmutability
{
class Program
{
static void Main(string[] args)
{
var emplyee = new Employee();
emplyee.Name = “Anas”;
emplyee.Age = 6;

var emplyee1 = emplyee;
emplyee1.Name = “Alavudeen”;
emplyee1.Age = 30;

//OR

var emplyeeChanged = ChangeEmployeeValue(emplyee);

//emplyee value will not be changed, while emplyee1 is being changed.
//If Employee struct is a class, then the emplyee value will be changed, while emplyee1 is being changed.
//This happens because p1 is a value type, not because it is immutable. both struct and class can be mutable and immutable.
Console.ReadKey();
}

private static Employee ChangeEmployeeValue(Employee emplyee1)
{
emplyee1.Name = “Alavudeen”;
emplyee1.Age = 30;
return emplyee1;
}
}

struct Employee
{
public string Name { get; set; }
public int Age { get; set; }
}

Point 2:

//Mutable Value type:

public struct MutableValueType
{
public int MyInt { get; set; }
}

 

//Immutable Value type: As everytime object have to be created to create/modify new int value.

public struct ImmutableValueType
{
private readonly int myInt;
public ImmutableValueType(int i) { this.myInt = i; }

public int MyInt { get { return this.myInt; } }
}
}

//Immutable Reference type

class ImmutableType
{
    public string Test
    {
        get; // No Set at all, not even a private set.
    }

    public ImmutableType(string test)
    {
        Test = test; // The compiler understands this and initializes the backing field
    }
}

public string Test
{
    get;
    private set;  // Not immutable, since this is still mutable from within the class
}

Point 3:

Strings aren’t value types since they can be huge, and need to be stored on the heap.  Thats the reason it is implemented as reference type. Value types are (in all implementations of the CLR as of yet) stored on the stack. Stack allocating strings would break all sorts of things: the stack is only 1MB, you’d have to box each string, incurring a copy penalty, you couldn’t intern strings, and memory usage would balloon, etc…

The distinction between reference types and value types are basically a performance tradeoff in the design of the language. Reference types have some overhead on construction and destruction and garbage collection, because they are created on the heap. Value types on the other hand have overhead on method calls (if the data size is larger than a pointer), because the whole object is copied rather than just a pointer. Because strings can be (and typically are) much larger than the size of a pointer, they are designed as reference types. Also, as Servy pointed out, the size of a value type must be known at compile time, which is not always the case for strings.

The question of mutability is a separate issue. Both reference types and value types can be either mutable or immutable. Value types are typically immutable though, since the semantics for mutable value types can be confusing.

Reference types are generally mutable, but can be designed as immutable if it makes sense. Strings are defined as immutable because it makes certain optimizations possible. For example, if the same string literal occurs multiple times in the same program (which is quite common), the compiler can reuse the same object.

So why is “==” overloaded to compare strings by text? Because it is the most useful semantics. If two strings are equal by text, they may or may not be the same object reference due to the optimizations. So comparing references are pretty useless, while comparing text are almost always what you want.

Speaking more generally, Strings has what is termed value semantics. This is a more general concept than value types, which is a C# specific implementation detail. Value types have value semantics, but reference types may also have value semantics. When a type have value semantics, you can’t really tell if the underlying implementation is a reference type or value type, so you can consider that an implementation detail.

 

 

 

Honor the Contract

Insist on the Abstraction
All of the code in an abstract superclass should apply to every class that inherits it. Superclasses should not contain code that applies to some, but not all, subclasses. This restriction also applies to modules: the code in a module must apply to all who use it.

Faulty abstractions cause inheriting objects to contain incorrect behavior; attempts to work around this erroneous behavior will cause your code to decay. When interacting
with these awkward objects, programmers are forced to know their quirks and into
dependencies that are better avoided.

Subclasses that override a method to raise an exception like “does not implement” are a symptom of this problem. While it is true that expediency pays for all and that it is sometimes most cost effective to arrange code in just this way, you should be reluctant
to do so. When subclasses override a method to declare that they do not do that thing they come perilously close to declaring that they are not that thing. Nothing good can come of this.

If you cannot correctly identify the abstraction there may not be one, and if no common abstraction exists then inheritance is not the solution to your design problem.

Subclasses agree to a contract; they promise to be substitutable for their superclasses.
Substitutability is possible only when objects behave as expected and subclasses are
expected to conform to their superclass’s interface. They must respond to every message
in that interface, taking the same kinds of inputs and returning the same kinds of
outputs. They are not permitted to do anything that forces others to check their type
in order to know how to treat them or what to expect of them.

Where superclasses place restrictions on input arguments and return values, subclasses
can indulge in a slight bit of freedom without violating their contract. Subclasses may accept input parameters that have broader restrictions and may return results that have narrower restrictions, all while remaining perfectly substitutable for their superclasses.

Subclasses that fail to honor their contract are difficult to use. They’re “special” and cannot be freely substituted for their superclasses. These subclasses are declaring that they are not really a kind-of their superclass and cast doubt on the correctness of the entire hierarchy.

Liskov Substitution Principle (LSP)

When you honor the contract, you are following the Liskov Substitution Principle, which is named for its creator, Barbara Liskov, and supplies the “L” in the SOLID design principles.

Her principle states:

Let q(x) be a property provable about objects x of type T. Then q(y) should be true for objects y of type S where S is a subtype of T. Mathematicians will instantly comprehend this statement; everyone else should understand it to say that in order for a type system to be sane, subtypes must be substitutable for their supertypes.

Following this principle creates applications where a subclass can be used anywhere its superclass would do, and where objects that include modules can be trusted to interchangeably play the module’s role.

Content from : Practical Object-Oriented Design in Ruby – Written by Sandi Metz.

Revealing Objects

The purpose of object-oriented design is to reduce the cost of change. Messages are should be at the design center of the application.

Object-oriented applications are defined by the messages that pass between objects. This message passing takes place along “public” interfaces; well-defined public interfaces consist of stable methods that expose the responsibilities of their underlying classes and provide maximal benefit at minimal cost.

Focusing on messages reveals objects that might otherwise be overlooked i.e, Nouns in requirements should not reveal Objects. When messages are trusting and ask for what the sender wants instead of telling the receiver how to behave, objects naturally evolve public interfaces that are flexible and reusable in novel and unexpected ways.

Content from : Practical Object-Oriented Design in Ruby – Written by Sandi Metz.

Never Forget an Idea Again with the Feynman Technique

Richard Feynman was a Nobel-prize winning physicist. He tells a story of going into the mathematics department and challenging anyone there to explain to him any idea, no matter how difficult or complicated, and as long as they used simple terminology (no complicated words or terms he didn’t understand), he would reach the same conclusions that they did. This story is often brought up to show what a great genius Richard Feynman was.  But in reality, anyone can do this technique, and I’m going to show you how.

You can use the Feynman Technique to:

  1. Understand ideas that you don’t really “get”.
  2. To remember ideas that you can understand, but forget on tests.
  3. As a really efficient way of studying before an exam. Many students spend hours in the library to lousy results. You can use this technique to deeply understand an idea in 20 minutes that will stick with you for years.

Let’s walk through the Feynman technique, so you can use it in your own studies to learn better.

Step One: Choose Your Concept

The first step is to choose the concept you want to understand. Take a blank piece of paper and write the name of that concept at the top of the page.

Step Two: Pretend You’re Teaching the Idea to a New Student

The second step is to write out an explanation, as if you were teaching it to someone who didn’t understand the subject. This is crucial because in explaining to yourself the ideas you already understand, as well as the ones you don’t, you gain a better understanding and pinpoint exactly the details you don’t understand.

Step Three: Whenever You Get Stuck, Go Back to the Book

Whenever you get stuck, go back to the reference materials, lectures or a teacher  assistant and re-read or re-learn the material until you do get it enough that you can  explain it on the paper.

Step Four: Simplify and Create Analogies

Wherever you create a wordy or confusing explanation, try to either simplify the language, or create an analogy to understand it better.

You’ll notice I did both of these in this quick demonstration. I simplified the language of torque, to explain it in terms of twisting. Second, I was able to describe it through analogy, by taking the torque vector and describing it as a corkscrew motion, tightening with right or loosening with left.

You can use this technique for understanding mathematical or technical classes, carefully walking through the steps and explaining it to yourself.

But you can also use this technique in non-technical classes to understand big ideas, or even to put together a large amount of facts in the same place, so you can understand them in context.

How can you use this technique?

If you’re trying to understand an idea, you can walk through this technique very slowly to pinpoint exactly what you don’t understand, so you can go to the textbook, lecture notes or a teacher and figure out exactly what detail you’re missing. If you’re trying to remember an idea for a test, you can focus on creating better analogies or simplify the words even more to understand it more vividly.

Finally, if you want to use this technique to study for tests, go through the technique without looking at your reference materials. That’s a really good way to self-test, to see if you understand the ideas deeply. Because if you can go through and explain the material, without looking back at your textbook, that means you really understand the ideas.

Go use this technique right now Take out a blank piece of paper and go through the technique on an idea you’re currently learning. It will only take twenty minutes, but if you get in the habit, it is an excellent way to learn ideas better.

scotthyoung

What Is Refactoring?

Refactoring is the process of changing a software system in such a way that it does not alter the
external behavior of the code yet improves its internal structure. It is a disciplined way to clean up
code that minimizes the chances of introducing bugs. In essence when you refactor you are
improving the design of the code after it has been written.

“Improving the design after it has been written.” That’s an odd turn of phrase. In our current
understanding of software development we believe that we design and then we code. A good
design comes first, and the coding comes second. Over time the code will be modified, and the
integrity of the system, its structure according to that design, gradually fades. The code slowly
sinks from engineering to hacking.

Refactoring is the opposite of this practice. With refactoring you can take a bad design, chaos
even, and rework it into well-designed code. Each step is simple, even simplistic. You move a
field from one class to another, pull some code out of a method to make into its own method, and
push some code up or down a hierarchy. Yet the cumulative effect of these small changes can
radically improve the design. It is the exact reverse of the normal notion of software decay.

With refactoring you find the balance of work changes. You find that design, rather than occurring all up front, occurs continuously during development. You learn from building the system how to improve the design. The resulting interaction leads to a program with a design that stays good as development continues.

 – By Martin Fowler

Different type of methods in Javascript

Object Creation:

Unlike most other object-oriented languages, JavaScript doesn’t actually have a concept of classes. In most other object-oriented languages you would instantiate an instance of a particular class, but that is not the case in JavaScript. In JavaScript, objects can create new objects, and objects can inherit from other objects. This whole concept is called prototypal inheritance and will be discussed more later in the “Public Methods” section. Fundamentally, though, there still needs to be a way to create a new object, no matter what type of object scheme JavaScript uses. JavaScript makes it so that any function can also be instantiated as an object. In reality, it sounds a lot more confusing than it is. It’s a lot like having a piece of dough (which is a raw object) that is molded using a cookie cutter (which is an object constructor, using an object’s prototype).

// A simple function which takes a name and saves it to the current context
function User( name ) {
this.name = name;
}

// Create a new instance of that function, with the specified name
var me = new User( “My Name” );

// We can see that its name has been set as a property of itself
alert( me.name == “My Name” );

// And that it is an instance of the User object
alert( me.constructor == User );

// Now, since User() is just a function, what happens
// when we treat it as such?
User( “Test” );

// Since its ‘this’ context wasn’t set, it defaults to the global ‘window’
// object, meaning that window.name is equal to the name provided
alert( window.name == “Test” );

The above listing shows the use of the constructor property. This property exists on every object and will always point back to the function that created it. This way, you should be able to effectively duplicate the object, creating a new one of the same base class but not with the same properties.

An Example of Using the Constructor Property

// Create a new, simple, User object
function User() {}

// Create a new User object
var me = new User();

// Also creates a new User object (from the constructor reference of the first)
var you = new me.constructor();

// We can see that the constructors are, in fact, the same
alert( me.constructor == you.constructor );

Now that we know how to create simple objects, it’s time to add on what makes objects so useful: contextual methods and properties.

Public Methods:

Public methods are completely accessible by the end user within the context of the object. To achieve these public methods, which are available on every instance of a particular object, you need to learn about a property called prototype, which simply contains an object that will act as a base reference for all new copies of its parent object. Essentially, any property of the prototype
will be available on every instance of that object. This creation/reference process gives us a cheap version of inheritance.

Since an object prototype is just an object, you can attach new properties to them, just like any other object. Attaching new properties to a prototype will make them a part of every object instantiated from the original prototype, effectively making all the properties public
(and accessible by all). Example of an Object with Methods Attached Via the Prototype Object.

// Create a new User constructor
function User( name, age ){
this.name = name;
this.age = age;
}
// Add a new function to the object prototype
User.prototype.getName = function(){
return this.name;
};

// And add another function to the prototype
// Notice that the context is going to be within the instantiated object
User.prototype.getAge = function(){
return this.age;
};

// Instantiate a new User object
var user = new User( “Bob”, 44 );

// We can see that the two methods we attached are with the
// object, with proper contexts
alert( user.getName() == “Bob” );
alert( user.getAge() == 44 );

Simple constructors and simple manipulation of the prototype object is as far as most JavaScript developers get when building new applications. In the rest of this section I’m going to explain a couple other techniques that you can use to get the most out of your object oriented code.

Private Methods:

Private methods and variables are only accessible to other private methods, private variables, and privileged methods (discussed in the next section). This is a way to define code that will only be accessible within the object itself, and not outside of it. This technique is based on the work of Douglas Crockford, whose web site provides numerous documents detailing how object-oriented JavaScript works and how it should be used:

• List of JavaScript articles: http://javascript.crockford.com/
• “Private Members in JavaScript” article: http://javascript.crockford.com/private.html

Let’s now look at an example of how a private method could be used within an application,
as shown in below listing. 

Example of a Private Method Only Usable by the Constructor Function.

// An Object constructor that represents a classroom

function Classroom( students, teacher ) {
   // A private method used for display first student
   function disp() {
   alert(‘Classroom created’);
   }
   // Store the class data as public object properties
   this.students = students;
   this.teacher = teacher;
   // Call the private method to display the message at the time of object creation
   disp();
}

// Create a new classroom object
var class = new Classroom( [ “John”, “Bob” ], “Mr. Smith” );

// Fails, as disp is not a public property of the object
class.disp();

While simple, private methods and variables are important for keeping your code free of collisions while allowing greater control over what your users are able to see and use. Next, we’re going to take a look at privileged methods, which are a combination of private and public methods that you can use in your objects.

Privileged Methods:

Privileged methods is a term coined by Douglas Crockford to refer to methods that are able to view and manipulate private variables (within an object) while still being accessible to users as a public method. Below listing shows an example of using privileged methods.

Example of Using Privileged Methods

// Create a new User object constructor
function User( name, age ) {
    // Attempt to figure out the year that the user was born
    var year = (new Date()).getFullYear() – age;
    // Create a new Privileged method that has access to
    // the year variable, but is still publically available
    this.getYearBorn = function(){
    return year;
    };
}
// Create a new instance of the user object
var user = new User( “Bob”, 44 );

// Verify that the year returned is correct
alert( user.getYearBorn() == 1962 );

// And notice that we’re not able to access the private year
// property of the object
alert( user.year == null );

In essence, privileged methods are dynamically generated methods, because they’re added to the object at runtime, rather than when the code is first compiled. While this technique is computationally more expensive than binding a simple method to the object prototype, it is also much more powerful and flexible. 

Static Methods :

The premise behind static methods is virtually identical to that of any other normal function. The primary difference, however, is that the functions exist as static properties of an object. As a property, they are not accessible within the context of an instance of that object; they are only available in the same context as the main object itself. For those familiar with traditional classlike inheritance, this is sort of like a static class method. In reality, the only advantage to writing code this way is to keep object namespaces clean. Below listing shows an example of a static method attached to an object.

A Simple Example of a Static Method

// A static method attached to the User object
User.cloneUser = function( user ) {
   // Create, and return, a new user
   return new User(
   // that is a clone of the other user object
   user.getName(),
   user.getAge()
   );
};
Static methods are the first methods that we’ve encountered whose purpose is purely organizationally related. A fundamental aspect of developing professional quality JavaScript is its ability to quickly, and quietly, interface with other pieces of code, while still being understandably accessible.

Content impressed from Pro JavaScript Techniques– John Resig

JQuery and CDN

jQuery is simply a bunch of JavaScript programming in an external JavaScript file. Like any external JavaScript file, you need to link it to your web page. However, because jQuery is so popular,you have a few choices when it comes to adding it to a web page: You can either use a version hosted at Google, Microsoft, or jQuery.com, or you can download the jQuery file to your own computer and add it to your website.

The first method uses a CDN or content distribution network—that is, another website hosts the jQuery file and sends it out to anyone who requests it. There are a couple of benefits to this approach: First, you can save your web server a few milliseconds by letting Google, Microsoft, or jQuery handle distributing the file to your site’s visitors.

In addition, CDNs have the added benefit of having servers located around the globe. So if someone in Singapore, for example, visits your site, he’ll receive the jQuery file from a server that’s probably a lot closer to him than your web server, which means he’ll get the file faster and your site will appear to run more quickly.

Lastly, and most importantly, because other designers use these CDNs as well, there’s a pretty good chance that someone visiting your site already has the jQuery file saved in their browser’s cache. Since he’s already downloaded the jQuery file from Google while visiting another site, he doesn’t need to download it again when visiting your site, resulting in a substantial speed increase.

There are a couple of downsides to using a CDN: First, visitors need to be connected to the Internet for this method to work. That becomes an issue if you need to make sure your site works offline, for example, in a kiosk at a museum or during a programming
demonstration in a classroom. In that case, you need to download the jQuery file from jQuery.com and add it to your website.

Adding your own jQuery file also ensures that your website will continue to work if the CDN servers go down. (Of course, if Google’s servers ever go down, then there may be bigger problems in the world than whether your website works.) Linking to the jQuery file on a CDN server Microsoft, jQuery, and Google all let you include the jQuery file on one of your web pages using their servers. For example, to link to version 1.6.3 of jQuery using Microsoft’s CDN, you would add this line of code in the <head> of your web page (just before the closing </head> tag), like this: 

<script src=”http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.3.min

.js”></script>

Using the jQuery CDN, you’d use this code:
<script src=”http://code.jquery.com/jquery-1.6.3.min

.js”></script>

And the code using Google’s CDN looks like this:

<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min

.js”></script>

You only need to use one of these lines on your page, based on the CDN you prefer
to use. The Google CDN seems to be the most popular, so if you’re unsure of which
to use, use the Google servers.

 

Content impressed from JavaScript & jQuery – David Sawyer McFarland