Tuesday, April 17, 2018

We were discussing why Interface description language don't become popular as compared to their alternatives. We said that interfaces or contracts provide the comfort for participants to work independently, offload validation, determine functional and non-functional requirements but the alternative to work with granular stateless requests that are well documented are a lot more appealing. 
We also discussed the trade-offs between state driven sessions and stateless APIs when discussing client side application development. We noted that there is a wonderful ecosystem of browser based client side software development using standard jargons and tools.
Today we see that there are differences to client side and application side software development. For example, client-side javascript based applications require to mitigate security threats that are fundamentally different from server side code. Those client scripts could run anywhere and on any device. Threats such as cross site scripting, man-in-the-middle attacks, sql injection attacks, cross-origin resource sharing etc are all vulnerabilites exploited from the client side.
Consistency in the way we describe our markup, stylesheets and scripts help smooth out the organization of code on the client side. However, they help only so much. There is nothing preventing the developer from moving logic forward from server to client side. When we did have fat clients, they were touted as sophisticated tools. With the help of Model-View-Controller architecture, we seemed to move to different view-models for tabs on the same web page and remove the restriction between rendering and content for the page. UI developers suggested that view-models make a page rather limited and highly restrictive in workflows requiring more navigations and reducing usability in general. The logic on the client side can also be further simplified without compromising rendering or usability. For example, we could make one call versus several calls to the API and data source. The entire page may also be loaded directly as a response from the backend. While API may define how the user interface is implemented, there is little need for user interface to depend on any state based interface. Therefore the argument holds even in front-end development.

#codingexercise : water retained in an elevation map :  https://ideone.com/HBEn3F

Monday, April 16, 2018

We were discussing why Interface description language don't become popular as compared to their alternatives. We said that interfaces or contracts provide the comfort for participants to work independently, offload validation, determine functional and non-functional requirements but the alternative to work with granular stateless requests that are well documented are a lot more appealing. 
Contracts are verbose. They take time to be written. They are also brittle when business needs change and the contract requirements change.
Contracts are also static and binding for the producer and consumer. Changes to the contract are going to involve escalations and involvement.  
Contracts whether for describing services or for component interactions. They are generally replaced by technologies where we use pre-determined and well-accepted verbs and stateless design.
The most important advantage of stateless design and syntax of calls is that each request is granularly authenticated, authorized and audited. By making a one to one relationship between a request and a response and not having the client span multiple requests with a shared state, we avoid the use of dangling resources on the server side and state management on clients.  The clients are required to be handling more preparation for each request but this happens to be a convenience when all the requests share the same chores.   
The other advantage to stateless design is that much of the requests now follow well-established protocols. These protocols come with important benefits. First they are widely accepted in the industry. Second they move away from company specific proprietary contracts.  Third the wide acceptance fosters a community of developers, tools and ecosystems. 
The popularity of a technology is determined not only by the simplicity of the product but by the audience using the technology. When tools, development environment and products are promoting stateless design over stateful contracts, no matter how much we invest in interface specification language, its adoption will be very much dependent on the audience who will generally go with their convenience. 
Protocols can be stateful and stateless. There is no doubt that either may come useful under different circumstances. Contracts still come useful in being a descriptor for a service in its three-part description - Address, Binding and Contract.  But when each service behaves the same as every other cookie-cutter service and a well-known binding and contract, there may not be anything more needed than address. 
Leaving the communications aside, let us look at the proposed benefit of a client-side state management. Certainly, it improves the performance of numerous intermediary requests if the setup and teardown are the ones taking the most performance hit. Also, the client has an opportunity to keep the reference on the server-side resource for as long as they want and the underlying communication channel holds. Proponents argue a stateful design may result in higher performance for trunk or bulk callers instead of retail individual callers since this reduces the number of clients to a manageable few. While this may be true, it underscores the stateful design as more of an exception rather than the norm. 
#codingexercise: https://ideone.com/3ZY49O

Sunday, April 15, 2018

