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

Junit (week-4)

JUnit is a unit testing framework for Java programming language. JUnit improve software design, makes software easier to understand, reduce debugging time, catch integration errors and in short to produce better code.

Choosing this topic has made me understand JUnit very clear. I have come to know the types of JUnit. Also come to know the use of testing driven development. As in the Test Driven Development, it is a software development process in which tests are written based on the requirements before any coding begins.

On the Test Driven Development(TDD), i also got to know its life-cycle. which are

  1. write the test
  2. run the test
  3. write just enough implementation code to make the test pas
  4. run all tests
  5. refactor
  6. repeat

Also go to know TDD is not about testing but development,specifically improving the quality and design of code.

Also learned what Code Coverage, which is the measuring how much of your code is executed during your unit tests.

Some best practice for measuring code coverage are

1.  use a code coverge tool like Sonar or JaCoCo. These tools help because they can point out areas of the code that are untested. Also Code Coverage does not guarantee the tests are perfect.

2.  Ensure that there are test cases that over all the branches of the code, i.e. if/else statement.

 

Another tip i got was, instead of using the print statement, rather use the assertions.

for instance:

 public class StringUtil {
    public String concat(String a,String b) {
        return a + b;
    }
    }
These are the two testing method
1)
@Test
public void testStringUtil_Bad() {
String result = stringUtil.concat(“Hello “, “World”);
System.out.println(“Result is “+result);
}
2)
@Test
public void testStringUtil_Good() {
String result = stringUtil.concat(“Hello “, “World”);
assertEquals(“Hello World”, result);
}
The first test is the print method and the second one is the assertion method.
the reason why you have to use the assertion is because it automatically indicate test results. but the print statement does not.

I really enjoy reading this article containing some interesting topics, which in the future will help me a lot. I got the understanding of some part of Junit testing in java and tips that i will using. The JaCoCo application for measuring how much code is executed during testing was a little confusing. but with time will understand it better.

 

Link : https://stormpath.com/blog/7-tips-writing-unit-tests-java

 

System Testing

System Testing 

 How to do System Testing?

 

i learned some ways to take when you are about to do system testing. I notics, in software system testing , testing has to follow some specific steps. which are below,

Step 1) First & important step is preparation of System Test Plan

 Step 2) Second step is to creation Test Cases:

 Step 3) Creation of test data which used for System testing.

Step 4) Automated test case execution.

Step 5) Execution of normal test case & update test case if using any test management tool (if any).

Step 6) Bug Reporting, Bug verification & Regression testing.

Step 7) Repeat testing life cycle (if required).

 

To get more about this topic, visit or click on this link System Testing .

HTML (Hypertext Markup Language) and CSS(Cascading Style Sheets)

HTML which stands for hypertext markup language and CSS(Cascading Style Sheets). Are what i decided to read about since with our final project with the typescript and angular , we will need HTML and CSS for it to work properly. Also giving it a better graphical look or user interface with the help of CSS.  Hope you viewers enjoy the article.

 

HTML stands for Hypertext Markup Language, and it is the most widely used language to
write Web Pages.
* Hypertext refers to the way in which Web pages (HTML documents) are linked
together. Thus, the link available on a webpage is called Hypertext.
* As its name suggests, HTML is a Markup Language which means you use HTML
to simply “mark-up” a text document with tags that tell a Web browser how to
structure it to display.
Originally, HTML was developed with the intent of defining the structure of documents like
headings, paragraphs, lists, and so forth to facilitate the sharing of scientific information
between researchers.
Now, HTML is being widely used to format web pages with the help of different tags
available in HTML language.

HTML Tags
As told earlier, HTML is a markup language and makes use of various tags to format the
content. These tags are enclosed within angle braces <Tag Name>. Except few tags,
most of the tags have their corresponding closing tags. For example, <html> has its
closing tag</html> and <body> tag has its closing tag </body> tag etc

A typical HTML document will have the following structure:

Document declaration tag
<html>
<head>
Document header related tags
</head>
<body>
Document body related tags
</body>
</html>

HTML Attributes

Attributes provide additional information about HTML elements.

  • All HTML elements can have attributes
  • Attributes provide additional information about an element
  • Attributes are always specified in the start tag
  • Attributes usually come in name/value pairs like: name=”value”

 

Now let get into CSS(Cascading Style Sheets).

CSS(Cascading Style Sheets) describes how HTML elements are to be displayed on screen, paper, or in other media. It saves a lot of work. It can control the layout of multiple web pages all at once

