jay's old blog

this blog will be deleted soon - please visit my new blog - https://thesanguinetechtrainer.com

Conversion of Types or Casting or Type Casting

When you so many types (value types, reference types) and of course built in types and so many custom types that are designed by you, as a developer, you will run into a common scenario. You need to convert one type into another. This can be called as conversion of type, or casting or type casting. Any and all of these words/phrases can be used interchangeably 


There are so many ways of converting types and lets see them one by one 


Implicit type casting is when you don’t have to do anything specific – code wise – to make the conversion happen. The compiler will take care of it on its own.  


For instance, when you do  


            int hello_there = 20; 
            double hello_there_double = hello_there; 


You are pushing an int type into a double type. It just gets done with no special intervention from you.  


Explicit type conversion is where you do the same thing explicitly.  


For instance, you do 


            double hello_there_double_explicit = (double)hello_there; 


The third way is when you do the conversion with a helper class. 

double hello_there_double_helper = Convert.ToDouble(hello_there); 


The fourth way is custom conversions that are of course, user defined, just like user defined types. That means, custom conversions are written by you, to enable a smooth conversion.  


This becomes useful when there are scenarios where you have a custom type, and you still want to encourage your custom type instances to be converted into another type. 


For instance, suppose you have a complex custom type that represents the many dimensions a water bottle such as its color, weight, height, design, capacity and so on. However, you still would like to allow some sort of a type conversion where in your water bottle instance can be casting into a int type, where in the capacity value of your water bottle is passed over.  


This would be very useful when you want to increase efficiency of your project by allowing conversions to value types. That way, in places where the entire object is not needed, you can simply use value types, obtain the necessary values via casting and consume them anyway you please, all the while reducing the memory footprint.  


The accompanying code at our repository has this example, along with all the earlier conversions.


Follow me on twitter, facebook and instagram for more updates. Thanks!

is and as

When working with type conversions, there are always ways to ensure that an incorrect type conversion does not happen. However, a try/catch is not always the best solution, especially for type conversions. That is why, in c sharp we have the 'is' and 'as' operators. 


As the wording indicates, the 'is' operator checks if a particular object type is compatible with another object type. The 'as' operator gets the converted object type, if the conversion is possible at all.  


The use case for 'is' is straight forward. You have two objects, and you want to find out if the conversion is possible. If conversion is possible, you would like to convert it, and then do stuff based on that.  


The use case for 'as' is when you feel that conversion is pretty much a guaranted and want to get a converted object right away. You could say that 'is' is good enough (since you will do a conversion later anyway) but 'as' makes you cooler because you just saved so many lines of code.  


As always, a sample is available at our code repository.  


Afterthought  


The is and as operator has strong connections to the Liskov substitution principle (which you can read more about in one of our earlier blog posts). The principle states that the base type objects can be used where the derived classes are used.  


That is essentially what the is and as operators are doing. Ideally, if you were to follow the standard design guidelines of object oriented programming, you would never have to use the 'is' and 'as' operators. Of course, the key word here is 'ideally'. Further, thanks to Generics, you can simply use a Generic type now and take care of things were you may be using different types. 



Follow me on twitter, facebook and instagram for more updates. Thanks!

SOLID

In programming, there are something called design principles. Design principles (sometimes also referred to as design guidelines) are some ideal stuff that you should be following. This is similar to life related wisdom that you receive from elders. For instance, your parents will always suggest that 20 % of your monthly income should go to your savings for a rainy day (I keep thinking...is my mom assuming that on the day I get fired or become unemployed, it will be raining?) or that you should never plan for things in a haste and stuff like that. 


That means, you can ignore these design principles and still write functional software. This is similar to another post I wrote about comments and regions.  


If you already planning to ignore general guidelines, then this post is not for you. However, if you are intrigued, read on. There is also a Wikipedia link on this, if you wish to check that out. 


