Optimistic.cf

Ad Banner

Artikel Terbaru

About Us

Social Share Icons

Sunday, 20 November 2016

Tips and Best Practices for SQL Programmers



Structured query language (SQL) is the primary language for databases. Whatever relational database platform you decide to use, you’ll need to use SQL to edit, insert, delete, and query records within the database. Each platform has small differences between their respective SQL syntax, but logic and development are still similar. The language is different than NoSQL, which has similarities but mainly different syntax. Here are some tips and best practices for any SQL development project.

1) Think About Relationships

The SQL language is the language of relational databases. You need to build tables based on relationships without creating “orphans.” Orphans are tables that don’t have a relationship with any other table and are poor database design. Each table should have a relationship with another, so when you query the database for records, you can join the tables together through their designated relationship.
You build a relationship through primary and foreign keys. For instance, suppose you have a customer table and an order table. Without the customer ID in the order table, the order table is orphaned. By placing the customer ID in the order table, you now have a relationship between the two tables that you can use to create queries.

2) Always Consider Performance, Even If the Query Seems Simple

Just because your SQL data set has few records currently doesn’t mean the data set won’t grow significantly after you move it to production. You should join tables on indexes and always have a primary key in each table.
One common mistake is to run a poorly performing query in development when the system has no users querying and very few records. The query runs fast, because there’s no load on the database server. Then, when the query is promoted to production and run in a busy environment, the query performs poorly and undermines site performance. Always consider performance even if the query seems like it won’t need many resources from the database server.

3) Use Table Aliases for Easier Reading

Let’s say you’re a developer who needs to maintain someone else’s code. Or, you’re a business owner who needs to hire a SQL developer to fill in the gaps with a specific project. The SQL developer can pick up where another developer left off much quicker if the code uses aliases and is well formatted.
Aliases shorten the name of a table and make it easier to read and determine the logic in a SQL statement. When you build a database, always consider the way the code is written. It should be easy for you and another developer to determine its logic and data set. Poorly coded SQL code can lead to bugs should another developer need to edit it.

4) Be Specific in Your SELECT Clauses

In any common SQL language, the asterisk ( * ) tells the database engine to return all columns within a table. There are several issues with this habit. The first issue is security. If a hacker is able to use a SQL injection attack on your database, it could leave every column available for theft. If you have customer passwords stored in the table, the attacker can expose passwords.
The second issue is performance. If you have a million records returned from a query, you affect performance when you return a couple dozen columns rather than the few that you need.
The third issue is that it’s difficult to determine what data will be returned. If you specify columns in your SELECT queries, you know exactly which ones are returned to the front-end application. For these three reasons, always specify the columns you want to return and avoid using the “all” or asterisk character in your queries.

5) Use NOCOUNT for Large Batch Queries

When you perform ad hoc queries such as updates and inserts on your database, the engine first performs the action, then gives you a count of the number of records that were affected. This is great for one-off changes when you want to confirm that changes were made to a specific number of records, but it shouldn’t be done on queries that run regularly.
When NOCOUNT isn’t used, the database must count the number of rows that were affected. This isn’t a necessary count with production queries that run regularly. Use NOCOUNT at the top of your stored procedures or ad hoc queries to improve performance.

6) Avoid Dynamic SQL

SQL injection is one of the most common attacks on the web. This type of attack leads to severe data breaches that expose millions of records to an attacker. Extremely strategic SQL injection attacks can even elevate permissions for the attacker to give them administrative rights on the database server.
Dynamic SQL is a type of coding that builds a SQL statement based on input from a user. Typically, it’s done on the front-end application side, but some SQL developers use it too. Dynamic SQL should be avoided at all costs—it’s this type of development that leads to SQL injection exposure.
If you absolutely need to use dynamic SQL, you should “scrub” data input and make good attempts to detect malformed SQL statements. You can use third-party tools or integrated tools available with some languages. For instance, the C# language has the TSqlParser class to help programmers identify SQL injection in a dynamic SQL environment.