Why doesn’t Interface description language become popular? 
Software is designed with contracts primarily because it is difficult to build it all at once.  Interfaces form a scaffolding that lets components be designed independently. A language used to define interfaces is enhanced to include many keywords to derive maximum benefit of describing the contract.  Software engineers love the validation that can be offloaded once the criteria is declared this way. Yet Interfaces or contracts do not become popular. Technologies that used such contracts as Component Object Model (COM) and Windows Communication Framework (WCF) were replaced with simpler and higher granularity and stateless mechanisms. This writeup tries to enumerate the reasons for this unpopularity. 
Contracts are verbose. They take time to be written. They are also brittle when business needs change and the contract requirements change. Moreover, they become difficult to read and orthogonal to the software engineers efforts with the component implementation. On the other hand, tests are improved because the success and the failure of the components as well as their functional and non-functional requirements can now be determined.  If the software does not work as expected, it might end up to be a miss or incorrect specification in the contract. 
Contracts are also static and binding for the producer and consumer. If they are static, it is easy to ship it to the consumer for offline software development. At the same time, the consumer might need to articulate changes to the contract if the interface is not sufficient. This bring us to the second drawback that changes to the contract are going to involve escalations and involvement.  
Contracts whether for describing services or for component interactions, are generally replaced by technologies where we use pre-determined and well-accepted verbs so that the lingo is the same but the payloads differ. Here we can even browse and determine the sequence of operations based on the requests made to the server. This dynamic discoverability of the necessary interactions helps eliminate the need for a contract. Documentation also improves the need to have explicit contracts and the chores needed to maintain them.  
Conclusion: Contracts provide the comfort for participants to work independently, offload validation, determine functional and non-functional requirements but the alternative to work with granular stateless requests that are well documented are a lot more appealing. 

#sqlexerrcise
Consider a set of players each of whom belongs to one and only one league. Each player may have several wins and losses as part of the games between leagues. A league may have any number of players.
Define a suitable schema and list all those players who have more wins than losses.
write a table valued function for SELECT player, count(*) as wins from GAMES where result='win' GROUP BY PlayerID
write a table valued function for SELECT player, count(*) as losses from GAMES where result='loss' GROUP BY PlayerID
Use the results A and B from above to determine count as
SELECT A.PlayerID, A.wins, B.losses from A INNER JOIN B on A.PlayerID = B.playerID where A.wins - B.losses > 0;
or we could use the PIVOT operator with the sum aggregate in this case.



Saturday, April 14, 2018

Today I'm taking a break from my previous post below on Java Interfaces to discuss a small coding question I came across  and post it here for thoughts:
/*
Implement a class with following methods
put( key, value );

delete( key );
getRandom(); // returns one of the values added randomly
Additional Requirements : No duplicates:
No dups.
    -    update existing
*/
public class MyNoDuplicateContainerWithGetRandom
{
    // for map based access
    private Dictionary<Object, Object>> dict;
    private List<Object> keys; // array
 
    public MyContainer() {
        dict = new Dictionary<Object, Object>> ();
        keys = new List<Object>();
    }
 
    public void put(Object key, Object value)
    {
        if (dict.ContainsKey(key)){
            dict[key] = value;
        }else
        {
            using(tr = new TransactionScope()){
            dict.Add(key, value);
            keys.Add(key);
            }
        }
    }
 
    public Object getRandom(){
        var r = new Random();     
        int index = r.Next(list.Count());
        Object key = keys[index];
        return dict[key];
    }
 
    public Object delete(Object key){
        if (dict.ContainsKey(key))
        {
                using (tr = new TransactionScope()){
                Object value = dict.Remove(key);
                list.Remove(key);
                }
        }
        return null;
    }

