Pages

Showing posts with label Coding Standards. Show all posts
Showing posts with label Coding Standards. Show all posts

Wednesday, February 26, 2014

Software Version Controlling Best Practices




Always use version controlling
Use version controlling/source control even if one developer exists. This issue brings change tracking and versioning of the application continuously. For multi developers, it brings more benefits like co-working on same files and fast codebase updates.

Do not commit halfdone work

Each commit should consist of a complete task (issue, bugfix, etc.). Partial commits may cause unfunctionality, crash of application or even compilation errors.

Full Update -> Build -> Run -> Full Commit rule
For having no trouble, a stable version controlling process should be applied. According to this process, you should full update the code, then build and run your application. If application runs correctly, you should commit all of your updated files. While committing, inspect all of your changed files and changes. If all team members apply this process, application will always continue to run and no one will prevent others work. 

Commit atomicity/granularity
Do not use version controlling system to backup each single file separately and do not commit hundreds of files after days or weeks of development. Commits should be atomic, and as a best practice, should include files which are related with only one task. Late commits also brings more conflicts.

Use descriptive commit messages
Commit messages are important for tracking changes. Descriptive commit messages help developers to control old versions of code within a functional context, instead of date and time only.

Don't commit generated files
Use "ignore" funcionalities of your version controlling tool to ignore commiting and updating of generated files (e.g. target folders, user settings, IDE generated files, generated classes after each build etc.) By doing this, you will not waste your time for managing those unstable/unimportant files.

Continuous integration
Use continuous integration along with version controlling. By doing that, perform automated builds and deploys to a specific location. Also, configure the tool to create a separate version number (with a predefined versioning algorithm, e.g. <major_changes>.<minor_changes>.<bug_fixes>) for each build. This will be useful to trace tests and deployments.

Use qualified version controlling tools and plugins (especially for merge)
Version controlling tool quality is also important. It must at least show changed files clearly, give ability to merge conflicted files easily and view old versions of files. Besides, it will be better to have a branching function to manage versions and and issue tracking system synchronization to manage issue-related code file matchings.

Use branches for testing and different lines of code
You should use different code branches for development, testing and also production. If a version of code is being tested, development should not continue on that branch. Development can continue on another branch and when a new version will be tested after fixing some bugs and adding new properties, a new test branch should be provided with a new version. When a stable test branch is reached, it may be released as a production branch.


You can also take a look at the below link for version controlling basics:
http://betterexplained.com/articles/a-visual-guide-to-version-control/


Wednesday, February 20, 2013

Layers of a Standard Enterprise Application





In a standard enterprise application which has a database and graphical UI (web or desktop), there are some typical layers which constitute the application. In this article we will mention those layers and give some instructions about them. 

The general diagram is as below:


There are some important properties about that diagram: 
There are vertical and horizontal layers. Vertical layers may be thought as general application service libraries which can paralelly work on all horizontal layers and independent from each other. However, a horizontal layer's subject of interest is only its neighbour (top and bottom) horizontal layers, and they work sequentially from top-to-bottom and bottom-to-top. Lastly, user can only interact with topmost horizontal layer. 

Horizontal layers:

  • Presentation: Every enterprise application has a UI, in fact graphical UI. This UI can be web or desktop based, which doesn't matter. The rule is simple. UI takes user action and sends it to the controller. And at the end it shows result taken from controller to the user. UI can be implemented according to MVC, MVP, MVVM or another approach.
  • Control: Handles business logic of the application. Takes info from user and sends it to DB layer (DAO or ORM framework) and vice versa. Abstraction type of controller may vary (a separate control and business layers for example)  according to the application parameters or development patterns (MVC, MVP, MVVM, ...) but the main idea remains the same.
  • Data Access: Database handling layer of the application. It may contain entity definitions, ORM framework or DB connection codes having SQL sentences, according to the abstraction decision. Its role is getting data from controller, performing data operation on database and sending results again to controller (if result exists). Database independence is a very important plus for this layer, which brings flexibility.