7) Don’t Forget Object-Level Security

Security should always be a priority when designing a database regardless of the platform you use. Object-level permissions provide security based on the user and what the account can access. For instance, you want to use a separate user name for all of your databases and give them access to the database accordingly. By using this method, if a hacker gains access to the account, they’ll only be able to access one database and not the entire server.
You can be even more specific with object-level permissions. This tells the database the exact tables and even columns that the user can access. By using object-level permissions, you limit the amount of exposure if an attacker is successful at SQL injection.
For instance, suppose you store social security numbers in the database. A public-facing user application should never have access to this information. You only want internal employees to have access. So, you create a public-facing user account and give it object-level permissions to the table, then access rights to specific columns, excluding the social security column. If a hacker gains access to this account, they won’t be able to view social security numbers, which limits your data breach exposure, risk, and damages.

Conclusion

The key to good database design is to always make performance and security a priority. Remember to format your code for other developers who might need to edit your code or maintain it in the future.
SQL can get complicated if you don’t organize your code and create a design before you start coding. Take these tips and best practices and apply them to your project when you hire a SQL developer. If you’re a developer, always use these best practices to help make your client’s project a success 

A brief introduction to Database Concepts and SQL



A brief introduction to Database Concepts and SQL


What's a database ?
A database is a collection of data organized in a particular way.
Databases can be of many types such as Flat File Databases, Relational Databases, Distributed Databases etc.
What's SQL ?
In 1971, IBM researchers created a simple non-procedural language called Structured English Query Language. or SEQUEL. This was based on Dr. Edgar F. (Ted) Codd's design of a relational model for data storage where he described a universal programming language for accessing databases.
In the late 80's ANSI and ISO (these are two organizations dealing with standards for a wide variety of things) came out with a standardized version called Structured Query Language or SQL. SQL is prounced as 'Sequel'.
There have been several versions of SQL and the latest one is SQL-99. Though SQL-92 is the current universally adopted standard.
SQL is the language used to query all databases. It's simple to learn and appears to do very little but is the heart of a successful database application. Understanding SQL and using it efficiently is highly imperative in designing an efficient database application. The better your understanding of SQL the more versatile you'll be in getting information out of databases.
What Can SQL do?
• SQL can execute queries against a database
• SQL can retrieve data from a database
• SQL can insert records in a database
• SQL can update records in a database
• SQL can delete records from a database
• SQL can create new databases
• SQL can create new tables in a database
• SQL can create stored procedures in a database
• SQL can create views in a database
• SQL can set permissions on tables, procedures, and views
What's an RDBMS ?
This concept was first described around 1970 by Dr. Edgar F. Codd in an IBM research publication called "System R4 Relational".
A relational database uses the concept of linked two-dimensional tables which comprise of rows and columns. A user can draw relationships between multiple tables and present the output as a table again. A user of a relational database need not understand the representation of data in order to retrieve it. Relational
programming is non-procedural.
[What's procedural and non-procedural ?
Programming languages are procedural if they use programming elements such as conditional statements (if-then-else, do-while etc.). SQL has none of these types of statements.]
In 1979, Relational Software released the world's first relational database called Oracle V.2
What a DBMS ?
MySQL and mSQL are database management systems or DBMS. These software packages are used to manipulate a
database. All DBMSs use their own implementation of SQL. It may be a subset or a superset of the instructions
provided by SQL 92.
MySQL, due to it's simplicity uses a subset of SQL 92 (also known as SQL2).
RDBMS Terminology:
Before we proceed to explain MySQL database system, let's revise few definitions related to database.
• Database: A database is a collection of tables, with related data.
• Table: A table is a matrix with data. A table in a database looks like a simple spreadsheet.
• Column: One column (data element) contains data of one and the same kind, for example the column postcode.
• Row: A row (tuple, entry or record) is a group of related data, for example the data of one subscription.
• Redundancy: Storing data twice, redundantly to make the system faster.
• Primary Key: A primary key is unique. A key value can not occur twice in one table. With a key, you can find at most one row.
• Foreign Key: A foreign key is the linking pin between two tables.
What's Database Normalization ?
Normalization is the process where a database is designed in a way that removes redundancies, and increases the clarity in organizing data in a database.
In easy English, it means take similar stuff out of a collection of data and place them into tables. Keep doing this for each new table recursively and you'll have a Normalized database. From this resultant database you should be able to recreate the data into it's original state if there is a need to do so.
The important thing here is to know when to Normalize and when to be practical. That will come with experience.
Normalization of a database helps in modifying the design at later times and helps in being prepared if a change is required in the database design. Normalization raises the efficiency of the database in terms of management, data storage and scalability.
Now Normalization of a Database is achieved by following a set of rules called 'forms' in creating the database.
1st Normal Form or 1NF:
Each Column Type is Unique.
2nd Normal Form or 2NF:
The entity under consideration should already be in the 1NF and all attributes within the entity should depend solely on the entity's unique identifier.
3rd Normal Form or 3NF:
The entity should already be in the 2NF and no column entry should be dependent on any other entry (value) other than the key for the table.
If such an entity exists, move it outside into a new table.
Now if these 3NF are achieved, the database is considered normalized.
SQL can be primarily divided into two parts: The Data Manipulation Language (DML) and the Data Definition
Language (DDL).
The query and update commands form the DML part of SQL:
• SELECT - extracts data from a database
• UPDATE - updates data in a database
• DELETE - deletes data from a database
• INSERT INTO - inserts new data into a database
The DDL part of SQL permits database tables to be created or deleted. It also define indexes (keys), specify
links between tables, and impose constraints between tables. The most important DDL statements in SQL are:
• CREATE DATABASE - creates a new database
• ALTER DATABASE - modifies a database
• CREATE TABLE - creates a new table
• ALTER TABLE - modifies a table
• DROP TABLE - deletes a table
• CREATE INDEX - creates an index (search key)
• DROP INDEX - deletes an index