  • https://1drv.ms/w/s!Ashlm-Nw-wnWtheIEHpU4Jua0V79

Friday, April 13, 2018

Interface annotator:
Abstraction is one of the pillars of Object Oriented programming. When applied to behavioral representation, it is demonstrated with the use of interfaces in language. An interface enables any class to implement a certain abstraction of behavior via the contract described. Unit tests are often written using the mocking of these interfaces. This facilitates tests to be written even before the classes are implemented. This notion is often referred as the Liskov Substitution Principle. The purpose of this writeup is to describe a user library that gather statistics on the call usages automatically.
Description: API monitoring and mechanics are well understood because we often leverage it in production support of critical API implementations. These monitoring services are configured to read the number of calls made, the failures associated and record metrics of availability and latency. Rules and alerts may also be written to take actions on the associated records. The purpose and pervasiveness of API monitoring is never questioned. However the work involved is significant and therefore applied to external facing services.
Developers generally do not have such instrumentation and call statistics other than profiling which comes at a very high cost. Something simpler in terms of just success failure and invocation counts cannot easily be determined from the runtime without some kind of instrumentation. Some do write annotations that can be added to methods to capture this information, however decorating each and every method is generally tiresome.
On the other hand, if every interface could gather such statistics and the results could be persisted from a run of the application, then such data could become valuable to query. Collecting information automatically on interfaces could be supported with the help of a library. In other words, monitoring as opposed to profiling could be helpful even pushed down to methods on the interfaces within a service and not just the methods that are externally facing and invoked via APIs.
Interfaces are used for several techniques one of which is the inversion of control principle. This lets implementations to be invoked from the interfaces so that they are automatically available within the service. Consequently unlike classes, they are heavily shared and statistics more appealing because the usage is not limited or scoped.
Conclusion: Simple statistics on interfaces if collected automatically could provide significant insight without the encumberance of profiling.
Courtesy : http://users.ics.aalto.fi/kepa/publications/KahLamHelNie-RV2009.pdf
https://ideone.com/saidLd

Thursday, April 12, 2018

 Today I'm going to continue discussing Microsoft Dynamics AX.  SAP, ERP and CRM solutions are a world of their own. We have not looked at these in detail earlier so we start with Dynamics. The user interface for Dynamics provides a variety of tools for viewing and analyzing business data. Data is usually presented in Reports. Reports can be standard-reports, Auto reports or ad hoc reports. Tasks might take longer to execute. Sometimes its best to let it run elsewhere and at some other time where they can be prioritized, queued and executed. Documents may be attached to data. This is helpful in cases where we need to add notes and attachments to the data.  The enterprise portal enables web based access to the dynamics instance on a server installed in the enterprise network. Access is role based such as employees, Sales representatives, consultants, vendors, customers etc. This completes a brief overview of the user interface.
The General Ledger is probably the core financial section of the user interface. It is used to record fiscal activities for accounts for a certain period. For example, it has accounts receivable and accounts payable sections.  The entries in the ledger may have several parameters, defaults, sequences, dimensions, dimension sets and hierarchies. In addition, tax information and currencies are also included.
Cost accounting is another key functionality within Dynamics AX.The cost of overheads and the indirect costs to the entities can be setup as cost categories and they can be defined for use within cost accounting. These cost categories can have a link to the ledger accounts. This way ledger transactions show up under the appropriate category. Costs can even be redistributed among other categories and dimensions so that the cost structure of the business can be analyzed. The dimensions of a cost usually include the cost center and the purpose.
Dynamics AX also has a bank section. We can create and manage company bank accounts and associate activities and artifacts such as deposit slips, checks, bills of exchange and promissory notes. We can create bank groups, bank transaction types and the bank accounts that the company has in each bank group and check the layouts for the bank accounts. Standard query operations may then be applied to the bank data. Reconciling, generating summaries and printing statements are also made possible. We can make a payment by check, setup a method of payment for checks, delete checks, create a deposit slip, unposted checks, a check on a ledger account or to reconcile bank accounts.
As we see the financial sections within Dynamics AX, we note that it is dedicated towards what helps the business process. This is what differentiates this product from other related products. Dynamics is all about convenience.
#codingexercise
https://ideone.com/BiivdE

Wednesday, April 11, 2018

Implementation of a circular queue

public class CircularQueue {

private List<int> items;

private int head;

private int tail;

public CircularQueue(int capacity)

{

items = new List<int>(Enumerable.Repeat(capacity, 0));

head = 0;

tail = 0;

}

public void Enqueue(int val)

{

if (head == tail)

{

     // throw new UnsupportedException

     tail = (tail  + 1) % capacity;

}

items[head] = val;

head = (head + 1) % capacity;

}

public int Dequeue()

{

if (tail == head)

{

throw new UnsupportedException();

}

int val = items[tail];

tail = (tail + 1) % capacity;

return val;

}

}



head  tail

0       0



E

D

DE

DD

EE

ED

EDE

EED

DEE

EEE

DDD

DDE

#minesweeper

https://ideone.com/kPGtZ5

https://ideone.com/ACLtJs