CSS is designed primarily to enable the separation of presentation and content, including aspects such as the layout , colors , and fonts . This separation can improve content accessibility , provide more flexibility and control in the specification of presentation characteristics, enable multiple HTML pages to share formatting by specifying the relevant CSS in a separate .css file, and reduce complexity and repetition in the structural content.

Separation of formatting and content makes it possible to present the same markup page in different styles for different rendering methods, such as on-screen, in print, by voice (via speech-based browser or screen reader), and on Braille-based tactile devices. It can also display the web page differently depending on the screen size or viewing device. Readers can also specify a different style sheet, such as a CSS file stored on their own computer, to override the one the author specified.

Changes to the graphic design of a document (or hundreds of documents) can be applied quickly and easily, by editing a few lines in the CSS file they use, rather than by changing markup in the documents.

example of Css

<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: lightblue;
}
</style>
</head>
<body>

<h1>Hello World!</h1>

<p>This page has a light blue background color!</p>

</body>
</html>

output:

Background will turn lightblue. try it!

Even though i know much about this article. It really helped me refreshed my mind on some stuff i forgot. now with no doubt , i know i will utilized this info to work better on my final project. Hope you guys also find this article very useful.

references : 

https://www.codecademy.com/courses/web-beginner-en-HZA3b/0/1?curriculum_id=50579fb998b470000202dc8b

https://www.w3schools.com/css/css_intro.asp

https://en.wikipedia.org/wiki/Cascading_Style_Sheets

 

TypeScript

I choose this topic because i wanted to know more about it, how it works and why developers choose to follow this style than our normal JavaScript style. Also to help me understand and do the coding for the duck simulator in typescript on design pattern.

TypeScript starts from the same syntax and semantics that millions of JavaScript developers know today. Use existing JavaScript code, incorporate popular JavaScript libraries, and call TypeScript code from JavaScript.

TypeScript compiles to clean, simple JavaScript code which runs on any browser, in Node.js, or in any JavaScript engine that supports ECMAScript 3 (or newer).

Types enable JavaScript developers to use highly-productive development tools and practices like static checking and code refactoring when developing JavaScript applications.

Types are optional, and type inference allows a few type annotations to make a big difference to the static verification of your code. Types let you define interfaces between software components and gain insights into the behavior of existing JavaScript libraries.

TypeScript offers support for the latest and evolving JavaScript features, including those from ECMAScript 2015 and future proposals, like async functions and decorators, to help build robust components.

These features are available at development time for high-confidence app development, but are compiled into simple JavaScript that targets ECMAScript 3 (or newer) environments.

 

Examples of typescript

The global variable foo contains the number of widgets present.

Code

console.log("Half the number of widgets is " + (foo / 2));

Declaration

Use declare var to declare variables. If the variable is read-only, you can use declare const. You can also use declare let if the variable is block-scoped.

/** The number of widgets present */
declare var foo: number;

Global Functions

Documentation

You can call the function greet with a string to show a greeting to the user.

Code

greet("hello, world");

Declaration

Use declare function to declare functions.

declare function greet(greeting: string): void;

Objects with Properties

Documentation

The global variable myLib has a function makeGreeting for creating greetings, and a property numberOfGreetings indicating the number of greetings made so far.

Code

let result = myLib.makeGreeting("hello, world");
console.log("The computed greeting is:" + result);

let count = myLib.numberOfGreetings;

Declaration

Use declare namespace to describe types or values accessed by dotted notation.

declare namespace myLib {
    function makeGreeting(s: string): string;
    let numberOfGreetings: number;
}

 

After learning and observing. I found out that this is way better than then normal javascipting coding. The reason why is say that is because with the typescript , i kind of like dealing with class (objects) like java coding which makes it easier for me. I like how things are organized and it also readable. I guess with this my coding will be javascript/typescript will be fun and cleaned. I really hope pupils enjoy this post and also research more about typescript.

link :: https://www.typescriptlang.org/

https://www.typescriptlang.org/docs/handbook/declaration-files/by-example.html

Angularjs

I chose this topic because we will be using it for projects. Wanted to know more about it, get some trick and also share it among the pupils. Also i have come to notice most companies in the web development require a potential employee to have this kind of programming language. At least an understanding of it.

AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML’s syntax to express your application’s components clearly and succinctly. AngularJS’s data binding and dependency injection eliminate much of the code you would otherwise have to write. And it all happens within the browser, making it an ideal partner with any server technology.