Vertical layers:

  • Security: Security is a general concept, which includes user authorization, user authentication, user role management, network or SQL injection attack prevention, data recovery etc but we grouped that items generally as "Security". Those issues must be handled for each horizontal layer if you want to have a fully secure software.
  • Logging: Logging is very important for maintenance and reporting in enterprise applications. An easily configurable, parameterized, readable, flexible and correctly implemented logging layer for all horizontal layers is very useful for both developers and users. 
  • i18n: i18n (internationalization) brings multiple language support and user interface text changing capability without rebuilding code. It may also have localization property which can handle number, currency and date formatting. So i18n provides flexibility on applications and should not be ignored.
  • Exception Handling: Exception handling may also be included in "Security" or "Logging" layers. We should not use only general exception classes or absorb all exceptions if we want to develop a quality software. We sometimes need our special exception classes with their specific behaviours for better security, logging and application performance.

If you design an architecture which has that layer structure considering software quality factors (which are told here), you will probably have a successful enterprise software application.

Wednesday, February 6, 2013

10 Groups of Software Quality Factors That Should Always Be Remembered





Flexibility and Extensibility: 
Flexibility is the ability of software to add/modify/remove functionality without damaging current system. Extensibility is the ability of software to add functionality without damaging system, so it may be thought as a subset of flexibility. Those functionality changes may occur acoording to changing requirements, or an obligation if development process is one of the iterative methods. Change is inevitable in software development and so, this is one of the most important properties of quality software.

Maintainability and Readability:
Maintainability is a little similar with flexibility but it focuses on modifications about error corrections and minor function modifications, not major functional extensibilities. It can be supported with useful interface definitions, documentations and also self-documenting code and/or code documentation. The more correct and useful documentation exists, the more maintainability can be performed.

Performance and Efficiency:
Performance is mostly about response time of the software. This response time should be in acceptable intervals (e.g. max. a few seconds), and should not increase if transaction count increases. And also, resources are expensive. Efficiency must be supported with resource utilization. As an exaggerated example, ability of performing a simple function only by using a 32 processor machine or 1 TB disk space is not acceptable. Optimal source/performance ratio must be aimed. 

Scalability:
A scalable system responds user actions in an acceptable amount of time, even if load increases. Of course more hardware may be added for handling increasing user transaction, but the architecture should not change while doing this. This is called vertical scalability. Ability of running on multiple, increasing count of machines is multiple processing. If the software can perform that type of processing, this is called horizontal scalability. A preffered scalable system should suit both of these methods.

Availability, Robustness, Fault Tolerance and Reliability:
A robust software should not lose its availabilty even in most failure states. Even if some components are broken down, it may continue running. Besides, even if whole application crashes, it may recover itself using backup hardware and data with fault tolerance approaches. There should always be B and even C, D .. plans. Reliability also stands for the integrity and consistency of the software even under high load conditions. So it is relevant with availability and scalability. An unreliable system is also unscalable.

Usability and Accessability:
User interfaces are the only visible parts of software according to the viewpoint of user. So, simplicity, taking less time to complete a job, fast learnability etc. are very important in this case. The most well known principle for this property is KISS (Keep It Simple Stupid). Simple is always the best. A usable software should also support different accessibility types of control for people with disabilities.

Platform Compatibility and Portability:
A quality software should run on as much various platforms as it can. So, more people can make use of it. In different contexts we may mention different platforms, this may be OS platforms, browser types etc. And portability is about adapting software that can run on different platforms, for being more platform compatible. In this sense, portability is also related with flexibility.

Testability and Managability:
Quality software requires quality testing. Source code should be tested with the most coverage and with the most efficient testing methods. This can be performed by using encapsulation, interfaces, patterns, low coupling etc. techniques correctly. Besides testability, a qualified software should be manageable after deployment. It may be monitored for e.g. performance or data usage status, or may enable developer to configure system easily. Creating a successful logging system is another very important issue about managability.

Security:
Security is a very important issue on software development, especially for web or mobile based ones which may have millions of users with the ability of remote accessing to system. You should construct a security policy and apply it correctly by leaving no entry points. This may include authorization and authentication techniques, network attack protections, data encryption and so on. all possible types of security leaks should be considered, otherwise one day only one attack may crash your whole applicaion and whole company.

Functionality and Correctness:
Functionality (or correctness) is the conformity of the software with actual requirements and specifications. In fact this is the precendition attribute of an application, and maybe not a quality factor but we wanted to point that as the last quality factor, for taking attention: Quality factors are not meaningful when we are talking about unfunctional software. First, perform desired functionality and produce correct software, then apply quality factors on it. If you can perform both paralelly, it is the best.

Thursday, December 13, 2012

