Featured

Tips for clean coding in java

I am required to read quite a bit of code written by other people, and over the years I’ve found that there are some problems that tend to recur again and again. The idea with this blog entry is to write up some tips , in the hope that it can help people out there who struggle to write clean code.

These are the tips for clean coding or good coding.

 

Keep classes small

So far you’ve created a few classes. After generating getter/setter pairs for even the small number (by the standards of a real-world Java class) of attributes, the Person class has 150 lines of code. At that size, Person is a small class. It’s not uncommon (and it’s unfortunate) to see classes with 50 or 100 methods and a thousand lines or more of source. Some classes might be that large out of necessity, but most likely they need to be refactored. Refactoring is changing the design of existing code without changing its results. I recommend that you follow this best practice.

In general, a class represents a conceptual entity in your application, and a class’s size should reflect only the functionality to do whatever that entity needs to do. Keep your classes tightly focused to do a small number of things and do them well.

Keep only the methods that you need. If you need several helper methods that do essentially the same thing but take different parameters (such as the printAudit() method), that’s a fine choice. But be sure to limit the list of methods to what you need, and no more.

Name methods carefully

A good coding pattern when it comes to method names is the intention-revealing method-names pattern. This pattern is easiest to understand with a simple example. Which of the following method names is easier to decipher at a glance?

  • a()
  • computeInterest()

The answer should be obvious, yet for some reason, programmers have a tendency to give methods (and variables, for that matter) small, abbreviated names. Certainly, a ridiculously long name can be inconvenient, but a name that conveys what a method does needn’t be ridiculously long. Six months after you write a bunch of code, you might not remember what you meant to do with a method called compInt(), but it’s obvious that a method called computeInterest(), well, probably computes interest.

 

Omit needless code!

It’s quite common to find code that’s commented out, but still hanging around. This is mainly bad because it bloats the code unnecessarily. People seem to do this because they want to have the possibility to bring the code back, either because they are writing an alternative they are not sure about, because they don’t dare to delete it. However, in nearly all cases there is no real reason to keep such code around. You should be using version control, and that means you could always find any deleted code again.

Also, since this code is no longer compiled or executed there is no real difference between commenting it out or deleting it. You’ve still made the change. The difference is that now it’s quite likely that this code will slowly move out of sync with the code around it, so that by the time you find you want it again it will no longer work. That actually makes the code dangerous, because it tempts you to include code without understanding what it does. (If you really understood it you could retype it quite quickly even if it was deleted.)

Of course, commenting out code while you are working on the code is fine. I do that a lot. However, I never check in code that is commented out, and whenever I find such code I delete it, without asking anyone or telling them. If they wanted the code they shouldn’t have commented it out. And it will be in the version history, anyway.

I chose this topic because i want to write code in a clean, efficient and faster way. I also chose this topic because since we will be studying it in the CS-343 class , why not learn ahead to get much more understanding on it.

Even though i knew some things about clean coding, i learned a lot. Some stuff i didn’t know where there. With these materials i have gain from other blogs or website added to my little knowledge of clean coding , i hope it will help me develop better coding in a clean, efficient and faster way.

 

I got the above information from this link ::: https://www.ibm.com/developerworks/library/j-perry-writing-good-java-code/index.html 

And

http://www.garshol.priv.no/blog/105.html

Advertisements