AngularJS is what HTML would have been, had it been designed for applications. HTML is a great declarative language for static documents. It does not contain much in the way of creating applications, and as a result building web applications is an exercise in what do I have to do to trick the browser into doing what I want?

The impedance mismatch between dynamic applications and static documents is often solved with:

  • a library – a collection of functions which are useful when writing web apps. Your code is in charge and it calls into the library when it sees fit. E.g., jQuery.
  • frameworks – a particular implementation of a web application, where your code fills in the details. The framework is in charge and it calls into your code when it needs something app specific. E.g., durandalember, etc.

AngularJS takes another approach. It attempts to minimize the impedance mismatch between document centric HTML and what an application needs by creating new HTML constructs. AngularJS teaches the browser new syntax through a construct we call directives. Examples include:

  • Data binding, as in {{}}.
  • DOM control structures for repeating, showing and hiding DOM fragments.
  • Support for forms and form validation.
  • Attaching new behavior to DOM elements, such as DOM event handling.
  • Grouping of HTML into reusable components.

A complete client-side solution

AngularJS is not a single piece in the overall puzzle of building the client-side of a web application. It handles all of the DOM and AJAX glue code you once wrote by hand and puts it in a well-defined structure. This makes AngularJS opinionated about how a CRUD (Create, Read, Update, Delete) application should be built. But while it is opinionated, it also tries to make sure that its opinion is just a starting point you can easily change. AngularJS comes with the following out-of-the-box:

  • Everything you need to build a CRUD app in a cohesive set: Data-binding, basic templating directives, form validation, routing, deep-linking, reusable components and dependency injection.
  • Testability story: Unit-testing, end-to-end testing, mocks and test harnesses.
  • Seed application with directory layout and test scripts as a starting point.

Example ::

<!DOCTYPE html>
<html>
https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js
<body>

Input something in the input box:

Name:

</body>
</html>

 

preview code:

Input something in the input box:

Name:

so with this example , you input a word or name to the name field and automatically it give you a feed back instantly below the name field. You guys should try it and see what i’m talking about. Very fun..

I have learned a lot about Angularjs. You can do a whole lot just on a single page without refreshing it or changing the page. Which is very efficient. I normally use jquery for my programming in web development but comparing it with Angularjs, i think Anjularjs is far easy, efficient than jquery. I might be wrong since i have not learned into it so deep. but for the small coding i did, was very easy and understandable.

Links::https://docs.angularjs.org/guide/introduction

 

Software Frameworks

This week i picked software frameworks. Since it’s going to be a next to topic to be discoursed in class in the future. I rather prepare my self, and get more understanding.

A software framework is a concrete or conceptual platform where common code with generic functionality can be selectively specialized or overridden by developers or users. Frameworks take the form of libraries, where a well-defined application program interface (API) is reusable anywhere within the software under development

Here are some types of software frameworks:

  • Resource Description Framework, a set of rules from the World Wide Web Consortium for how to describe any Internet resource such as a Web site and its content.
  • Internet Business Framework, a group of programs that form the technological basis for the mySAP product from SAP, the German company that markets an enterprise resource management line of products
  • Sender Policy Framework, a defined approach and programming for making e-mail more secure
  • Zachman framework, a logical structure intended to provide a comprehensive representation of an information technology enterprise that is independent of the tools and methods used in any particular IT business

Using a framework is not really any different from classic OOP programming.

When you write projects in a similar environment, you will probably see yourself writing a framework (or a set of tools) over and over again.

A framework is really just code reuse – instead of you writing the logic for managing a common task, someone else (or you) has written it already for you to use in your project.

A well designed framework will keep you focused on your task, rather than spending time solving problems that has been solved already.

Frameworks of all kinds are extremely important nowadays, because of the time factor. When building something you will need to invest a lot of your time in building the logic for your application – and you don’t want to be forced to program any kind of low-level functionality. Software frameworks do that, they take care of the low-level stuff for you.

There are some this disadvantages :

  • Creating a framework is difficult and time-consuming (i.e. expensive).
  • The learning curve for a new framework can be steep.
  • Over time, a framework can become increasingly complex.

But these disavantages , i think its the best way to go.

From this topic i learned a framework is a code reuse, extremely important for programmer for it to take care of the low-level stuff. This will also help me develop better codes and in a fast pace .  I really hope this help all the students taking this cs-343 class for better understanding in the future.

 

links or reference :: https://www.techopedia.com/definition/14384/software-framework ,

http://whatis.techtarget.com/definition/framework