SOLID has 5 components attached to it. 


  • Single responsibility  

  • Open/Closed  

  • Liskov substitution  

  • Interface segregation  

  • Dependency Inversion  

 

Okay, let's go through them, one at a time. 


Single responsibility  


This one is obvious. When you are defining a class, it should have a single purpose. This is something that extends to not just class definitions but methods, UI elements and properties and so on.  


When defining a class, you must ensure that it has a single purpose. Suppose you are writing a class that is supposed to represent students (in a college). Although, the subjects that the student study as part of their college semester is tightly coupled with their everyday life, it is not recommended that you include elements of subjects into the student class.  


Rather, you will design a separate class for subjects. Same goes to designing a class for faculty. You won't club both faculty and students into the same class definition.  


Why does this principle matter? Well, among other things, repairing things becomes tough when you use 'multi purpose' classes. Always remember that as you develop your project, you will realize that some class definitions will have to be modified, replaced or deleted altogether. If your class has multiple purposes, then you cannot do any of this because the class (and hence its objects) are being used at multiple locations. If tomorrow you design a better class definition, you simply cannot delete the existing class because it is being used in other places where your 'better' class definition wont work.  


It's like, for some reason, your smartphone and your laptop are both held together with a tight cord and they have the same battery! That means, wherever you take your smartphone, you have to take your laptop. Wherever you take your laptop, you have to lug your smartphone. If the battery dies for some reason (old age, dropped in the toilet, drove your two wheeler in the rain, somebody sat on it and ignored a lifetime of advice about going to gym) both your phone and laptop are rendered useless. 

On the other side of the park, if your classes are single purpose, replacing them becomes easy. If you were to change something, that impacts only that 'portion' of the project that are supposed to be 'impacted' by the change.  


Open/Closed  


The expansion of this is that an object (hence its definition) should be closed for modifications but open for extension. This means, the classes that you define should allow (in fact, encourage) additions to be made to them, to give them added functionality and properties. However, the base class itself should not be tampered with or should not be allowed to tampered with.  


An everyday example of open/closed principle would be our very own smartphones. Once you buy your phone, you are allowed to expand it functionality by installing apps to it. For instance, you could installing a mapping app and now the smartphone is also your navigator. However, the navigator functionality is in addition the phone call functionality that comes bundled with the phone.  

Tomorrow, if you choose to, you can remove the map app from your phone but that does not take away the phone call functionality out of your phone. So, your phone is 'open' enough to be given additional capabilities but 'closed' enough that you cannot prevent it from doing its core work. 


Liskov substitution  


To me, perhaps this is the most important principle and also the one that is hardest to implement. This must tell you that you should master this if you are thinking of anything more than a good developer. 


Liskov (that is such a cool name...Mr. Liskov, your massage table is ready now...it simply has a nice ring to it) substitution states that when you are deep in super deep inheritance and stuff, you should be able to replace the base types with any of its subtypes without affecting functionality 


As with most other principles, this is plain common sense but somehow difficult for a lot of developers to follow. Here is an everyday example.  


Suppose you have a bicycle (that thing that your mom probably bought for you when your were like short and young and everybody you were useless...just kidding). Later, you modify the bicycle to work with an engine so that you can power it with fuel (petrol or gas or diesel).  


At this point, two things can happen.  


  • You remove the pedals. - If you decided that, okay, now that you have engine, you no longer need the pedals. This is well and good because your vehicle is powered by fuel and it runs when there is fuel. However, the problem is, this new 'vehicle' was based or derived from the bicycle. The moment you removed the pedals, you broke the Liskov principle. You can no longer call your new vehicle a derived class of bicycle because a new 'property' that you have added (requirement of fuel and removal of pedals) has made it impossible to use your new vehicle as a bicycle (one that runs without fuel). 

  • You keep the pedals. When you keep the pedals, then the Liskov principle is respected. Your new vehicle will keep running as long as its provided with fuel. Now, suppose the vehicle runs out of fuel. You can still continue using your new vehicle, by pedaling as you would a bicycle.  


