Monday, February 20, 2017

Code reviewing tips

(Extract from dzone.com)
Clean Code

Checklist Item
Category
Use Intention-Revealing Names
Meaningful Names
Pick one word per concept
Meaningful Names
Use Solution/Problem Domain Names
Meaningful Names
Classes should be small!
Classes
Functions should be small!
Functions
Do one Thing
Functions
Don't Repeat Yourself (Avoid Duplication)
Functions
Explain yourself in code
Comments
Make sure the code formatting is applied
Formatting
Use Exceptions rather than Return codes
Exceptions
Don't return Null
Exceptions
* Reference: http://techbus.safaribooksonline.com/book/software-engineering-and-development/agile-development/9780136083238

Security
Checklist Item
Category
Make class final if not being used for inheritance
Fundamentals
Avoid duplication of code
Fundamentals
Restrict privileges: Application to run with the least privilege mode required for functioning
Fundamentals
Minimize the accessibility of classes and members
Fundamentals
Document security related information
Fundamentals
Input into a system should be checked for valid data size and range
Denial of Service
Avoid excessive logs for unusual behavior
Denial of Service
Release resources (Streams, Connections, etc) in all cases
Denial of Service
Purge sensitive information from exceptions (exposing file path, internals of the system, configuration)
Confidential Information
Do not log highly sensitive information
Confidential Information
Consider purging highly sensitive data from memory after use 
Confidential Information
Avoid dynamic SQL, use prepared statement
Injection Inclusion
Limit the accessibility of packages,classes, interfaces, methods, and fields
Accessibility Extensibility
Limit the extensibility of classes and methods (by making it final)
Accessibility Extensibility
Validate inputs (for valid data, size, range, boundary conditions, etc)
Input Validation
Validate output from untrusted objects as input
Input Validation
Define wrappers around native methods (not declare a native method public)
Input Validation
Treat output from untrusted object as input
Mutability
Make public static fields final (to avoid caller changing the value)
Mutability
Avoid exposing constructors of sensitive classes
Object Construction
Avoid serialization for security-sensitive classes
Serialization Deserialization
Guard sensitive data during serialization
Serialization Deserialization
Be careful caching results of potentially privileged operations
Serialization Deserialization
Only use JNI when necessary
Access Control


 * Reference: http://www.oracle.com/technetwork/java/seccodeguide-139067.html

Performance
Checklist Item
Category
Avoid excessive synchronization
Concurrency
Keep Synchronized Sections Small
Concurrency
Beware the performance of string concatenation
General Programming
Avoid creating unnecessary objects
Creating and Destroying Objects


* Reference: http://techbus.safaribooksonline.com/book/programming/java/9780137150021

General
Category
Checklist Item
Use checked exceptions for recoverable conditions and runtime exceptions for programming errors
Exceptions
Favor the use of standard exceptions
Exceptions
Don't ignore exceptions
Exceptions
Check parameters for validity
Methods
Return empty arrays or collections, not nulls
Methods
Minimize the accessibility of classes and members
Classes and Interfaces
In public classes, use accessor methods, not public fields
Classes and Interfaces
Minimize the scope of local variables
General Programming
Refer to objects by their interfaces
General Programming
Adhere to generally accepted naming conventions
General Programming
Avoid finalizers
Creating and Destroying Objects
Always override hashCode when you override equals
General Programming
Always override toString
General Programming
Use enums instead of int constants
Enums and Annotations
Use marker interfaces to define types
Enums and Annotations
Synchronize access to shared mutable data
Concurrency
Prefer executors to tasks and threads
Concurrency
Document thread safety
Concurrency
Valid JUnit / JBehave test cases exist
Testing


* Reference: http://techbus.safaribooksonline.com/book/programming/java/9780137150021

Static Code Analysis
Category
Checklist Item
Check static code analyzer report for the classes added/modified
Static Code Analysis


de Analysis


