Friday, August 31, 2018

Program to Nearer Future




As loving programming, we code software systems daily. But did you think about the future validity of your program .Sorry… "Near Future".


Sometimes our code may give big trouble when the systems scale up. Scaling your system may be from 2 users to 100 or 100000..00 users. You could say "we could not think about the Far Future because of project timing constraints". You are right. But remember to think for Near Future.


This is an example for illustrate the practice:

Lets say we have list of persons.


“Now  write a code to print person last names which start with the letter “Y””

If you are working with legacy system (before java8) your solution may look like below(java 8 solution will present at the end of the topic).  


But we know, when we going to apply that in real industrial environment we need to move those logics in to separate methods (in order to reduce code complexity).So we can write the same code as below:



But If we need to print persons which name start with H? Are you going to create separate method for that?(printLastNameStartWithH() etc.).You may say


...Noop……That’s not a good solution.First I change the method name and use generalized name and I can use additional argument to externalize filtering input. Then passing the filtering string, we can achieve your requirement.



But in near future if want to filter by lastNameStartWithM & lastNameStartWithH while keeping lastNameStartWithY ?
hmm..I need to create a separate method for that. Otherwise getting trouble now…

No still you need not to implement separate method for that.You can fallow this way;

Step 01:Create interface with test method


Step 02: Use anonymous inner class to implement filtering logic



In here we can change filtering logic as what we want. If we want to filter by lastNameStartWithM & lastNameStartWithR ,no need to change conditionalFilter methods’ signature. You can change the implementation of Condition interface as below.


 Now your code becomes:

If you familiar with java 8 ,no need to create separate interface for the above requirement. In java 8 , we have Predicate functional interface and lamda for that. Below is the java 8 solution.

So always try to program “NEAR FUTURE”. Sometimes his journey may not be simple to beginner. You have to learn and follow several things , specially including Design Patterns and Design Principles.