Sunday, 13 November 2016

5 Books Programmers Must Read To Improve Their Coding Skills

Console.log
Learning a Programming language e.g. Java or C++ is easy but learning to write good code is not. Writing good code is an art and also an important differentiating factor between an average programmer vs a good programmer. Since most of the programmers often look for inspiration and resource to improve their coding skill, I decide to share some of the good books which can help them to improve their coding. Since many universities, colleges and training courses only teach programming languages but not the art of coding, it still remains one of the self-learned skill. The internet has helped a lot to coders with several websites coming up to teach code, programming contest, helping to solve you programming interview questions and all, but IMHO, books are still vital for overall improvement. In this article, I am going to share some of the great books, written by both great author and great programmers, which can certainly help you to write good code and become a better programmer.


5 Books to Improve Coding Skill of Software Developers

Coding is an art and like many arts, it takes a lot of practice, study, and self-discipline to become a good coder. In my childhood, I have read that "books are your best friend, keep them near to you", and that has been proved absolutely correct in the world of Programming and Coding.

Programming is a challenging field with new development happening every day and knowledge quickly becomes obsolete, but good coding skill and self-discipline is something, which will never get obsolete and help you throughout your career. Books have helped me a lot and in this article, I am going to share 5 great books which will help you to improve your coding skill.


You might have read some of them already, but they are worth reading again. I have always learned new things while reading a good book like Clean Code twice. They are must read books for any Programmer who wants to become a good coder as well. They will also help you to do well in your Job, earn respect from peers and seniors, and also do well in job interviews.


1) Clean Code by Uncle Bob Martin
Clean code is one of the best books for java programmer but any programmer can benefit from it. This book will help you to write better code.This book teaches you about code smell, function and data structure, object-oriented design principles, design patterns. Uncle Bob Martin who himself is a great programmer has done a tremendous job of imparting his year of experience in simple words. The title "Clean Code" aptly justifies advice, best practices given to the programmers in this book. If you have to choose  just one book then pick the clean code.

