Thursday, 28 April 2016

Technical Debt Shouldnt Be Handled Like Financial Debt






by Sarang Nagmote



Category - Developer
More Information & Updates Available at: http://vibranttechnologies.co.in




Like many software developers in the 21st century, I use the term “technical debt” in a negative way: its the ever-accumulating cruft in your system that stands in the way of adding new features. As technical debt increases, the work takes ever longer, until you reach a point where forward progress ceases.
This view of technical debt equates it to a credit card: unless you pay your balance in full each month, youre charged interest. If you only make the minimum payment, that interest accrues and it will take you years to pay off the card. If you make the minimum payment and keep charging more, you may never get out of debt. Eventually, after maxing out several cards, youll have to declare bankruptcy.
But thats a very puritanical view of debt, and its not a view shared by everyone.
For a person with a business-school background, debt is a tool: if you can float a bond at 5% to build a factory that gives you a 10% boost in income, then you should do that (usually — there are other factors to consider, such as maintenance and depreciation). More important, youre not going pay that bond off before its due; doing so would negate the reasons that you issued it in the first place.
Which means that the term “technical debt” probably doesnt have the same connotations to your business users as it does to you. In fact, using that term may be dangerous to the long-term prospects of your project. If you say “we can release early but well add a lot of technical debt to do so,” thats a no-brainer decision: of course youll take on the debt.
I think a better term is total cost of ownership (TCO): the amount you pay to implement features now, plus the amount you will pay to add new features in the future. For example, “we can release this version early, but well add three months to the schedule for the next version.”
Which may still mean that you cut corners to release early, and probably wont stave off demands to release the next version early as well. But at least youll be speaking the same language.

Design Patterns in Swift: Document-View






by Sarang Nagmote



Category - Mobile Apps Development
More Information & Updates Available at: http://vibranttechnologies.co.in




Over the years, weve developed a few patterns to deal with building user interfaces to programs and dealing with dynamic data. Weve had Model-View-Controller (MVC), Document-View (DV), Model-View-ViewModel (MVVM), and a few more (for an exhaustive list, see Derek Greers excellent piece covering the history and use of every presentation pattern youve heard of, and a few you havent). Though Im not going to cover all of these, I would like to start discussing the most popular ones. It amazes me given how much weve discussed these patterns over the years that we still regularly get them wrong in custom implementations.
The Document-View Pattern. The document-view pattern was once the preferred pattern used in Visual C++ development. Microsoft built the original Microsoft Foundation Classes around this pattern, in fact, back in the dark ages. It’s not used much today, but it’s useful when you have simple data management needs. The problem with this particular pattern was the decentralization of data management logic, which tended to be spread around the document and view classes.
This pattern, originally, was built to address data view proliferation. Back then, engineers were building applications like spreadsheets, email clients, or word processors, and these were primarily rich clients running locally on some workstation. The more sophisticated applications had a client-server architecture with a data repository backend of some kind. Engineers were continually running into issues where they had to dynamically display the same data in multiple ways. Now, the MVC pattern would certainly have solved this problem too, but when the MFC designers adopted DV we didn’t have the kind of internet we have today. It’s very likely they weren’t aware of the pattern. They also may have felt it was too complex, and wanted a simpler data display architecture. Whichever the case may be, they used DV instead of MVC, getting rid of a separate controller class.
What is it? In the DV pattern, we have essentially two classes - a document class, which works as a model and an observer and can communicate with some backend repository, and a view class, which displays data and provides user data manipulation functionality. The document contains a reference to all the views, and each view contains a reference to the document, for a many-to-one relationship between views and documents. And it’s pretty easy to migrate from DV to MVC too, a definite plus. You can start with a simpler pattern and easily refactor to a more complex, powerful one if needed. More on this shortly.
Why use it? Well, it’s simple. It’s fast to build and easy to navigate.
Why not? It’s pretty disorganized. So the view object needs to not only render data, it also needs to handle data input. This can lead to bloated document and view classes, and a distribution of control logic across two separate classes, usually a bad idea. Realistically, this usually gets relegated to an aggregate object in more complex scenarios. And this, basically, is MVC. It also has circular dependencies, which are always fun to design around.
An example. This is a simple example, but it shows how data can update from some backend store through the document and how the views can also update the data based on control gestures from the user. First, let’s define some protocols:
public protocol Document { typealias EventType typealias KeyType typealias DataType var state : DataType? { get set } func addView(key: KeyType, eventHandler: (EventType) -> Void) func removeView(key: KeyType)}public protocol Event { init(message: String) var message : String { get }}
Here, we have two protocols, one defining a document, and one defining an Event. The document references multiple view callback functions, while each view references a single document. Yay! Circular dependencies! Here, we get around this by manually adding each view to the document rather than supplying an initialization argument containing a list of views.
Next, using these protocols, let’s define some classes:
public class SimpleEvent : Event { public var message : String public required init(message: String) { self.message = message }}
This is a simple event implementation. It packages a message into a simple event class. You’d frequently pass much more information than this in an event, perhaps even a pointer to a larger data object. In this case, we’re just passing a string to more clearly illustrate the pattern.
public final class StringDocument<T : Event> : Document { private var views : [String: (T) -> Void] = [:] private var data: String? public var state: String? { get { return data } set(state) { if let mystate = state { data = mystate if let mydata = data { notify(mydata) } } } } public func addView(key: String, eventHandler: (T) -> Void) { views[key] = eventHandler } public func removeView(key: String) { views.removeValueForKey(key) } public func removeAllViews() { views.removeAll() } private func notify(data: String) { let event = T(message: data) views.forEach { $1(event) } }}