Interface segregation  


Every class would need interfaces with which outside members can access its many methods and fields and properties. This principle states that (similar to the first principle of single responsibility) the interfaces that are used must be tailored to individual clients.  


An everyday example would be a wireless mouse. A wireless mouse connects to a PC or tablet or even a smartphone through Bluetooth technology. That is how it interfaces. However, what if you decide to make a wireless mouse have a wired connection as well? Sure, this may become useful in the rare scenario when a particular PC does not have the necessary Bluetooth connectivity but the real question is, is it worth the trouble?  


Similarly, when you are designing interfaces and you are working with multiple clients, tailor each interface to a specific client instead of building one interface that works with all the clients.  


Dependency Inversion  


This is of course, an advance topic and principle. I will explain in my own words and if you are just starting with learning programming, you may skip it. 


For those who dare to take the road less taken (or never taken in my case) read on. 


The way object oriented development works, it's like a collection of components, connected with nuts and bolts, working together. One thing depends on another, and another thing depends on another and so on.  

Here is what my mentor (and friend and super awesome guy) has to say about this. 


'Dependency inversion is meant for decoupling. It does it so by implementing common abstractions for both higher level code and lower level code, where the higher level uses the lower level for its implementation. In dependency inversion neither the high or low level component has a direct knowledge of each other. It is achieved through interfaces and abstract classes. It also means by definition that created abstractions should not depend of details, but rather the details depend on abstraction. In the very most simplistic case it means that higher level module needs some functionality. It will then use that functionality through some defined interface. And on the low level side the interface is being implemented by some low level class. Then during runtime the components are hooked together e.g. using dependency injection.' 


As you can see, it is a lot of high level stuff. To simply it, csharp provides for something called interfaces and abstract classes. Unlike regular classes, interfaces and abstract classes don’t contain actual definitions. It is up to the derived class to implement the interfaces and abstract classes, therefore following an established pattern.  


What does this all mean? It means, when building software, it is best to depend on interfaces and abstractions instead of definitions. 


I will admit that the 5th principle (and the topics of dependency inversion and dependency injection) is a tough cookie and you will understand it as you grow as a developer.



Follow me on twitter, facebook and instagram for more updates. Thanks!

Enums

In this post, I will be talking about enums (or enumerations).  


Enums are values that are given names, and you can use those names to access those values. That sentence might be a bit confusing but perhaps an example would help.  


Suppose, you are working on a project where you are looking to use certain values to represent certain real life things. For instance, the project is about managing devices that are handed out to students at a college. Here are some of the items that are handed out. 

  • Laptop 

  • Tablet 

  • Smartphone 

  • Calculator 

  • Mobile hotspots 


Now, you can represent each of them with a variable (to which you assign some value), and when performing operations, you may use these values. 


For instance, you could do something like this. 


Int laptop = 2; 

Int device_given_to_student = 2; 

If(laptop == device_given_to_student) 

{ 

//show output that says that the student has been given a laptop. 

} 


Now, this is okay and it works fine. However, any number of things could go wrong here. What if, at some point during runtime, the variable laptop is accidentally assigned 3. That would completely mess up the entire system. Not only that, you will have to define a new class (and hence declare/instantiate objects which means more memory consumption) and do everything that is associated with using new classes.  


An alternative would be to use enums. Thanks to enums, you can have something like this. 


enum devices 

{ 

Laptop, 

Tablet, 

Smartphone, 

Calculator, 

Mobile hotspots 

} 


Thanks to the magic of c sharp, each of these devices will be assigned a value starting with 0, with increments of 1. That means, laptop automatically has a value of 0, and table 1, smartphone 2, calculator 3 and mobile hotspots 4. This has already saved you a lot of time.  


Further, there is no way the values of these individual items will be altered midway. Any alteration will have to be done right there at the enum definition.  


In addition to that, this is a value type and that means, it is treated as such.  


Check out the following code on our github repository to see enums in action. As always, the code is heavily commented so that you know what is going on. 