Best book to learn Coding in Java




2) Working Effectively With Legacy Code
This is the one book I recommend to every Programmer who codes. Since development and maintenance are primary jobs of software engineers, and a bad code is hard to maintain, but sometimes you have no choice but to live with that, this book will help you how to work effectively with legacy code. This is also from the Rober C. Martin Series, the same series where "Clean Code" and other good books like "Clean Coder" belongs.

Book to become good Coder




3) Refactoring to Patterns 1st Edition by Joshua Kerievsky
This is one of the rare books where you will find the best combination of theory and practice. Refactoring is a process to make your working code more beautiful and this book can help you there by leveraging already tried and tested patterns of software development world. This is one of the best books to learn how and when to use design patterns. Java developers have added advantage because examples are given in Java, but it's not a big problem for C++, Scala or Python developer because examples are easy to follow and can be understood by anyone who knows how to read the pseudo code. Java's verbosity and English like language will also help a lot.

Good book to improve coding



4) Refactoring: Improving the Design of Existing Code
Refactoring is a process of making a working code beautiful, refactoring helps to improve the design of working code.It is also one of the important tricks of good programmers, more often than not good coders are also good on refactoring. This book will teach you both the art and science of refactoring code.It doesn't matter whether you are a Java programmer, C++ developer or a Python developer, every programmer can benefit from this book. This book  is a collective effort of some of the best authors in the programming world. List of authors includes Martin Fowler, Kent Beck, John Brant, William Opdyke, Don Roberts, and forward by Erich Gamma.

Best book to learn Coding




5) Beautiful Code: Leading Programmers Explain How They Think
This is one of the great books to improve your coding skill because it offers you an opportunity to see how expert programmer approach a problem, how the written code and how do they solve the problem and still able to keep their code beautiful. This book is a collection of case studies that tells how those expert programmers, which includes, Brian Kernighan, Jon Bentley (author of Programming Pearls), Tim Bray, Karl Fogel, Michael Feathers (author of Working Effectively with Legacy Code), and many more great authors and programmers. No matter, which programming language  you use for coding e.g. Java, C++, Python or Ruby, you will find something interesting in this book.

Great book to learn Coding skill


That's all about some of the great books to improve coding skill. Both beginners and experienced programmers can benefit from these books. In fact, these are the best resource for expert beginners which has experience but lack the knowledge to support those experience. It's a real shame if you have 10 years of experience but cannot write good code and believe me it happens.

If you are not writing code on the daily basis, not trying to improve, not introspecting than a number of years in the job will grow but your programming experience will not. You will struggle to write good code and good unit tests, which is one of the important traits of a good programmer. Never is too late, read some of this book to get back on track, if you are not sure which one to start, just read the Clean Code. 









Monday, 31 October 2016

10 Java Coding Tips Every Programmer Should Know

When you talk about Object Oriented Programming, the best and the most apt example that comes to the mind is Java. Developed by Sun Microsystems, Java leads the way in terms of cross platform programming language and developing application software. The reason Java has gained such a large fan base and unprecedented popularity is because the language deploys a very easy and efficient approach to perform various programming tasks and aid the developers.
Its simplicity can sometimes be a distraction and the highly experienced Java developers have always aimed a notch higher and have tried to explore the different possibilities that the language offers. Being a good Java developer is always within touching distance of any computer programming enthusiast, however; it is standing amongst the very bests that matters. 
Below are some tips that might help you grow as a Java developer and gain more knowledge about the language. 

1. Get the basics right

As Java offers so many features and options to the developers, people are sometimes lured into learning too many things in too little time. As a result of this, they get ‘bits and pieces’ knowledge of a few options that Java offers, but their basics hang on a loose thread. Trust me when I say this, Java is one programming language which is easy if you have paid attention to the simple basics, however; it can be frustrating if you get greedy and try to take the shorter route forward.

2. Don’t just read 