gradle (#443)

I chose this article because i wanted to get more understanding on it. also because of the costume logic  it allows in the language, be it java or groovy.

first let’s understand what gradle is all about. gradle is a general purpose build system. It comes with a rich build description language based on Groovy. Gradle supports build-by-convention principle but it is very flexible and extensible. It derives all the best integrates well with Ivy, Ant and Maven.

Gradle combines approaches of Ant and Maven providing a middle ground between configuration and convention. Gradle is compatible with both, as you can use the existing Ant tasks and Maven repositories. Projects are auto-configured with sensible defaults, but the configuration can be easily changed.

Unlike Ant and Maven which use XML for scripting, Gradle uses Groovy, a Domain Specific Language that’s a subset of Java with plenty of syntactic sugar. That makes the scripts much more concise and expressive. Learning Groovy is not required as you can use plain Java, but it helps.

All the project build configuration goes into build.gradle file, an executable Groovy script which runs when you issue gradle someTask command.

why gradle?

according to dr.dobb’s, if you’ve ever dealt with build systems, frustration may be one of the feelings that comes up when thinking about the challenges you’ve faced. Shouldn’t the build tool naturally help you accomplish the goal of automating your project? Instead, you had to compromise on maintainability, usability, flexibility, extendibility, or performance.

Let’s say you want to copy a file to a specific location when you’re building the release version of your project. To identify the version, you check a string in the metadata describing your project. If it matches a specific numbering scheme (for example, 1.0-RELEASE), you copy the file from point A to point B. From an outside perspective, this may sound like a trivial task. If you have to rely on XML, the build language of many traditional tools, expressing this simple logic becomes fairly difficult. The build tool’s response is to add scripting functionality through nonstandard extension mechanisms. You end up mixing scripting code with XML or invoking external scripts from your build logic. It’s easy to imagine that you’ll need to add more and more custom code over time. As a result, you inevitably introduce accidental complexity, and maintainability goes out the window. Wouldn’t it make sense to use an expressive language to define your build logic in the first place?

Here’s another example. Maven follows the paradigm of convention-over-configuration by introducing a standardized project layout and build lifecycle for Java projects. That’s a great approach if you want to ensure a unified application structure for a green-field project — a project that lacks any constraints imposed by prior work. However, you may be the lucky one who needs to work on one of the many legacy projects that use different conventions. One of the conventions Maven is very strict about is that one project needs to produce one artifact, such as a JAR file. But how do you create two different JAR files from one source tree without having to change your project structure? Just for this purpose, you’d have to create two separate projects. Again, even though you can make this happen with a workaround, you can’t shake off the feeling that your build process will need to adapt to the tool, not the tool to your build process.

from my research i came to get more understanding of gradle, how to use if it efficiently and what it can contribute to my java project when dealing with testing. This gradle will really help me in my java project involving testing.

 

 

references: http://www.drdobbs.com/jvm/why-build-your-java-projects-with-gradle/240168608

https://gradle.org/install/

https://www.tutorialspoint.com/gradle/gradle_installation.htm

Mock Testing #443

I chose this topic just to get better understanding of it. It was a little bit confusing when studing it in class, with the subs and dummy.

firstly, through my research, mocks or mocks objects are pre-programmed with expectations which form a specification of the calls the are expected to receive.

Why use mocks?

  • Isolate code under test; less fragile tests
  • Difficult to set up dependencies
  • Verify interaction between objects
  • Side effects (sending emails, launching missiles)
  • Abnormal situations (network outages, disk full)
  • Multiple dev streams (actual class doesn’t exist)
  • Non-deterministic results (timezones)
  • Real code too slow (trips to database)
  • Real code interacts with user (i.e. UI)

 

an example of mock

//setup

var mockCustomer = new mock<ICustomer>():

mockCustomer.Setup(cust => cust.Name).Returns(“Elvis”);

//execute

var customer = mockCustomer.Ojbect;

var customerName = customer.Name;

//verify

Assert.AreEqual(“Elvis”, customerName);

mockCustomer.VerifyGet(cust => cust.Name, Times.AtLeastOnce());

 

Test lifecycle with mocks:

setup –> execute –> verify

  • This is actually the set of steps that *every* unit test should follow, but with mocks it is a little different.
  • Organizing your tests in this way helps clarity. If you mix up the steps it is harder to see what is going on.

 

Maintainability Concerns

  • Things like dependency injection, if not applied correctly, can spread dependency knowledge throughout the app
  • Interfaces are not DRY
  • Exposing what should be private as virtual/protected/public/internal
  • It requires discipline to create an appropriate design that allows for mocking and for good maintainability

Creating mock objects with mockito

 

According to vogella,

Mockito provides several methods to create mock objects:

  • Using the static mock() method.
  • Using the @Mock annotation.

If you use the @Mock annotation, you must trigger the creation of annotated objects. The MockitoRuleallows this. It invokes the static method MockitoAnnotations.initMocks(this) to populate the annotated fields. Alternatively you can use @RunWith(MockitoJUnitRunner.class).

The usage of the @Mock annotation and the MockitoRule rule is demonstrated by the following example.

import static org.mockito.Mockito.*;

public class MockitoTest  {

    @Mock
    MyDatabase databaseMock; 

    @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); 

    @Test
    public void testQuery()  {
        ClassToTest t  = new ClassToTest(databaseMock); 
        boolean check = t.query("* from t"); 
        assertTrue(check); 
        verify(databaseMock).query("* from t"); 
    }
}
Tells Mockito to mock the databaseMock instance
Tells Mockito to create the mocks based on the @Mock annotation
Instantiates the class under test using the created mock
Executes some code of the class under test
Asserts that the method call returned true
Verify that the query method was called on the MyDatabase mock

 

After the research, i got a better understanding of mock.Mock objects are a powerful tool that you should have in your testing toolbox. Injecting mock objects requires some design considerations. Luckily this also leads to better code .

references: http://en.wikipedia.org/wiki/Solid_%28object-oriented_design%29

http://bit.ly/7WWq9

http://www.vogella.com/tutorials/Mockito/article.html

Test Automation

The reason of this area of research was to know why test Automation is better than other kind of testing and also get to know more about it.

First, Automation, is the use of tools and strategies that reduce human involvement or interaction in unskilled, repetitive or redundant tasks.

The automated test lifecycle methodology 