The Document implementation manages the document data and a collection of views that’re interested in updates to that data.

public final class StringView<T : Event, D: Document where D.EventType == T, D.DataType == String> { private let name : String = String(arc4random_uniform(10000)) private var document : D private var data : String? init(document: D) { self.document = document } public func onDataChange(data: T) { self.data = data.message render() } public func submitData(data: String) { document.state = data } public func render() { if let mydata = data { print("((name)) data is: (mydata)") } else { print("((name)) no data available") } }}
Keep in mind, the View class is usually associated with some kind of visual user interface element. Here, for illustrative purposes, we haven’t implemented that kind of interactive control, though we have implemented the ability to change and render document data from a view, so the StringView class does behave like a view from the design pattern, though in a simple way. In the view class we can alter data, and when we do that, the document object is notified (and the document then notifies all the registered views). We also print the address of each view object in order to differentiate the objects when they’re printing submitted data. Really, very simple, but each class has the responsibilities outlined in the pattern. The document manages views and data from a backend repository of some kind. The view provides the ability to manage data, and presents the data to the user when it changes. Both the document and view classes reference one another. Here’s a simple example program using these classes:
typealias SimpleStringDocument = StringDocument<SimpleEvent>typealias SimpleStringView = StringView<SimpleEvent, SimpleStringDocument>var document = SimpleStringDocument()var view0 = SimpleStringView(document: document)var view1 = SimpleStringView(document: document)var view2 = SimpleStringView(document: document)document.addView(view0.name, eventHandler: view0.onDataChange)document.addView(view1.name, eventHandler: view1.onDataChange)document.addView(view2.name, eventHandler: view2.onDataChange)[view0, view1, view2].forEach { $0.render() }document.state = "blargh"view0.submitData("foo")view1.submitData("bar")document.removeView(view2.name)view0.submitData("blech")
Let’s run this example in a playground; what do we get?
(313) no data available(4371) no data available(460) no data available
After we create and add the new views, we render the document data from each view. The data’s yet to be assigned, so we have no data to view.
(460) data is: blargh(313) data is: blargh(4371) data is: blargh
We’re setting information in the document from some backend repository, and the document then notifies all the views of the update. The connected views then print the data that has been updated in the repository, carried in the event message.
(0x00007f956d900210) new data is: foo(0x00007f956d81eec0) new data is: foo(0x00007f956bd037a0) new data is: foo
Here, we’re viewing data to the user based on notification events received in the views from the document.
(0x00007f956d900210) new data is: bar(0x00007f956d81eec0) new data is: bar(0x00007f956bd037a0) new data is: bar
Again with the changing of the data via a view object. Then, for fun, we remove one of the views.
(0x00007f956d900210) new data is: blech(0x00007f956d81eec0) new data is: blech
Here, we only notify two views of the change, so we update the data twice, once through each view.
That’s it! Very simple, as I promised. Document-view patterns are fast to build, easy to test, but only really work in simple cases.