IOT - Internet of Things


  • It is a system of interrelated computing devices, mechanical and digital machines, objects, animals or people that are provided with unique identifiers and the ability to transfer data over a network without requiring human-to-human or human-to-computer interaction.
  • This is the concept of basically connecting any device with an on and off switch to the Internet (and/or to each other)
  • IoT allows for virtually endless opportunities and connections to take place
  • A typical IoT Architecture would be as follows (Extract - docs.microsoft.com - Microsoft Azure IoT Suite)

Friday, February 17, 2017

Java SE – Concurrency (Docs.Oracle.com)

  • Package – java.util.concurrent
  • Concerns two topics – processes & threads
  • Processes is based on computer hardware processor (runtime resources)
  • Each process has its own memory space
  • Threads exist within a process
There are two methods for starting a thread
  • Implement Runnable interface and provide code for "run" method













  • Subclass the Thread class













  • Thread.sleep causes the current thread to pause execution for a specific period (note that neither the Runnable interface is implemented nor the Thread class is extended. Just call Thread.sleep with time)











  • Supporting thread interruption
For a thread "A" to interrupt thread "B", thread "B" should be supporting its own interruption (i.e. the thread should be returning immediately when an interruption is received)

Below class supports interruption since immediately the exception is received the thread returns













If a thread continues to run without any InterruptedException then the thread should frequently call interrupt method to check if an interruption is available. If yes then should return immediately. Code snippet is as below.

