Practical Implementation of in-memory Repository Patterns

Recently I have been given a task to demonstrate my key knowledge on OOP and Design Patterns and its practical implementation.

The Task

Create an in memory implementation of IRepository<T>

Hints:The solution should be developed in a Test Driven approach, we expect the code you write to have excellent unit test coverage.Keep the solution simple, we value simple architecture and SOLID principles, but we’re not looking for over engineered design.The code should be self-explanatory, documentation should not be required to understand the code.

I have create a solution for that but prior to that I would like to explain what is repository pattern and explain it in my own words and how I implemented by describing my thoughts.

Repository Pattern: what is it?

Repository pattern is a pattern for data access. This is a common design pattern inside of applications that need to perform data access.

Why do we use the Repository Pattern?

Because most of applications do need to access data from some Data source or perhaps multiple data sources, and for that we need to use data access code throughout Business Logic or Domain Model. It is true that data access code typically is very repetitive and it’s concerned with low-level infrastructure details such as opening SQL connection and managing parameters etc.

This pattern will help us to separate the data access code from business logic and increase the testability of an application without real data in the place. and we can simulate data access in unit tests and have a component that works with in-memory data instead of web service or against any database schema.This allows us to unit test to be very repeatable, very low friction and not much effort to set up and it has quick feedback cycle.

So Let us crack on.

A Repository is going to be a class that you build for your application and it’s going to exist somewhere between the Business Logic and the Data Source of your application. You might have multiple repositories inside of an application. You might have a repository for each type of entity that you need to store.