1.outline the potential benefits and test tool proposal

2.test tool evaluation and selection

3.Steps necessary to outline automated testing to the project

4.Identifies the test procedure standards, defines the tests, defines development standard

5.Test plans are executed

6.This is done throughout the lifecycle

 

why automation?

Verification – developed software matches the requirements

Validation – it is what the organisation wanted

Defects and failures – incorrectly setup environments  or wrong version of software being deployed – human error –  bug or malfunction – system malfunctioning or failing

Compatible – so that new software deployed wont mess up any existing apps

According to smartbear, Every software development group tests its products, yet delivered software always has defects. Test engineers strive to catch them before the product is released but they always creep in and they often reappear, even with the best manual testing processes. Test Automation software is the best way to increase the effectiveness, efficiency and coverage of your software testing.

Manual software testing is performed by a human sitting in front of a computer carefully going through application screens, trying various usage and input combinations, comparing the results to the expected behavior and recording their observations. Manual tests are repeated often during development cycles for source code changes and other situations like multiple operating environments and hardware configurations. An automated testing tool is able to playback pre-recorded and predefined actions, compare the results to the expected behavior and report the success or failure of these manual tests to a test engineer. Once automated tests are created they can easily be repeated and they can be extended to perform tasks impossible with manual testing. Because of this, savvy managers have found that automated software testing is an essential component of successful development projects.

The advantages of automation

Reliable: carries out the same operations – eliminating human error
Reusable: can reuse tests on different versions of an application
Better Quality Software: can run more tests in less time with fewer resources – good coverage
Fast: run tests significantly faster than human users.
Cost Reduction: number of resources for tests are reduced.

Replaces: manually mundane and labor intensive tasks

 

 

In conclusion, i learned that testing in automation tests for ever-shrinking schedules and minimal resources, i got the understanding of the automated software testing lifecycle and also the usefulness of it. I also got to know, it has a zero risk of missing out a pre-decided test. Once the test becomes a part of continuous integration, it will run without someone having to remember to run it.

 

References :

http://www.my-project-management-expert.com/software-application-testing.html

https://smartbear.com/learn/automated-testing/what-is-automated-testing/

https://smartbear.com/learn/automated-testing/

black box and white box testing #443

I picked this article just to get more understanding on black box and white box testing. Also wanted to know the differences between them.

White box testing is testing where we use the info available from the code of the component to generate tests.

This info is usually used to achieve coverage in one way or another – e.g.

  • Code coverage
  • Path coverage
  • Decision coverage

Debugging will always be white-box testing

 

White box testing types

 

3 Main White Box Testing Techniques:

  1. Statement Coverage
  2. Branch Coverage
  3. Path Coverage

 Statement coverage:

In a programming language, a statement is nothing but the line of code or instruction for the computer to understand and act accordingly. A statement becomes an executable statement when it gets compiled and converted into the object code and performs the action when the program is in a running mode.

Hence “Statement Coverage”, as the name itself suggests, it is the method of validating whether each and every line of the code is executed at least once.

Branch Coverage:

“Branch” in a programming language is like the “IF statements”. An IF statement has two branches: True and False.

So in Branch coverage (also called Decision coverage), we validate whether each branch is executed at least once.

In case of an “IF statement”, there will be two test conditions:

  • One to validate the true branch and,
  • Other to validate the false branch.

Hence, in theory, Branch Coverage is a testing method which is when executed ensures that each and every branch from each decision point is executed.

 Path Coverage

Path coverage tests all the paths of the program. This is a comprehensive technique which ensures that all the paths of the program are traversed at least once. Path Coverage is even more powerful than Branch coverage. This technique is useful for testing the complex programs.

Black box testing is also called functional testing. The main ideas are simple:

1.Define initial component state, input and expected output for the test.

2.Set the component in the required state.

3.Give the defined input

4.Observe the output and compare to the expected output.

  • black-box is based on requirements and functionality, not code
  • tester may have actually seen the code before (“gray box”)but doesn’t look at it while constructing the tests
  • often done from the end user or OO client’s perspective
  • emphasis on parameters, inputs/outputs (and their validity)

Types of Black Box Testing

  • requirements based
  • positive/negative – checks both good/bad results
  • boundary value analysis
  • decision tables
  • equivalence partitioning – group related inputs/outputs
  • state-based – based on object state diagrams
  • compatibility testing
  • user documentation testing
  • domain testing

 

Black Box vs. White Box testing

We can contrast the two methods as follows:

  • White Box testing

–Understanding the implemented code.

–Checking the implementation

–Debugging

  • Black Box testing

–Understanding the algorithm used.

–Checking the solution – functional testing

This article will really help me in the future in terms of testing of coding. I got better understanding and also got the differences between the two. Even dough i had an idea of it, this has really help me.

 

