You Don’t Know Java Script- Up and Going Part 1

Comparison Operators

if I ask you what is result of the following ?

var a = [‘a’ ,’b’, ‘c’];
var b = [‘a’ ,’b’,’c’];
a == b

most probably you would say true right ? But that’s not the case here, the answer is false
let us examine why

when you are using == or === operators for comparing non primitive types, i.e functions or objects including arrays, they will simply check whether the references match, not anything about underlying values.

for example in case of arrays , while comparing , all array values are by default coerced in to strings by joining all values with commas( , ) in between.  consider below example now

var a = [1 ,2 ,3];
var b = [1 ,2 , 3];
var c = “1,2,3”;
a == c;  // will return true

Inequality and Coercion

var a = 41;
var b = “42”;
var c = “43”;
a < b;   // true;
a < c;   // true;

In case of above inequality comparison,

  • when comparing two string values , the comparison is made lexicographic-ally i.e the case with a < b
  • where  as, if any one of the both is not a string then both values are coerced with numbers.

So what will be the result of comparing a Number and a String if both are coerced in to numbers?

var a = 42;
var b = “foo”;
a > b;  //false
a < b;  // false
a == b;  //false

So now what do you think coercion of  “foo” will be ?
its “Invalid Number Value” NAN

And the specification says NAN is neither greater nor less than any other value hence the result is false for the above.

 

 

 

 

 

 

 

Advertisements

Meaningful Names

Names are everywhere in the software. We name our variables, functions, arguments,classes and namespaces. We name our source files and the directories that contain them.So Basically we Name and Name and Name. Because we do so much of it . We’d better do it well. Let is see simple rules for creating good names.

Use Intent Revealing Names

Choosing names takes time but it saves more than it takes. So take care while naming and do change them when you find better ones.Every one who reads your code will be happier(including you) if you do so.This is what you need to think while naming – The name of a variable , function , or a class , should tell you why it exists, what it does, and how it is used.

If a name requires a comment then it does not reveal its content. in the below variable ‘b’ reveals nothing . we should choose a name such that it should specify what is being measured and unit of measurement

int d; //ellapsed time in days
int elapsedTimeInDays;
int daysSinceCreation;
int daysSinceModification;
int fileAgeInDays;

If you follow this your life will become happy. consider if I ask you what the below code does
       public List<int[]> getThem()
        {
            List<int[]> list1 = new List<int[]>();
            foreach(var x in theList)
            {
                if(x[0] == 4)
                {
                    list1.Add(x);
                }
            }
            return list1;
        }
Why do you think its hard to tell what the above code does. 
its not at all complex its just plain 4 lines of code. 
Here the problem is not about the simplicity of the code, but its about the imlicity , meaning, 
the degree to which the context is not explicit in the code itself. with the above code its hard to answer 
the below questions
  1. What kind of things are in theList ?
  2. What is the significance of zeroth subscript of an item in theList?
  3. What is the significance of value 4?
  4. How should I use the list being returned?

I am sure with looking the larger context of the program its very hard to answer the above questions. Now consider the below code after reformatting the above code

public List<int[]> getFlaggedCells()
        {
            List<int[]> flaggedCells = new List<int[]>();
            var STATUS_VALUE = 0;
            var FLAGGED = 4;
            foreach (int[] cell in gameBoard)
            {
                if(cell[STATUS_VALUE] == FLAGGED)
                {
                    flaggedCells.Add(cell);
                }
            }
            return flaggedCells;
        }
Now if you see above code, readability is much better after just applying naming conventions.
And we can go further and create a new class and hide all the magic numbers(4, 0) in that
class as shown below.
 public List<Cell> getFlaggedCells()
        {
            List<Cell> gameBoard = new List<Cell>();
            List<Cell> flaggedCells = new List<Cell>();
            foreach (var cell in gameBoard)
            {
                if (cell.isFlagged())
                {
                    flaggedCells.Add(cell);
                }
            }
            return flaggedCells;
 
        }
As you can see readability is must better now, all the implementation details are abstracted.

Later equals never

if you have been a programmer for more than 2 or 3 years, have you ever been impeded by bad code written by you or your team.? when i say impediment, what i think about impediment is if you were asked to do a change and it ideally should have taken less time, but practically it is never the case, doing small change requires making lot of other changes.

I think this will happen because of bad code. and ofcourse this bad code was written by us the programmers. but why do you think we write bad code? may be because of

we are trying to go fast or we were in a rush ignoring the principles , perhaps we were ignorant or tired of working on program for so long and may be frustrated because of this or promised to your manager to get it done by this time at any cost! or may be something cool coming up and you were pretty excited to get it started so didn’t concentrate on the current task in your hand.

and most of the time you know the program is in a mess and you have choosen to leave it for another day since you might have relieved by your QA confirmed that the code is working.We all have done it. I had done it saying to ourselfs we will come late and clean this up!

There is a law called LeBlane’s law which says ‘Later equals Never’. Now you know the law and its applicable to us

OAuth 2.0… basics you need to know…