Testing Java EE (or Why Integration Tests Are Overrated)






by Sarang Nagmote



Category - Programming
More Information & Updates Available at: http://vibranttechnologies.co.in




In (enterprise) development testing often is treated very much as poor relations. But for more than “Hello World” applications testing is not just nice to have (at the end of the project) rather than crucial for working software. How to test Java EE applications in a productive yet comprehensive way?
A good test has following criteria: It must be fast, reliable and easy to write and maintain.
There are several ranges of testing like unit, integration or system tests. The smaller the scope of the test is the easier it is to write and to maintain, the faster it runs but also the more “far away” it is from the real world application.
IMO following test scopes should be applied in certain situations.
Unit Tests
Unit tests cover the business logic of a single component — usually a class — and provide very fast feedback for the developers without needing to startup any container.
The simplest way to unit test Java EE components is to use plain JUnit without any special runner and Mockito to mock away every other involved component.
@Stateless public class TaskStore { @PersistenceContext EntityManager entityManager; public List<Task> listAll() { return entityManager.createNamedQuery("Task.findAll", Task.class).getResultList(); } public List<Task> filterAll(final Filter filter) { return listAll().parallelStream().filter(filter::matches).collect(Collectors.toList()); } ... }

import static org.mockito.Matchers.*; import static org.mockito.Mockito.*; public class TaskStoreTest { private TaskStore cut; @Before public void setUp() { cut = new TaskStore(); cut.entityManager = mock(EntityManager.class); TypedQuery mockQuery = mock(TypedQuery.class); when(cut.entityManager.createNamedQuery(anyString(), any())).thenReturn(mockQuery); when(mockQuery.getResultList()).thenReturn(sampleTasks()); } @Test public void testFilterContextMatch() { Filter filter = new Filter(); ... List<Task> filteredTasks = cut.filterAll(filter); assertEquals(1, filteredTasks.size()); assertEquals(...); verify(cut.entityManager).createNamedQuery("Task.findAll", Task.class); } }