Links: http://www.cs.unh.edu/~it666/reading_list/Defense/blackbox_vs_whitebox_testing.pdf

https://www.guru99.com/back-box-vs-white-box-testing.html

https://www.softwaretestinghelp.com/white-box-testing-techniques-with-example/

Causes of software errors #443

I picked this article because i wanted to better understand the term error(s) under testing. What actually got me to do this research was the causes of errors in software development.

first let know the terms of software error, fault and failures. Software error is made by programmer, like syntax error or logic error. Software fault is a part of the software which may not execute. Software Failures, this is due how the software is executed.

Some of the causes that i searched throw were:

Faulty Requirements Definition

  • Usually considered the root cause of software errors
  • Incorrect requirement definitions
  • Simply stated, ‘wrong’ definitions (formulas, etc.)
  • Incomplete definitions
  • Unclear or implied requirements
  • Missing requirements
  • Just flat-out ‘missing.’ (e.g. Program Element Code)
  • Inclusion of unneeded requirements
  • (Many projects have gone amuck for including far too many requirements that will never be used.

Impacts budgets, complexity, development time

 

Client-developer communication failures

  • Misunderstanding of instructions in requirements documentation (written / graphical instructions)
  • Misunderstanding of written changes during development.
  • Misunderstanding of oral changes during development.
  • Lack of attention
  • to client messages by developers dealing with requirement changes and
  • to client responses by clients to developer questions
  • Very often, these very talented individuals come from different planets, it seems.
  • Clients represent the users; developers represent a different mindset entirely sometimes!

 

Coding errors

  • Too many to try to list.
    • Syntax errors (grammatical errors)
    • Logic errors (program runs; results wrong)
    • Run-time errors (crash during execution)
    • Know the differences. Be also able to supply an example.  Examples do not ‘define’ something, but they may be used to ‘support’ or ‘supplement’ a definition.

Logical design errors

  • Omission of required software system states
  • If rank is >= O1 and RPI is numeric, then….easy to miss an action based on the software system state.
  • Omission of definitions / procedures concerning reactions to illegal operation of the software system.
  • Including not only code to detect an illegal operation but failure to design the computer software reaction to this: Gracefully terminate, sound   alarm, etc
  • an error is a human activity resulting in software containing a fault
  • a fault is the manifestation of an error
  • a fault may result in a failure
  • Failure is a relative notion: e.g. a failure w.r.t. the specification document
  • Verification: evaluate a product to see whether it satisfies the conditions specified at the start

 

I got to learn more about errors, what happens when error occurs and how identify them.  These articles that i have searched and learned will help me identify bug, or even error very quick. And also in an organized fashion.

links: https://www.testingexcellence.com/error-fault-failure-software-testing/

https://www.tutorialspoint.com/software_testing_dictionary/error.htm

https://www.softwaretestingmaterial.coI m/difference-between-defect-bug-error-and-failure/

 

Static vs. Dynamic Testing (week-6)

On week 6, i did some research on static and Dynamic testing. The main reason for picking this topic is to know ahead before we start talking about it in class. In that way i am able to follow and ask question that i may want to ask the prof.

I learned a whole lot, first this is what learned on static testing. It does not execute code. It manually checks work documents to find errors in early stage.

Some benefits of static testing techniques.

  1. lifetime cost reduction
  2. reduced fault levels
  3. improved customer relations
  4. development productivity improvement
  5. And also reduced development timescales

Some of the information i got from dynamic testing. From my understanding, it is a term used to describe the testing of the dynamic behavior of code.  Not like the static testing which does not execute code, dynamic testing does, it involves working with the software, giving input values and checking if the output is as expected.

Dynamic testing is the validation portion of verification and validation. some of the validation activities are unit tests, integration tests, system tests and acceptance tests

some techniques on dynamic testing

 

graphical representation of dynamic testing techniques

Static Testing Vs Dynamic Testing

from one of the links(blogs) below gives the techniques of dynamic testing

  • Unit Testing:Under Unit Testing ,  individual units or modules is  tested by the developers. It  involves testing of source code by developers.
  • Integration Testing: Individual modules are grouped together and tested by the developers. The purpose is to determine that modules are working as expected once they are integrated.
  • System Testing: System Testing is performed on the whole system by checking whether the system or application meets the requirement specification document.

Through the research got to know static and dynamic testing complement to one another and each type has a unique approach to detecting bugs.

also got to know white box testing where developers verity or check code to find fault is derived from static testing system.

one also big different about static and dynamic is that, static testing is about prevention whereas dynamic testing is about cure.

 

These articles or blogs really helped my understanding of these two testing, static testing and dynamic testing.

references : https://www.guru99.com/static-dynamic-testing.html

https://www.softwaretestingclass.com/difference-between-static-testing-and-dynamic-testing/

https://www.360logica.com/blog/difference-between-static-testing-and-dynamic-testing/