10 Software Process Management Best Practices





Regardless of software process management type (waterfall, scrum, iterative etc.), there are some main rules which should be considered about software process management. In this post we will mention most important of these practices theorically:



1. Define roles and tasks of team members:
For productivity, roles of team members should be defined clearly. These roles may be project manager, team lead, develeoper, tester etc. Furthermore, authorizations and responsibilities of these roles should be defined very clearly. Task-assignment based development should also be applied for avoiding redundant effords and chaos. 

2. Define meeting types:
Meetings are very important if we are talking about software process management and should be defined in detail (meeting participants, context, average duration etc.). Team members should also obey meeting rules. This will bring more productive meeting and development process, and will avoid losing time unnecessarily.

3. Define documentation strategy:
Every single software process has a documentation strategy, even agile or extreme methods (backlogs, lessons learned info, bug items etc.). These documentation types should be defined clearly (document physical properties, standard sections, document update period, version numbering etc.) for consistency, understandability and more effective software production. 

4. Define software quality metrics and measure them:
There are so many metric types (line of code, cyclomatic complexity etc.) in software world. According to the properties of your software type, some of these should be chosen to measure quality and growth of code. These info may be discussed periodically and production quality will be increased after assessments.

5. Perform issue/requirement tracking:
Requirement management or issue tracking is one of the key points in software development. They determine the scope of software, also supports a traceability base for functional tests. Those issues/requirements are preferred to be saved and managed with useful tools which have more features than text editing.

6. Perform version controlling:
Version controlling is also crutial in production. This should include code and other documents. It will support co-working on code, returning to older versions of code and will ease versioning and dependency management. Versioning strategy (version numbering,versioning periods etc.) should also be determined clearly to obtain consistency.

7. Perform testing:
Testing is one of the main phases of software development. Unit testing must be performed for every type of software, except a few exceptions like some user interface code. Other testing types (system, user, integration etc.) should be defined clearly and applied consistently as defined. This will increase quality of production and decrease bugs.

8. Perform dependency management:
As software projects grow, more external libraries (jar, dll, ...) or projects (external projects or internal company projects) are included. If those items are added to projects imprecisely, later updates or version changes will bring chaos and so much time consumption. Dependency management strategies and tools should be used for efficient productivity.

9. Perform code reviews frequently: 
Code review brings high quality code. First of all it enforces developer to produce better code, because it will be controlled by others. Besides, a junior developer will learn better coding quickly by corrections of senior developers. So, code review is a partial type of pair programming and it enhances productivity.

10. Save "lessons learned" info for your projects:
Even if there are experienced staff in projects, there may be unforeseen events which may obstruct or retard development process. This can be a complex item configuration, error, production experience etc. Those happenings are highly preferred to be written in "lessons learned" documents and shared in public locations. This will avoid recurrence of time loss and provide more productive software.

Friday, November 30, 2012

Software Unit Testing and Best Practices





Software Unit Testing is about testing of individual units of source code. Those units are generally methods and they are grouped by class names (called as Test Case). 


For example, if you have an XYZUtility class which having methodA, methodB, methodC methods, you will potentially have an XYZUtilityTestCase class having methodATest, methodBTest and methodCTest tests.

Unit tests must cover as much code as they can while running, but it is not the primary purpose. Code coverage is prefferred to be high as a result but the main purpose of the unit tests are:
  • Testing output of a function with specific inputs. Those inputs must include boundary (min/max) values and potential exceptional values (divide by 0 etc.). And the inputs are also preffered to be chosen for covering all condition cases of the method.
  • Documenting the software. One of the self-documenting code development techniques is unit testing. It shows usage of the code section.
  • Increasing modularity, flexibility and extensibility of the code along with concerning the developer with the interface before implementation, in Test Driven Development (TDD) approach.
There are also 5 important properties for unit tests that must be obeyed according to Andy Hunt's Pragmatic Unit Testing book.

  • Automatic
Unit test results (pass/fail) must be controlled automatically with tools. And generally more than one tests are need to be run together. A test should not have a manual step which stops execution of all tests.
  • Repeatable
A unit test must be repeatable. In other words, if it passes on a certain version of code, it must always pass with that code or if it fails on a certain version of code, it must always fail with that code. Database changes or other external services or files etc. should not change the result of the unit test.
  • Independent