Follow me on twitter, facebook and instagram for more updates. Thanks!

Nullables and Generic Types

When discussing types, we touched upon the concept of nullables. Some types are nullable while others are not. Nullable type means, such a type can have a 'null' value and if a type is not nullable, it must have a non-null value assigned to it. A simple approximation is that value types cannot have null values where as reference types can have null values.  


This is all well and good.  


However, what if there is a certain scenario where a given value type has to become null. For instance, suppose your project is using a variable called 'no_of_students' and you don’t know yet, how many students are going to be there. You would prefer it, if this particular type instance had a value of 'null' to indicate 'unknown' rather than '0' which means 'zero students showed up'.  

When you have such scenarios, you can use the Nullable option to indicate that a particular value type can have a value of null.  


Another concept that plays well with nullables are generics. Of course, this in no way means that you will be using nullables and generics together.  


Now, how does generics or generic types work? Put it simply, instead of using specific types in your project or class or method, you use generic types.  


Check the attached code to see this in action.



Follow me on twitter, facebook and instagram for more updates. Thanks!

Why we are going with bitbucket and not github

Think code repositories, immediately you will think of github. In fact, until very recently I simply assumed version control equals github (although I have been familiar with visual studio online services for years) and ended my understanding at the point.  


Then, I looked at my own students at study nildana. Many of them gearing up to starting committing their own code as they are now about to start working as developers. I feared that, since github does not allow private repositories, I will have to end up shelling out money for that as well. That is when I ran into bitbucket and its free offering.  


Bitbucket allows unlimited private and public repositories for up to 5 users. I think that is a reasonable provision. As a developer, I know that there is no such thing as a free lunch but then again, a lot of work in the world of software gets done at a low cost (Linux, for example). So, as much as I am a big fan of github (I get a lot of stuff from their repositories) I am afraid, I will have to use bitbucket's offerings for now.  


I don’t envision my team to grow beyond 5 members, at least till the end of this year. So, I can start off by using the free service. In addition to this, I noticed that the paid service is a reasonable offer as well. 10 dollars (approximately 700 rupees) per month is reasonable for 25 users. Another thing which impressed me was the ability to ge the bitbucket server itself (so I can host it on my own) for a cool 10 dollars (approximately 700 rupees)  for 10 users.  


Overall, for current and future requirements, bitbucket simply seems to have an incredible offering and I am going to have to say goodbye to github for now.



Follow me on twitter, facebook and instagram for more updates. Thanks!

Boxing and Unboxing

There will always be a time when you want to keep some of value types as they are (get to use them as value types) but treat them as reference types. The most important distinction here is, value types are stored in the stack memory while reference types go and take lodging at the heap memory. Perhaps, you feel that you have way too many value types and you want to push them off stack memory and into the heap memory.  


When you want to do something like this, you box and unbox your value types. As the name entails, you put your existing value type variable and 'box' it into an object type variable. Later, when you want to consume that value type that is currently inside the 'box', you will then go ahead and 'unbox' it.  


Unlike so many other things that the c sharp compiler does for you, one thing it does not do is check if you are 'unboxing' properly. It is entirely up to you to unbox the object into its proper value type. If you do a mistake, then the compiler will never warn but you will get a runtime error. 


Another point to add is that, thanks to the availability of generic types (which is discussed here), you may not even opt to use boxing/unboxing. You could simply choose to represent your value types as a generic type which will give you reference type behavior with object type memory storage.  


Eventually, you choose where this goes.  


As always find sample project for this at our code repository.


Follow me on twitter, facebook and instagram for more updates. Thanks!
Follow me on twitter, facebook and instagram for more updates. Thanks!

Method Overloading