As EJBs and CDI managed beans are basically POJOs with annotations, it’s trivial to create or mock them in a test.
@Injected dependencies can be mocked and manually modified in the class due to the fact that the test resides in the same package as the component and can access the package-private defined property. Not all developers may agree to making the properties not private just for testability. However, this enables the test to easily modify the dependencies without the need for (slow) Reflection. And the Java EE implementation will prevent production code to reset the dependencies of any managed bean.
With that approach one can run hundreds of tests in no time. Any special @RunWith runner definition should be considered over-engineering for a simple unit test — with the exception of Parameterized tests. The latter are in fact very helpful for mass tests.
In general: You can be creative in how to write tests, but they must run fast and simplicity wins.
Integration Tests
Integration tests in a Java EE environment usually mean to combine a few components in a sort of emulated container. Test frameworks like Arquillian can be used to accomplish this.
The problem with this approach is that it consumes much more time than a unit test as the container has to be started every time. That is why it can be a problem to cover business logic with integration tests.
The killer use case however is to test CDI extensions and technical Java EE “plumbing” — rather than business logic. Testing custom CDI producers or custom scopes for example is a perfect scenario. But: These tests should be the big exception in your application.
System Tests
Unit and integration tests are nice to get a fast feedback but if your application is solely tested by them you’ll get other errors on production (like environment-specific configuration, problems with the server environments or external interfaces, etc.). A full system test on the other hand covers all business use cases end-to-end. The application should run in the same way during the test as it would in production. That means the system test environment is ideally the same — including server configuration, databases, network, etc. — with the only difference that it’s not the real production server. During the tests all external systems are mocked away and ensure that the application communicates with them in a correct way.
Having that said means also that integration tests which combine a few components are somewhat overrated. Your application can’t rely on integration tests only and then the feedback time saved is in general not worth the overhead of writing and maintaining them.
That is why I recommend to only have simple unit tests for fast feedback and fully-fledged system tests — with the exception that integration tests sometimes help to test Java EE “plumbing”.
An easy way to achieve an identical system for all environments is to use containers. The container which incorporates the application, the application server and the operating system is built once from the CI server and used for all environments. Using this approach highly increases the stability as exactly the same artefacts run in production which have been tested extensively.
Conclusion
From my point of view a productive and yet comprehensive Java EE testing pipeline looks like follows:
  • Unit tests with plain JUnit (no @RunWiths needed)
  • Integration tests for business logic considered harmful
  • Full system tests which cover all business use cases
  • Continuous Deployment pipeline deploying and starting the system tests automatically
  • Automated performance / stress tests depending on the requirements
  • Deploying the tested application (ideally as container) in production

Sunday, 24 April 2016

Spark and Scala Resources






by Sarang Nagmote



Category - Data Analysis
More Information & Updates Available at: http://vibranttechnologies.co.in




Github Resources 

Github Resources - Scala Workshop

Setup Resources

Setup

Make sure you have the Java 7 or Java 8 SDK installed for your platform (Mac, Linux or Windows).   Then you’ll need to download Scala 2.10.x, SBT and then Spark.   I also recommend downloading Maven. 

Solving Local Spark Issues

export SPARK_MASTER_IP=127.0.0.1export SPARK_LOCAL_IP=127.0.0.1export SCALA_HOME=~/Downloads/scala-2.10.6export PATH=$PATH:$SCALA_HOME/bin
For Windows, use SET instead of EXPORT and ; and not :.

Books

Tutorials

E-Books

Scala Koans/Exercises

Resources

Online Free Courses – Scala

Online Free Courses – Spark

When PostgreSQL Doesnt Scale Well Enough






by Sarang Nagmote



Category - Databases
More Information & Updates Available at: http://vibranttechnologies.co.in




The largest database I have ever worked on will eventually, it looks like, be moved off PostgreSQL. The reason is that PostgreSQL doesnt scale well enough. I am writing here, however, because the limitations are so extreme that it ought to give plenty of ammunition for those who think databases dont scale.

The current database size is 10TB and doubling every year. The main portions of the application have no natural partition criteria.  The largest table currently is 5TB and is the fastest growing portion of the application.

10TB is quite manageable. 20TB will still be manageable. By 40TB, we will need a bigger server. But in 5 years, we will be at 320 TB, and so the future does not look very good for staying with PostgreSQL.

I looked at Postgres-XL and that would be useful if we had good partitioning criteria but that is not the case here.

But how many cases are there like this? Not too many.

EDIT:  It seems I was misunderstood. This is not complaining that PostgreSQL doesnt scale well. It is about a case that is outside of all reasonable limits.
Part of the reason for writing this is that I hear people complain that the RDBMS model breaks down at 1TB which is hogwash. We are facing problems as we look towards 100TB. Additionally, I think that PostgreSQL would handle 100TB fine in many other cases, but not in ours. PostgreSQL at 10, 20, or 50TB is quite usable even in cases where big tables have no adequate partitioning limit (needed to avoid running out of page counters), and at 100TB in most other cases I would expect it to be a great database system. But the sorts of problems we will hit by 100TB will be compounded by the exponential growth of the data (figure within 8 years we expect to be at 1.3PB). So the only solution really is to move to a big data platform.