Well, if your sole purpose of learning Java is to clear the exam you have the next day, go ahead and mug up all the things that you can and you might just get the passing marks. However; if you are really serious about learning Java and getting better at it, the best way to do it is not by reading, but by implementing. Gain knowledge and then execute what you have learnt, in the form of code. You can never learn Java if you are not willing to get your hands dirty.

3. Understand your code and algorithm

Even if you are writing a simple code having a ‘if else’ statement, as a beginner, start by realizing the code on a piece of paper. The algorithm and the whole compiler process will look so meaningful once you understand the idea behind the code. Even for experts, the best way to solve a complex problem or to formulate an algorithm to solve a Java program is to break the problem into sub-parts and then try to devise a solution for each sub part. When you start getting the solutions right, you will get the confidence to work more.

4. Do not forget to allocate memory 

This tip is particularly useful for those who switch from C, C++ to Java. The memory allocation in Java using the ‘new’ keyword is a necessity as Java is a dynamic programming language. C, C++ does not explicitly have this feature, therefore you must take care while handling array and object declaration in Java. Not using the ‘new’ keyword will show a null pointer exception in the code.
Eg:
1
int array = new int [5];
Note the difference in array declaration in Java and C or C++.

5. Avoid creating useless objects

When you create an object in Java, you use up memory and processor speed from the system. Since object creation is incomplete without allocating memory to it, it is better to keep the object requirements under check and not create unwanted objects in the code.
Eg:
1
2
3
4
5
6
7
8
public class vehicles {
    public List getvehicles(){
        if(null == vehicles){ // this ensures that the object is initialised only when its required
            countries = new ArrayList();
        }
        return vehicles;
    }
}

6. Interface is better than Abstract class

There is no multiple inheritance in Java, and this will be spoon fed to you so many times while learning the language that you will probably never forget it for the rest of your life. However; the tip here in not to remember that there is no multiple inheritance in Java, but the fact that interface will come in handy if you want to implement something like multiple inheritance without using the extends keyword. Remember, in Java, when nothing goes your way, you will always have interface by your side. Abstract class does not always give programmers the liberty of having a variety of methods to work with, however; interface only have abstract methods therefore is does the job of abstract classes and has other advantages as well. 

7. Standard library is a bliss

The biggest advantage that Java has over its predecessors, from a programming point of view, is probably its rich set of standard library methods.  Using Java’s standard library makes the job of a programmer easy, more efficient and gives a well organised flow to the code. Further, operations can be performed easily on the methods specified in the library. 

8. Prefer Primitive classes over Wrapper Class

Wrapper classes are no doubt, of great utility, but they are often slower than primitive classes. Primitive class only has values while the wrapper class stores information about the entire class.  Further, since wrapper classes often deal with object values, comparing them like the primitive classes does not give desired results as it ends up comparing objects instead of values stored in it.
Eg:
1
2
3
4
5
6
int num_1 = 10;
int num_2 = 10;
Integer wrapnum_1 = new Integer(10);
Integer wrapnum_2 = new Integer(10);
System.out.println(num_1 == num_2);
System.out.println(wrapnum_1 == wrapnum_2);
Note: In the above example, the second print statement will not display true because wrapper class objects are getting compared and not their values.

9. Dealing with strings

Since Object oriented programming classifies String as a class, a simple concatenation of two strings might result into the creation of a new string object in Java which eventually affects the memory and speed of the system. It is always better to instantiate a string object directly, without using the constructor for this purpose.
Eg:
1
2
String slow = new String ("This string is making the system slow"); //slow instantiation
String fast = "This string is better"; //fast instantiation

10. Code, Code, Code

There is so much to learn about Java that you just cannot get over with this programming language and it keeps getting more interesting and amusing, however; it is important to maintain the interest within to learn and the hunger to get better. A programming language like Java can be learnt on our own and with great success, but the only thing that is required is continuous learning and coding to test what you have learnt.  Java is a lot like playing a sport; the more you sweat in the practice, less you bleed in the match.