Unit test results must be independent of other unit tests. If a unit test result changes after changing the running order or other environment change (database data etc.), it can not be called as a unit test.
  • Thorough
A unit test must control every condition as it can (all possibilities, exceptions, boundaries ...). Its code coverage must be as much as it can and controlled conditions are preferred to be logical and functional.
  • Professional
Unit test code must obey coding standards of the project which it belongs to, because it also is  a professional code. Furthermore, it was stated before that unit test is another way of self-documenting code. Clean and understandable unit test code will bring better documentation.

As a last word, for providing repeatable and independent unit tests, using mock objects is a good practice. Mock objects replaces the external sources (database, services, etc.) and returns predefined results. A good object oriented design having required amount of interfaces will  simplfy the creation of mock objects. You can also use some API's like EasyMock or Mockito. 


Thursday, October 18, 2012

Best Must-Read Books for Software Engineers





Here are the CodeBuild selection of must-read software engineering books. Books are grouped according to their content with some description.

  • Reference Books
These Robert C. Martin and Gang of Four books are very fundamental OOP resources for every software engineer.

    
  • Coding Perfection
These Steve McConnell, Robert C. Martin and Joshua Bloch books are very helpful with increasing your coding skills.

      

  • Refactoring and Patterns
Refactoring and patterns are very important issues of OOP, which brings quality and maintainability. These Martin Fowler and Joshua Kerievsky books are maybe the best references about this issue.

          

  • Pragmatic Programming
Andrew Hunt's and David Thomas's "pragmatic" approach to programming brings very important viewpoints to software engineering.

     

  • Project Management
There are many project management books in the market but  Frederick P. Brooks Jr. and Tom DeMarco presents very impressive important viewpoints to project management.


     

Thursday, September 27, 2012

5 Common Automized Software Quality Metrics (with Pros & Cons)





1. Source Lines of Code (SLOC)
Counting lines of code is probably the most simple method. It mostly indicates the scale of the software and gives an input for project growth and planning. For example, if we get SLOC count once a month, we may sketch a graph of project growth. Of course this is not reliable due to refactoring and design phases but may give a viewpoint.

SLOC may be counted as Source Logical Line of Code (SLLOC) for better info. Logical code lines does not include empty lines, one char brackets and comment lines. You can easily calculate SLLOC using tools like Metrics. 

Line of code should not be used for evaluating developer performance. This may cause duplicate, unmaintainable and unprofessional code.


2. Bugs per code_section/module/time_period
Bug tracking is essential for better testing and faster maintainability. If bugs are tracked, bugs per code section, module or specific time period (day, week, month etc.) may be calculated easily by reporting tools (e.g. Mantis). If this value is obtained, bug causes may be noticed and intervened early.

Bug count may be used as one of the inputs of evaluating developer performance, but attention must be paid. If it is most important evaluation method, software developers and testers may become enemies. In a productive company, all employees must be coherent with each other.

For better evaluation, bugs may be classified as low, medium, high etc. for weighting, because their importance and resolving costs are not the same. 


3. Code Coverage
Code coverage states the degree to which the source code of a program has been tested. Automaticity of code coverage calculation is a plus. There are so many tools which perform that operation (e.g. Cobertura). 

Code coverage does not represent the whole quality of unit tests, but may give some info about test coverage. It may be used as a software metric together with a few other test metrics. Also unit test codes, integration test scenarios and results should be reviewed frequently.

4. Design/Development Constraints
There are so many design constraints and principles for software development. Some of them are:
  • Class/method length,
  • Number of methods/attributes in a class,
  • Method/constructor parameter counts,
  • Magical number, string usage in code files,
  • Comment lines percentage etc.
These are important for code maintainability and readability. Development teams may choose a few (or all) of those metrics and follow them with automized tools (like maven pmd plugin). This will raise the quality of produced software.


5. Cyclomatic Complexity
We separated cyclomatic complexity from other design/development constraints because its concept is a bit different. Cyclomatic complexity is about the detailed implementation and code execution. It also may be calculated automatically with tools like pmd.

It is calculated as "the count of the number of linearly independent paths through a source code section". For example, if there are a path diagram of a source code section as below:



Cyclomatic Complexity = E(edges) - N(nodes) + 2P (exit nodes)
So, Cyc.Cmp. = 8 - 7 + 2*1 = 3