for (int i = 0; i < inputs.length; i++) {
    heavyCrunch(inputs[i]);
    if (Thread.interrupted()) {
        // We've been interrupted: no more crunching.
        return;
    }
}
  • To tell thread "A" to resume execution after thread "B" completes (in other words, to tell thread "A" to
wait until thread B" completes, you can call the below method
B.join(); // within thread "A", we are telling A to join B

Thread interference Thread interference occurs when multiple threads run on 2 operations but act on same data (interleave)
See below sample code
class Counter {
    private int c = 0;

    public void increment() {
        c++;
    }

    public void decrement() {
        c--;
    }

    public int value() {
        return c;
    }

}
<CONTINUES FROM https://docs.oracle.com/javase/tutorial/essential/concurrency/simple.html>

Thursday, February 16, 2017

Databases : Normalization vs De normalization (studytonight.com)

Normalization – a systematic approach of decomposing tables to eliminate data redundancy and undesirable characteristics

Normalization forms
  • 1st Normal Form
  • 2nd Normal Form
  • 3rd Normal Form
  • BCNF (Boyce-Codd Normal Form)


Possible Database Anomalies
  • Update anomaly
Ex: Both Employee and EmployeeContact tables have address columns. When updating the contact information, one table is not updated so the same employee has 2 different address values when queried
  • Insertion anomaly
Ex: Course table contains fields CourseID, teacherID,
A teacher who is not yet assigned to a course is added to table with CourseID as null
  • Deletion anomaly
Ex: “Faculty and Courses” table has both lecturer and faculty. If “MEDICAL” faculty is closed, and if we delete all records belonging to “MEDICAL” faculty, all the lecturers in the same faculty will also get deleted (will cease to exist)


Normalization explained

1st Normal Form
No 2 rows of the table should contain repeating information

Each set of column must have a unique value (columns should not have comma-separated / list of values)
Before normalization
Adam
15
Biology, Maths
After normalization
Adam
15
Biology
Adam
15
Maths

Cons – Data redundancy increases
2nd normal form
For a table that has concatenated primary key, each column in the table that is not part of the primary key must depend upon the entire concatenated key for its existence. If any column depends only on one part of the concatenated key, then the table fails Second normal form.
Ex:
Name      Age        Subject
Mike        15           Maths
Mike        15           Science
Andrew   20           History

Above table has a concatenated primary key (i.e. to search a unique value the concatenated value has to be considered.
The field “Age” is not dependent on Name + Age + Subject. It depends only on the name. So Age should be separated out with a primary key

Above table will be decomposed into 2 tables
One has columns Name, Age & the other has columns Name, Subject where name will be the primary key of both tables

3rd normal form
There should not be the case that a non-prime attribute is determined by another non-prime attribute

Ex:
Student_id
Student_name
DOB
Street
city
State
Zip
Street, City & State depends on Zip. So the 3 fields should be moved to a different table as follows (decomposed into 2 tables)

Student_id
Student_name
DOB
Zip


Zip
city
State
Street


BCNF - <TO BE INCLUDED>



Normalization vs De-normalizations
Normalization

  • Writing operations (insert, update) are easy to perform (since no duplicate columns need to be updated)
  • Reading operations are difficult to perform (since data span across multiple tables so joint statements should be used)
De-normalization
  • Writing operations (insert, update) are difficult to perform since more than 1 columns need to be updated
  • Reading operations are easy to perform since data is contained in same table so no need to use joint statements

Micro services architecture (Mammatustech.com)


  • Focuses on distributed, componentized, SOA applications
  • Each service performs a single function
  • Is NOT same as SOA (SOA is often based on WSDLs, SOAP & XML schemas while MS is based on JSON, REST & HTTP)
  • Attempt to deploy independent services
  • Tries to keep business logic and data together
  • Results in continuous integration & delivery
  • JSON is the minimum requirement for micro services
  • Micro services are note stateless (they should own their data)
  • Is about going back to OOP basics (Data, Data storage is specific for its service)
  • Uses Docker or an Amazon AMI
  • You don’t use EAR/ WAR files in MS

Tuesday, February 14, 2017

Design Patterns - Demo


Factory Method


Factory class would look like below












<EDITING>

Atlassian BitBucket - Cloud version

Atlassian Bitbucket is a Repository Management solution
Cloud version is also available

History of commits for a Source code can be compared in different views





Branches 



Sunday, February 12, 2017

Java Garbage Collection (JavaTPoint.com)

In java, garbage means un-referenced objects.

Garbage Collection is process of reclaiming the run time unused memory automatically. In other words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management.

  • It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.
  • It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.

Java Persistence API (JPA)

Provides ORM facility for managing relational data in Java applications


  • Entity (equals to a table in a relational DB)
    • Must have a public/ protected no-arg constructor
    • Must not be declared final
  • Entity instance (equals to a table row in a relational DB)
  • Entity Manager Interface 
The EntityManager API creates and removes persistent entity instances, finds entities by the entity’s primary key, and allows queries to be run on entities.


A sample relational mapping is as follows


@OneToOne
@JoinColumns({
    @JoinColumn(name="PARTNUMBER",
        referencedColumnName="PARTNUMBER"),
    @JoinColumn(name="PARTREVISION",
        referencedColumnName="REVISION")
})
public Part getPart() {
    return part;
}

Message Queuing - RabbitMQ






RabbitMQ


  • Accepts and forwards messages.
  • Components are
    • Producer (Forwards the messages)
    • Consumer (Receiver)
    • Queue (an infinite buffer of messages)
  • Confirms to AMQP (Advanced Message Queuing Protocol)


Steps of the Producer (Pyhthon code)
1. Establish the connenction

import pika connection = pika.BlockingConnection(pika.ConnectionParameters( 'localhost')) channel = connection.channel()

2. Create a Queue

channel.queue_declare(queue='hello')

3. Send the message to the queue (Using an exchange method)

channel.basic_publish(exchange='',
                      routing_key='hello',
                      body='Hello World!')
print(" [x] Sent 'Hello World!'")


4. Close the connection
connection.close()

Steps of the Consumer 

1. Declare the Queue

channel.queue_declare(queue='hello')

2. Define the callback methodw which prints the message to be received

def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)


3. Define the Producer queue from which the messages should be received

channel.basic_consume(callback,
                      queue='hello',
                      no_ack=True)

4. Never ending loop which consumes messages continuously
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()