Here we have been given an opportunity to create a solution for in-memory Generic IRepository Implementation which allows us to Save, Delete, Retrieve all or Find data by Id. Because it is generic in nature it can be easily implemented for any other entities.  Likewise here we are talking very specific implementation for IStoreable which has a Property of IComparable. (You must have knowledge of how IComparable works and implements and further details can be found here

image

So let us get back to our original given problem statement:

Following interfaces has been given and we have to implement the concrete class for them.

The first file is IStoreable.cs as given below:

   1: using System;

   2:  

   3: namespace RamInfosystems.Interview

   4: {

   5:     public interface IStoreable

   6:     {

   7:         IComparable Id { get; set; }

   8:     }

   9:     

  10: }

Now next file is IRepository.cs as given below:

   1: using System;

   2: using System.Collections.Generic;

   3:  

   4: namespace RamInfosystems.Interview

   5: {

   6:     // Please create an in memory implementation of IRepository<T> 

   7:  

   8:     public interface IRepository<T> where T : IStoreable

   9:     {

  10:         IEnumerable<T> All();

  11:         void Delete(IComparable id);

  12:         void Save(T item);

  13:         T FindById(IComparable id);

  14:     }

  15: }

 

And we need to create some test in Unit Test file.

My approach to solve this is by applying Test first. Clearly here the implementation of an interface is generic type and has constraints of type Interface. And this will harness the element which we can compare and test against it. So far nothing unusual.

So when you implement the IRepository Class you also need to implement  IStoreable as well. Which I think first you need to figure it out what need to be achieved.

   1: public class TestStoreable : IStoreable

   2:     {

   3:         public string Name { get; set; }

   4:         public IComparable Id { get; set; }

   5:     }

 

So what we need to do here is Implement the IRepository interface and its 4 of Methods as such All, FindByID, Delete and Save. It was pretty obvious that implementation is a key for the each of operation required to be tested. I have to add a property call Name as string to attach.

I started with unit test and create my first test method named Test_Repository_List_Returns_IEnumberable_CorrectType as follows:

   1: [Test]

   2: public void Test_Repository_List_Returns_IEnumberable_CorrectType()

   3: {

   4:   repository = new Repository<TestStoreable>();

   5:   this.expected = repository.All();

   6:   Assert.IsInstanceOf<IEnumerable<TestStoreable>>(expected);

   7: }

Small explanation about the long name. I intend to do readable code as needed and what  my code does is reflect by its name for example test repository list returns when IEnumberable with correct type.

But I don’t have any implementation of Repository or any implementation of All(). Let’s implement it as below:

   1: using System;

   2: using System.Collections.Generic;

   3: using System.Linq;

   4: using System.Text;

   5:  

   6: namespace RamInfosystems.Interview

   7: {

   8:     public class Repository<T> : IRepository<T> where T : IStoreable

   9:     {

  10:         private List<T> entities;

  11:  

  12:         public Repository()

  13:         {

  14:             entities = new List<T>();

  15:         }

  16:  

  17:         public IEnumerable<T> All()

  18:         {

  19:             return entities;

  20:         }

  21:         ///Not fully implemented. 

  22:       

  23:     }

  24: }

so when we call repository.All() it expected to be IEnumberable of generic type and List<T> is a same of the type.  Trick here is a concrete implementation of IStoreable gives us a opportunity to test all() method’s implementation.

Further on Delete(IComparable id) and Save(T item) implementation also based on the writing test first approach, Arrange, Act and Assert is cycle for TDD and I follow the same.

   1: [Test]

   2: public void Test_Repository_Save_AddNewItem()

   3: {

   4:    repository = new Repository<TestStoreable>();

   5:    newItemToBeSaved = new TestStoreable { Id = 1, Name = "ItemToBeSaved" };

   6:    repository.Save(newItemToBeSaved);

   7:    expected = repository.All();

   8:    Assert.IsTrue(((IEnumerable<TestStoreable>)expected).Contains(newItemToBeSaved));

   9: }

  10:  

  11: [Test]

  12: public void Test_Repository_Delete_An_Existing_Item()

  13: {

  14:    repository = new Repository<TestStoreable>();

  15:    anExistingItem = new TestStoreable { Id = 1, Name = "AnExistingItemToBeDeleted" };

  16:  

  17:    repository.Save(anExistingItem);

  18:    repository.Delete(1);

  19:    expected = repository.All();

  20:  

  21:    Assert.IsFalse(((IEnumerable<TestStoreable>)expected).Contains(anExistingItem));

  22: }

 

Now it is obvious for method Delete we are providing an ID (which is IComparable) and which leads to additional method to create as it requires Predicate of its type and we can fetch through the Id by lambda expression  as follows

   1: private Predicate<T> MatchedId(IComparable id)

   2: {

   3:   return match => match.Id.Equals(id);

   4: }

 

Alright. so it help to find an Id which provided in the Delete method. Also it add an advantage to avoid a duplicate id in the Save operation shown as follows

   1: public void Save(T item)

   2: {

   3:    Delete(item.Id); // Avoid Duplicate

   4:    entities.Add(item);

   5: }

 

Here it might get tricky as Lazy evaluation of Find as we are passing IComparable Id which lead us to do certain things.  

   1: [Test]

   2: public void Test_Repository_Find_By_Id()

   3: {

   4:     repository = new Repository<TestStoreable>();

   5:     someItem = new TestStoreable { Id = 2, Name = "SomeItem" };

   6:     anExistingItem = new TestStoreable { Id = 1, Name = "ExistingItem" };

   7:     newItemToBeSaved = new TestStoreable { Id = 3, Name = "NewItemToBeSaved" };

   8:     repository.Save(someItem);

   9:     repository.Save(anExistingItem);

  10:     repository.Save(newItemToBeSaved);

  11:  

  12:     expected = repository.FindById(2);

  13:  

  14:     Assert.AreEqual(someItem, expected);

  15: }

And finally Implementation of FindById.

   1: public T FindById(IComparable id)

   2: {

   3:     return entities.Find(MatchedId(id));

   4: }

 

This will harness all the uses of Predicates and Generic list to find and match equal ids. This technique will help to enhance in-memory sorting and searching very quickly. However I haven’t included any stress-test to generate let us say 100 Million records and measure performance against the memory load or anything as it was out of scope for me at this stage. But Later I am thinking to write a separate article for it.  

I have tried to implement and develop this task using my ability to provide demonstration about how to implement the Repository Pattern for in-memory. 

Consequences

There are a couple consequences to using the Repository Design Pattern. First, you should have an increased level of abstraction inside your application. This is good because it should mean that you’ll have less duplicated code. It also means that you should have code that’s more maintainable, more flexible, and more testable, however, you do have some additional interfaces, some additional classes, some people who are not familiar with the design pattern might need to look at this and figure out exactly what’s going on before they can catch on. When you have data access logic buried right inside of your business code, sometimes it’s very easy to look at that and understand what’s going on, but it just doesn’t scale up well, and in complex applications, you really need this increased level of abstraction just to manage the complexity. Another consequence of the Repository Design Pattern is that you are one step further away from the data. Since the Repository is shielding you from the underlying infrastructure, sometimes it can also be more difficult to get hints into that infrastructure that can help it optimize some of the operations that it needs to perform against the Data Source.

Summary

Here I tried to explain the Repository Design Pattern and how we can use it to keep Business Logic and Domain Model free of data access code and away from infrastructure code and actual components that talk to the database.

Using the Repository Pattern, I was able to write more maintainable code and easily unit test code. And  I showed a specific example that implemented a generic repository in C# code, the IRepository<T> interface. Using the magic of Generics, I was able to provide a single concrete implementation of this interface that covers most of our needs in an application.

If you are looking for a code or repository you can get it from code project and stack overflow as link given below:

https://www.codeproject.com/Articles/1220983/Practical-Implementation-of-in-memory-Repository-Pattern

Introduction First Video Post

Hi all, my name is Ravi Lodhiya and I am a Full stack developer, this is my first video post. I am looking for a Contract opportunity in the Microsoft Technologies stack. I am available immediately for an interview. Please email me your Job Specification. Thanks for watching. I hope to speak you soon. Bye.

Move On Up

LYRICS

Hush now child, and don’t you cry

Your folks might understand you, by and by

Move on up, toward your destination

You may find from time to time

Complication

Bight your lip, and take a trip

Though there may be wet road ahead

And you cannot slip

So move on up for peace will find

Into the steeple of beautiful people

Where there’s only one kind

So hush now child, and don’t you cry

Your folks might understand you, by and by

Move on up, and keep on wishing

Remember your dream is your only scheme

So keep on pushing

Take nothing less, than the second best

Do not obey, you must keep your say

You can past the test

Just move on up, to a greater day

With just a little faith

If you put your mind to it you can surely do it

Just move on up

Move on up

But move on up

Oh child, but just move on up

But move on up

Move on up

Songwriters: Curtis Mayfield

Move On Up lyrics © Warner/Chappell Music, Inc

Okay, there may be no plans

Yes that’s right. As of now I had no plans ahead and yet achieved 10 pomodoros sessions straight in past few days, which also including help my kid to run for cross country race at Wigston Academy.

At the end she wasn’t first or no way near in top 20. But what valuable lesson I learn was when she went to the washroom and I was able to get motivation from the gymroom

IF MY MIND CAN CONCEIVE IT,

AND MY HEART CAN BELIEVE IT –

THAN I CAN ACHIEVE IT.

It’s just amazing and refresh my beliefs.

Ciao.

Overwhelm by LinkedIn responses

image

Original Post

I am really overwhelm by the response and viewers who looked at my post on LinkedIn. It is but obvious that I can not able to pin point who looked at it but at least I can say 182 of them where Managers/CEOs which means to me a lot. Most of them were Recruiters as you can see. But I am More interested talking to managers/directors where I think I can add value to their organization.

I admire all the companies and their management styles, they all are great and I am proud that some of the most recognised companies from Midlands and I adore them all. For the new role I am really keen to meet personally which allow me to excel my dreams and in return I will give my commitment to the company to put value back by serve them for next 5 years undoubted.

If it sounds good enough to you and feel that investing in my intellectual can reward your organization with greater returns then please contact me or delegate your HR to send me a proposal which I unable to denied. Your HR can email me from here.

I look forward to hear from you soon.

Sincerely,

Ravi Lodhiya

p.s.: If you are a Key Decision maker and want to save 25% agency fees then please approach me directly.

p.p.s.: Recruiters don’t be afraid to contact me either. I admire you equally and happy to have you business. So feel free to drop me a line.

The Powerful–‘Now’

I know lately I am not writing enough or doing something I should do or suppose what I love to do a lot. Writing. So I have come to a point where I found that let me write what is it.

‘Now’ – a powerful state. How? Let me explain to you.

If you have five minute from now onwards then just stop reading this further and switch off you screens, and sit down if you are not already be sited and without thinking further just sit quietly for 5 minutes.  See you after 5 minutes.

Image result for now

[……Read this after 5 Minutes……]

Right, if you are already not lost or distracted by any other activity or interrupted, than let me tell you the power you have felt is just now.

Think it again, Go back when you sit quietly,

what did you observed?

what did you feel?

Train of thoughts, mumbling self talks, Feelings, Rush through, Time lapse, your senses – smell, hear, see, touch. heartbeats …. endless emotions, feelings and your reaction to it – without thinking that all it is virtue. 

Just for a moment, detached yourself from your own self(by not to think about anything), a moment where you become now (technically we’re all ‘Now’, but we are not conscious or aware of it).  I don’t want to confuse you or puzzled you but let you feel what exactly you are feeling ‘Now’ and the moment you breath in or out, and be aware of ‘Now’ you will feel that power. Ok, I know it is first hard to understand and unexplainable in a way.

Let me help you out. What ever you are feeling right now, just stop. Just for a few moments, and go back when it started (not in the past but back just few moments ago) and try to identify what was it that make you feel? a thought – sense (hear, see, smell, touch) or something very powerful which you don’t know about it, Until ‘Now’.

The misery of  entire life lies in ‘Now’. Yes you have read correct – ‘Now’ is the truth. Sort but brutal, it born, you live it and it died, became a past, in this second. Done. Yet leave so many things behind, thoughts, things, emotions, memories,…… lots of it…

Have you ever wonder why? No… no need to. When you became aware of ‘Now’. This powerful moment, you don’t have to feel anything but just accept it as it is. Shell I have to do anything about it? Yeah off course. Live it fully. Happy, sad, anger, any emotions do you have now or feel when you think or wonder…. just remember – ‘Now’. Right… ‘Now’.

I think it is really a deeper then I anticipate, yet very simple. I am not a philosopher or disciple of any Guru’s, or God or religion, Well I used to be one, but when I awake or become conscious about ‘Now’ everything for me become secondary and no need to worry or feel anything about anyone. But it doesn’t mean that I am not getting angry, happy or sad or anything a normal human does. But because of this awareness,  Powerful ‘Now’, I don’t have to waste my energy on anything which is virtue.  So you don’t have too.

When you are feeling so many things or time where you feel down or high or any state just be aware of yourself by Now. Key is Detached yourself completely and feel the ‘Now’. All the problems will vanish on that very moment. You become more wise and wisdom of ‘Now’ will guide you through.

Let me know how do you feel now….?

Sincerely,

RL 

Simple can be harder than complex

Simple Can be harder than complex

Simple can be harder than complex: You have to work hard to get your thinking clean to make it simple. But it’s worth it in the end because once you get there, you can move mountains.

-Steve Jobs

Motivation make my day.

How to convert legacy site to responsive site without breaking it ?

I have been asked many time for how do you convert legacy site to responsive site. There is no easy answer to that, however over the years I have gained experience about how to do it wisely.

First of all, we need to understand what is responsive and what do we expect to see or not see when render to the different screens or estates. In other words, what do you want to hide and what do you want to show. Visualize it and walk through it by paper prototype and not even that if possible just build quick prototype (abstract functionality) for understand behaviour and set for the feedback from actual users and refine it until wow factor seen.

Upon agreement then I look at all the elements on the page and we tried to bind regions and match existing functionality to the each regions. It is harder than the said but we have to do it that way only to avoid error or even better failures.  Each region is like a view or possible view and without modifying its core functionality, I estimate it to bolt on new design by middle layer.

the_Rabbit_Hole

So how long do you think it would take?

Great question. It depends on how deep the rabbit hole goes. How tightly couple your design is and how well you can abstract those dependencies. All that counts. But for sure you need to be consistent with its development, and depend on complexity and usability. When I say how long, my understanding is when user able to use it live. It is tough to understand but it has to be like that way.

So if you think I have calibre to help you in your ongoing project or project that needs facelift and delivered without loosing its core. Ask me or just contact me and book appointment to discuss over a nice cup of tea. I will be delighted.

Do you need a resource to complete IT project/s? Yes. Then call me now…

Every company needs resources. Resources to complete projects where budget has been already allocated.  Now problem is with very little unemployment in the UK, companies are struggling to get hold of good resources and workforces, people are moving getting better wages and of course Brexit on the horizon and it has started its negotiation process. Yet all of this uncertainty, projects need to be carried out and delivered constantly, Pressure is mounting to make financial targets on Project Managers and Teams.

In this tough time, few things happening to the existing projects either project needs to keep on hold or hire more resources, or delegating projects/workloads to offshore or inland third-party (if it is safe to do so.) and on the top budget is limited and time is burning quickly.

Hire Ravi Lodhiya as a contractor

With this in mind, and as an experienced IT Contractor (trying to be Freelancer) I have few things to offer in this crucial time:

  • I can come to rescue your projects or workload if you delegate me.
  • I can help you/your company to find resource for your troubled IT projects.
  • I can help you to motivate your team and engaging them to better perform.
  • I can be honest to assess your estimates for the project and add value to it.
  • I can bring your project on track and if your budget is tight then find alternative resources for that.
  • As an independent entity, I  can be more resourceful to your enterprise by more cost-effective and reliable, affordable and promising.  While you are searching with your current recruitment agency to fill the gap in your team, I can surely add value to your projects and keep balls rolling till you find right candidate as a permanent staff or may be help your trainees to come up to speed.

So if you have a project going on trouble due to  lack of resources or new greenfield project on the horizon but not able to prove by recruiters or want to get an idea about how much it is actually going to cost. Just email me your details via contact page here.

I usually turn around your projects quickly and we can build long-term relationship as it grow.

p.s.: I am not a recruiter or neither representing them. I am an independent contractor work as a limited company and try to rescue enterprises and deliver value to their projects by offering my ability.

So if you reading this and feel that it is better to contact me here for further discussion. Believe me you won’t be disappointed.

Unwritten Ground Rules

Recently I watched documentary on unwritten ground rules(www.ugrs.net) and it was pretty impressive.

As an employee, we are bound for our duties and such duties have been pass it on without challenging it and it became an unwritten ground rule. It was until now at least for me.

Now, after watched that 2 minutes movie, I realized that the key reason was missing from it and that is,  what do I value most at my workplace, is it because ….

  1. Its commutable.
  2. Good wages.
  3. Great work culture.
  4. Potential for growth.
  5. Long history of success.
  6. Positive feedback.
  7. Friendly.
  8. Flexible

List goes on, but may be none of those implies that how can I make my company a better workplace?

However I always wondered, suppose if I have my own corporate company then how can I make that company an awesome place to work for and people absolutely adore it and value it, make it more successful and yet fun to work for?

I must admit here I need to define my own company’s purpose and core values first and then envision it. Every business is driven by 4Ps – People, Product, Places and Promotion.  

Purpose:

To give the best products with great promotion and value to the people at their own places.

What do I  value most?

  • Innovation
  • Integrity
  • Diversity
  • Openness
  • Teamwork

What is it that drives it?

I always see employees as an assets. They are intellectual assets who can nurture the culture. I should hire those who are passionate about their job, love what exactly they do. And have a same vision and values for the company.

I should always ask myself  – do my business (corporate) really care for them? As a company do I really able to accept those changes?

It is true that company can always hire anyone they want and fire them at the same time. But by doing that don’t you think it violates integrity. 

As an employee we must know about company’s core values and we must share it and respect it to live. Being passionate, enthusiastic about company and its products, take pride and be part of it. Absolutely vital that they took a proud for working.

Company shouldn’t choose them, they should choose the company and with a great reason.

Recognition and rewards always leads retention. Loyalty comes with a great trust and faith.

Success of the company lies where its employees welfare and continuous growth with a significant challenges.

I learn one thing from unwritten ground rules and I would like to share it.

If a corporate seeking a changes then employees must be treated as a loyal customers because they are the reason for the existence of corporate success.