You can also see that there are 3 different paths from leftmost node to rightmost node. This value can be calculated especially for methods, using the whole method source as the execution path. Some upper limit numbers (6, 8 or 10 etc.) may be defined according to the project type.

Only one metric does not detect the quality of your whole project or solve everything. If you use more metrics, you will have more viewpoints about the quality of your project. 


Monday, June 25, 2012

20 Subjects Every Software Engineer Should Know





Here are the most important subjects for software engineering, with brief explanations:

1.Object oriented analysis & design: For better maintainability, reusability and faster development,  the most well accepted approach, shortly OOAD and its SOLID principals are very important for software engineering.

2.Software quality factors: Software engineering depends on some very important quality factors. Understanding and applying them is crucial.

3.Data structures & algorithms: Basic data structures like array, list, stack, tree, map, set etc. and useful algorithms are vital for software development. Their logical structure should be known.

4. Big-O notation: Big-O notation indicates the performance of an algorithm/code section. Understanding it is very important for comparing performances. 

5.UML notation: UML is the universal and complete language for software design & analysis. If there is lack of UML in a development process, it feels there is no engineering.

6.Software processes and metrics: Software enginnering is not a random process. It requires a high level of systematic and some numbers to monitor those techniques. So, processes and metrics are essential.

7.Design patterns: Design patterns are standard and most effective solutions for specific problems. If you don't want to reinvent the wheel, you should learn them.

8.Operating systems basics: Learning OS basics is very important because all applications runs on it. By learning it, we can have better vision, viewpoints and performance for our applications.

9.Computer organization basics: All applications including OS requires a hardware for physical interaction. So, learning computer organization basics is vital again for better vision, viewpoints and performance.

10.Network basics: Network is related with computer organization, OS and the whole information transfer process. In any case we will face it while software development. So, it is important to learn network basics.

11.Requirement analysis: Requirement analysis is the starting point and one of the most important parts of software engineering. Performing it correctly and practically needs experience but it is very essential.

12.Software testing: Testing is another important part of software engineering. Unit testing, its best practices and techniques like black box, white box, mocking, TDD, integration testing etc. are subjects which must be known.

13.Dependency management: Library (JAR, DLL etc.) management, and widely known tools (Maven, Ant,  Ivy etc.) are essential for large projects. Otherwise, antipatterns like Jar Hell are inevitable.

14.Continuous integration: Continuous integration brings easiness and automaticity for testing large modules, components and also performs auto-versioning. Its aim and tools (like Hudson etc.) should be known.

15.ORM (Object relational mapping): ORM and its widely known implementation Hibernate framework is an important technique for mapping objects into database tables. It reduces code length and maintenance time.

16.DI (Dependency Injection): DI or IoC (Inversion of Control) and its widely known implementation Spring framework makes life easy for object creation and lifetime management on big enterprise applications.

17.Version controlling systems: VCS tools (SVN, TFS, CVS etc.) are very important by saving so much time for collaborative works and versioning. Their logical viewpoint and standard cammands should be known. 

18.Internationalization (i18n): i18n by extracting strings into external files is the best way of supporting multiple languages in our applications. Its practices on different IDEs and technologies must be known.

19.Architectural patterns: Understanding architectural design patterns (like MVC, MVP, MVVM etc.) is essential for producing a maintainable, clean, extendable and testable source code.

20.Writing clean code: Working code is not enough, it must be readable and maintainable also. So, code formatting and readable code development techniques are needed to be known and applied.

Wednesday, March 21, 2012

10 Best Practices of Code Commenting & Formatting





Code commenting and formatting are all about code understandability. Code understandability is very relevant to code maintainability. So, small details about programming may help maintainability. In this context, some practices about commenting and formatting will be told here:

Commenting

Comments may be thought as part of the code, so they are really important. E.g. a commentless code library will be useless in a short time with high probability. Even though there are some approaches which suggests self-documenting code over code documentation, we suggest (self-documenting code + code documentation).
  1. Use comments "as required". 
    • Unnecessary over-commenting in each line will reduce readability:
      • int count = 0; // assigning zero as initial value to the count (?!?)
    • Lack of commenting will increase maintenance time. Also, variable/method names should be understandable and self commenting
      • int s = sqrt(v1) + v2 / v3 + fread(s). getChar(0)  //(?!?)
      • List<int> getVal(int val, int len, String op) //(?!?)
  2. Don't write uncorrect comments. Uncorrect explanations are worse than no-comment. 
  3. Write comments for variables which are important and non-selfdocumenting.
  4. Writing comments (e.g. JavaDoc declaration) for all public methods is a good practice. Of course, these comments should be "really necessary" and "as required".
  5. Document "gotcha"s and "todo"s instantly when detected. These items may be remembered for that day but may not for tomorrow when not documented, so a buggy code will be inevitable.