OAuth 2.0

Before jumping straight in to oAuth.. let me ask you some questions..(may be rewind yourselfs 2-3 years back..because in the last 2-3 years.. each and every popular site you are interacting with would already have implemented oAuth)

How many have you given passwords of either facebook/gmail/yahoo to other sites like slideshare/zomato etc..
if your answer is yes.. then its a bad thing.. its wrong to share passwords.. you are giving access to slideshare or any other third party application access to your full gmail account.

Necessity and Birth of oAuth

with new applications(mobile/web) growing day by day.. and its mandatory that at some point of time .. we have to register to theapplication.. and to make user’s life easy(by not having remembering new passowrd :D) app providers have provided a way to login via google/facebook/twitter to their applications.this has led to user sharing their username/password of gmail/twitter/facebook to the third party provider..

This is a huge security breach.. consider you have provided your gmail id and password.. third party has access to your entire gmail.. i.e it can post/delete mail with your consent..

So there is a need to register with facebook/gmail/twitter with out having to share username/password..

i believe that need has became developing oAuth

OAuth Definition

Here’s the definition of OAuth 2.0 from the OAuth 2.0 IETF specification itself:
“The OAuth 2.0 authorization framework enables a third-party application to obtain limited access to an HTTP service, either on behalf of a resource owner by orchestrating an approval interaction between the resource owner and the HTTP service, or by allowing the third-party application to obtain access on its own behalf.”

Terms to Know

1. Resource Server – The Server that holds the resource
2. Resource Owner – The user who owns the specific resources
3. Authorization Server – A server that authenticates the resource owner and issues access tokens to the client
4. client – the application that requests access on resource on behalf of resource owner

IceBergClass -AntiPattern

found some article here

http://deviq.com/iceberg-class/

its a good read… !!

In Short.. its not good to have more PRIVATE methods in your class.
if you have more methods that depends on some behaviour.. its better to have abstracted them. i.e have an interface and declare all your behaviours in the interface and have the class implement this interface.. so that you will abstract the behaviour in to a concrete class and if ever this behaviour were to be changed, you will do changes in the concrete class.. by that way you will be adhering to single responsibility principle and open closed principle

Design Smells

In This post We will discuss on Design Smells

When you will know your design Rots…when you are experiencing any of the following in your project/ code you are working on.. you should be certain that there is something wrong happening and you really need to look in to it

1. Rigidity
2. Fragility
3. Immobility
4. Viscosity
5. Needless Complexity
6. Needless Repetition
7. Opacity

1. Rigidity

Rigidity is the tendency of the software difficult to change..A design is rigid , if a single change causes a cascade of subsequent changes..

Its like you are developing a system , and you are half way there.. and while adding new features or when you were asked to do a small change in existing system and if you are experiencing it is difficult to do that change because, its impacting most of the things in system and you need to change most of the existing system.you should consider your system is not rigidit

2. Fragility

Fragility is the tendency of a program to break in many places when a single change is made..

I would say fragility and rigidity would complement each other… when you are adding a new feature to the system, ideally there should be no impact to existing system.. as we would all agree it is almost impossible :).. BUT there should be minimal or no impact to existing system..then you should consider your system is not Fragile

3. Immobility

A design is immobile, when it contains parts that could be useful in other systems, but the effort and the risk involved with separating those parts from system are tooo great. this is unfortunate but very common occurrence

4.Viscosity
a viscous project is one in which the design of the software is difficult to preserve

when you find any problem in your system,generally we find more than one way to do that change.. one is adhering to design and the other which is not( A Hack ;)). When design preserving methods are harder to implement than hacks.. then your design is viscus

5.Needless Complexity

This may happen when developers are way ahead than Requirements..At first this may seem like a good thing to do..

i.e consider you may anticipate future requirements and you will put in elements in system which will be needed later in future, which you might consider a good thing to do. But you should consider that preparing for future changes should keep our code flexible and prevent nightmarish changes later.

unfortunately, the effect is just opposite.by preparing for future contigencies, design becomes littered…some of these preparations may pay off… but many are NOT

6. Needless Repetition

Cut and paste may be useful text-editing operations, but they can be disastrous to your system..

consider this.. suppose you need to convert a calendar date to business date and you thought that this must be somewhere in the system already and you do ctrl+shift+f and copy the code and paste it in your module… it happens that the code which you copied was written by a X developer which he had copied and pasted in his module from seeing in another module which has been developed by Y developer.. and also happens that Y developer copied and pasted that code in his module from another module which is developed by Z developer.. and Z developer had written that module… so there is a lot and lot of same code.. and if need to change that code… consider the nightmare…!!!!

7. Opacity

Opacity is the tendency of a module to difficult to understand..to avoid this code should be written in clean, clear and Expressive manner..

its a complete developers responsibility to write clean, clear and expressive code…
when you first write a code, it may seem every thing is clear to you at first.. because you might of immersed in it at an intimate level and you know every detail of whats happening over there…some months later, when you revisit the code and wonder if you had written this code…

To make your system free from opacity… its one’s responsibility to put ourselves in readers shoes and make a concrete effort to make code clean , clear and expressive

Now we have some understanding what are code smells and when can we identify them, let us also understand , why there are code smells.. and why they are accumulated in system..??

Why software Rots..??? Why there are code smells
You will see most of the software rots and code smells in non-agile environments..why mostly in non-agile environments..?

Because Requirements change in a ways that the initial design did not anticipate. and often these changed need to be made quickly and may be made by developers who are not familiar with the original design philosophy..though change to design works, it somehow violates the original design. Bit by Bit, as a changes continue, these violations accumulate making code worse and rotten…

However, we should not blame the changes in requirements for your rotten code.. if you are a software developer and if you have been in this industry, you should already know that requirements are most volatile elements in software projects and they are tend to change.. if our designs are failing owing to constant changes in requirements…its our design and practices that are at fault..and we must somehow need to find a way to make our designs resilient to those changes and practices that protect them from rotting..

what you need to do to keep your system clean
you should be agile… as an agile team thrives on change. team invests little upfront so it is not vesting on aging initial design .you should keep your system as clean as possible and back up your system with lots and lots of unit tests, this keeps design flexible and easy to change.. when you are changing some thing you know you have your tests and rely on them…
in each iteration(sprint) should end with a system whose design is as appropriate(clean) it can be for the requirements in that iteration.

Separating Your Concerns- Antidote to Smart UI Part 5

So in the previous blog we have created IDiscountStrategy and applied it to  NullDiscountStrategy and TradeDiscountStrategy Classes.

We have only created Discount Pattern here… and we need to apply this on Price Object and driving factor regarding which Discount Pattern to be applied will be decided by Customer Type.So in order to apply Discount pattern on Price object lets create DiscountFactory class which does this job.

 public static class DiscountFactory
    {
        public static IDiscountStrategy GetDiscountStrategyFor(CustomerType customerType)
        {
            switch (customerType)
            {
                case CustomerType.Trade:
                    return new TradeDiscountStrategy();
                default:
                    return new NullDiscountStrategy();
            }

        }

    }

With discount Strategies in place .. now lets implement Price Object…

 public class Price
    {
        private IDiscountStrategy _discountStrategy = new NullDiscountStrategy();
        private decimal _rrp;
        private decimal _sellingPrice;
        public Price(decimal sellingPrice,decimal rrp)
        {
            _rrp = rrp;
            _sellingPrice = sellingPrice;
        }
        public void SetDiscountStrategyTo(IDiscountStrategy discountStrategy)
        {
            _discountStrategy = discountStrategy;
        }
        public decimal SellingPrice
        {
            get { return _discountStrategy.ApplyExternalDiscountsTo(_sellingPrice); }
        }
        public decimal RRP
        {
            get { return _rrp; }
        }
        public decimal Discount
        {
            get
            {
                if(RRP&gt;SellingPrice)
                {
                    return RRP - SellingPrice;
                }
                else
                {
                    return 0;
                }
            }
        }
        public decimal Savings
        {
            get
            {
                if (RRP &gt; SellingPrice)
                    return (1 - SellingPrice / RRP);
                else
                    return 0;
            }
        }
    }

Now we need to apply this discount Pattern to Products List which we will do thru an Extension method

    public static class ProductListExtensionMethod
    {
        public static void Apply(this IList<Product>;products,
            IDiscountStrategy discountStrategy)
        {
            products.ToList().ForEach
                (p =&gt; p.Price.SetDiscountStrategyTo(discountStrategy));

        }
    }

Domain Service

with Domain in place.. we need to have a service in domain so that client(typically service layer ) can communicate with Domain layer.. lets create a Domain Service(name it Product Service)

public  class ProcuctService
    {
        private IProductRepository _productRepository;
        public ProcuctService(IProductRepository productRepository)
        {
            _productRepository = productRepository;
        }
        public IList<Product? GetAllProductsFor(CustomerType customerType)
        {
            IDiscountStrategy discountStrategy =
                DiscountFactory.GetDiscountStrategyFor(customerType);

            IList<Product> products = _productRepository.FindAll();
            products.Apply(discountStrategy);

            return products;
        }


    }

Now Domain Service layer is in player.. lts implement Service layer which would communicate with Domain Service layer


public class ProductService
    {
        private model.ProcuctService _productService;

        public ProductService(model.ProcuctService productService)
        {
            _productService = productService;
        } 

        public ProductListResponse GetAllProductsFor(
            ProductListRequests productListRequest)
        {
            ProductListResponse productListResponce =
                new ProductListResponse();
            try
            {
                IList<model.Product> productEntities =
                   _productService.GetAllProductsFor(productListRequest.CustomerType);

                productListResponce.Products =
                    productEntities.ConvertToProductListViewModel();

                productListResponce.Success = true;
               
            }
            catch (Exception ex)
            {
                productListResponce.Success = false;
                productListResponce.Message = ex.Message.ToString();

                throw;
            }
            return productListResponce;
        }
    }