Now that you are writing methods (and by extension giving behavior to the types you are definingit's time you learnt about overloading of method. Of course please remember that method also means functions, this topic is same as overloading of functions or function overloading. 


Overloading is a concept where two or more methods have the same name. The compiler (and you) are able to differentiate between these methods based on the differences that crop up in the parameters -  both the number of parameters and type of these parameters, and the sequence/arrangement of these parameters in terms of type uniqueness. 


The attached code example Method_Overloading will show you how this works.  


Now, before you jump head first (like tomb raider) into the overloading code, perhaps a few minutes to understanding the significance of overloading. I can be honest, and in my earlier days of coding, I used to think, this whole overloading concept was a headache. To continue further down the road of confessions, I actually thought object oriented programming itself was needlessly complicated. This was back in the early 2000s when C programming was all the rage and everybody was like 'dude, you should learn C man' and all that.  


So, returning to Overloading, I think it’s a pretty neat concept. That's because, even a particular context, some factors can change leading to different reactions. For instance, think of a smartphone. When you are making a phone call, it’s a phone. However, when you are out enjoying with friends, it can take photos by acting like a camera. When you are bored, you can play a multiplayer game and suddenly it’s a console.  


In all these scenarios, the context (using the phone) is constant. However, because the input (or shall I say parameters) changed, the same device (or shall I say method) was able to act out differently. However, the core behavior remains the same.  


Here is a programmatic example. Suppose you want to add two numbers. You could write four different addition methods, each of them with a different type as a parameter. When you call these four methods, you know that the name is the same (lending you immense convenience) and also choose which type of parameter to send. In this 4 case, there were 4 'different' scenarios. What if there are a hundred scenarios? If so, you still have the luxury of using the same, well thought out and useful name while implement hundred different scenarios.  


However, do understand that you cannot overload for the sake of overloading. If you find two methods which are not falling under the same context (for example, you are building a calculator and you want overload the addition and subtraction methods), you are using it wrong. As with most things, overloading is one of those things you get with practice.



Follow me on twitter, facebook and instagram for more updates. Thanks!

Extending Types – Overriding and Extension methods

The entire basis for an object oriented language such as c sharp is that you can extend. Two quick ways you can do this are via overriding (methods) and extension (methods). 


When you use extension methods, you are essentially adding methods outside the actual class definition, but still making it available to all instances of the object. I cannot think of too many scenarios where you may do this. Mostly because, if I want a class to have an extra method, I could simply add it to the original class definition or I could have a derived class that contains the base class stuff anyway. 


However, let's says I wish to make a quick addition to a class definition, without having to update the original class definition, I could use the extension method to do the same.  


As always, find attached code at our code repository to see how it works. 


Overriding methods is pretty straightforward. You have already read about how methods can be overloaded. In this case, you simply derive a class and then override the methods you wish to override. Of course, there may times when you don’t want a method or the class (which contains said method) to be overriden. If so, you can 'seal' a method or the entire class with the 'sealed' keyword. 


As always, code available in our repository


Follow me on twitter, facebook and instagram for more updates. Thanks!

Class and essential components

If you read all of our posts till now, you have some idea about types, methods and other stuff. These are all the building blocks. Now, it's time to put them to good use.  


In a standard class definition (which acts like a template or blueprint) using which you will create or instantiate objects, you will find the following. 


Constructor 


Constructor is a special type of method that gets called when you create a new object. Since it is a method, you can do everything you can do with methods like sending parameters. However, a constructor will always return a reference to the object that was just created, so you cannot control that.  


Unlike a regular method, you cannot give your name to the constructor. A constructor will always have the same name as the class.   


Fields 


There are any number of ways to use variables (those that hold data) in your class. At this point, you will be using fields which are one way of referring to variables or objects you will use in your class.  


Fields can be private or public and there are other 'access specifiers' that are available.  


Methods 


These are functions that you will be writing to do a lot of stuff. You write methods to do work for you. You use methods to access private fields (and it is always recommended that fields are made private). You can write methods to call methods that have been made private. Essentially, you can use methods to do anything and everything.  


Find the code for classes at our repository. 



Follow me on twitter, facebook and instagram for more updates. Thanks!