Formatting

Formatting rules can be detected automatically by most tools (e.g. maven checkstyle) and applied automatically by most IDEs (e.g. Eclipse Code Formatter ctrl+shift+f). But there may be little differences between company formatting rules, so these tools should be configured before applying formatting.
  1. Use brackets consistently. You may choose opening a bracket at the end of the current line or at the beginnning of the new line. Choose one of them and use consistently in the whole application.
  2. Use blank lines consistently and as required. Blank lines may be used for separating  code lines or line groups semantically for readability. E.g. 3 blank lines at the end of a method, no-blanks on whole code or one or two blank lines between each line of code reduces readability and not good for eye pleasure.
  3. Pay attention for indentation. Correct indentation for grouping statements is as important as using brackets and blank lines.
  4. Character count of a line should be limited for readability. This limit is generally 80 for most developers, but may change a little due to some other development parameters. 
  5. Using space chars in code should also be consistent in whole application. Generally, situations below are suitable for using spaces:
    • Between operators and operands: 
      • a += b , c = 0; (a == b)
    • Between statement keywords and brackets: 
      • if (value) {, public class A { 
    • After ';' char in loops: 
      • for (int i = 0; i < length; i++) 
    • Between type casters and operands: 
      • (int) value , (String) value


Monday, February 20, 2012

15 Best Practices of Variable & Method Naming






  1. Use short enough and long enough variable names in each scope of code. Generally length may be 1 char for loop counters, 1 word for condition/loop variables, 1-2 words for methods, 2-3 words for classes, 3-4 words for globals.
  2. Use specific names for variables, for example "value", "equals", "data", ... are not valid names for any case.
  3. Use meaningful names for variables. Variable name must define the exact explanation of its content.
  4. Don't start variables with o_, obj_, m_ etc. A variable does not need tags stating that it is a variable.
  5. Obey company naming standards and write variable names consistently in application: e.g. txtUserName, lblUserName, cmbSchoolType, ... Otherwise readability will reduce and find/replace tools will be unusable.
  6. Obey programming language standards and don't use lowercase/uppercase characters inconsistently: e.g. userName, UserName, USER_NAME, m_userName, username, ...
    • For example for Java, 
      • use Camel Case (aka Upper Camel Case) for classes: VelocityResponseWriter
      • use Lower Case for packages: com.company.project.ui
      • use Mixed Case (aka Lower Camel Case) for variables: studentName
      • use Upper Case for constants : MAX_PARAMETER_COUNT = 100
      • use Camel Case for enum class names and Upper Case for enum values.
      • don't use '_' anywhere except constants and enum values (which are constants).
  7. Don't reuse same variable name in the same class in different contexts: e.g. in method, constructor, class. So you can provide more simplicity for understandability and maintainability.
  8. Don't use same variable for different purposes in a method, conditional etc. Create a new and different named variable instead. This is also important for maintainability and readability.
  9. Don't use non-ASCII chars in variable names. Those may run on your platform but may not on others.
  10. Don't use too long variable names (e.g. 50 chars). Long names will bring ugly and hard-to-read code, also may not run on some compilers because of character limit.
  11. Decide and use one natural language for naming, e.g. using mixed English and German names will be inconsistent and unreadable.
  12. Use meaningful names for methods. The name must specify the exact action of the method and for most cases must start with a verb. (e.g. createPasswordHash)
  13. Obey company naming standards and write method names consistently in application: e.g. getTxtUserName(), getLblUserName(), isStudentApproved(), ... Otherwise readability will reduce and find/replace tools will be unusable.
  14. Obey programming language standards and don't use lowercase/uppercase characters inconsistently: e.g. getUserName, GetUserName, getusername, ...
    • For example for Java, 
      • use  Mixed Case  for method names: getStudentSchoolType 
      • use  Mixed Case  for method parameters: setSchoolName(String schoolName)
  15. Use meaningful names for method parameters, so it can documentate itself in case of no documentation.

Tuesday, January 31, 2012

15 Best Practices for Exception Handling






  1. Don't manage business logic with exceptions. Use conditional statements instead. If a control can be done with if-else statement clearly, don't use exceptions because it reduces readability and performance  (e.g. null control, divide by zero control). .
  2. Exception names must be clear and meaningful, stating the causes of exception.
  3. Throw exceptions for error conditions while implementing a method. E.g. if you return -1, -2, -3 etc. values instead of FileNotFoundException, that method can not be understand.
  4. Catch specific exceptions instead of the top Exception class. This will bring additional performance, readability and more specific exception handling.
  5. Null control with conditionals is not an alternative to catching NullPointerException. If a method may return null, control it with if-else statement. If a return may throw NullPointerException, catch it.
  6. Try not to re-throw the exception because of the price. Bu if re-throwing had been a must, re-throw the same exception instead of creating a new exception. This will bring additional performance. You may add additional info in each layer to that exception.
  7. Define your own exception hierarchy by extending current Exception class (e.g. UserException, SystemException and their sub types) and use them. By doing this you can specialize your exceptions and define a reusable module/layer of exceptions.
  8. Use types of exceptions clearly. Fatal: System crash states. Error: Lack of requirement. Warn: Not an error but error probability. Info: Info for user. Debug: Info for developer. 
  9. Don't absorb exceptions with no logging and operation. Ignoring exceptions will save that moment but will create a chaos for maintainability later.
  10. Don't log the same exception more than once. This will provide clearness of the exception location.
  11. Always clean up resources (opened files etc.) and perform this in "finally" blocks.
  12. Exception handling inside a loop is not recommended for most cases. Surround the loop with exception block instead.
  13. Granularity is very important. One try block must exist for one basic operation. So don't put hundreds of lines in a try-catch statement.
  14. Produce enough documentation for your exception definitions (at least JavaDoc).
  15. Giving a number/code for each different exception message is a good practice for documentation and faster communication.

Thursday, December 29, 2011

A Look Into Java Annotations & A Real World Spring Example





An "annotation" is a type of programminglanguage definition and used as a “marker”. They can be thought as commentlines which programming language engine can understand. They don’t directlyaffect program execution but affect indirecly if wanted.

Definition

An annotation is defined with @interface keyword and is similar withan interface. It has attributes which are defined like interface methods.Attributes can have default values. Let’s define an annotation named “Page”,which defines UI pages of an application:

public @interface Page {
    int    id();
    String url();
    String icon()default "[none]";
    String name();default "[none]";
}

Usage

Annotations are widely used to informcompiler or compile-time/runtime/deployment-time processing.
Usage ofan annotation is simpler:

@Page(id=1, url=”studentView”, icon=“icons/student.png”,name=”Students”)
public class StudentWindow extends Window { … }

Annotationscan also be defined for methods and attributes:

@AnAnnotation
public String getElementName() {…}

@AnAnnotation(type=”manager”, score=3)
public int income;

Examples

1)   Reflection/code generation:

Methods havinga specific annotation can be processed at runtime:

public @interface MyAnnotation { ... }
public class TestClass {
    @MyAnnotation
    public static method1() { ... }
    @MyAnnotation
    public static method2() { ... }
    @MyAnnotation
    public static method3() { ... }
}

public static void main(String[] args) {
    for (Method method : Class.forName("TestClass").getMethods()) {
        if (method.isAnnotationPresent(MyAnnotation.class)) {
            // do what you want
        }
    }
}

2)   Spring bean configuration (this section requires Spring bean configurationknowledge):

Let’s useour “Page” annotation again:

package com.cmp.annotation;
public @interface Page {
    int    id();
    String url();
    String icon() default "[none]";
    String name(); default "[none]";
}

Say thatwe have a few classes having @Page annotation in a package:

@Page(id=1, url=”studentView”, icon=“icons/student.png”, name=”Students”)
public class StudentWindow extends Window { … }

If wedefine a bean configuration as below in a Spring application-context.xml file, Springwill create class instances “which has @Page annotation” placed in “givenpackage”.

<context:component-scan base-package="com.cmp.ui" annotation-config="true">
<context:include-filter type="annotation" expression="com.cmp.annotation.Page"/>
context:component-scan>

So, we havebeen enforced Spring to instantiate only a selection of classes at runtime.


For more detailed info about annotations, please refer to: