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

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

Object Oriented Programming(java)

I know many of you know much about Object Oriented programming. But still yet i wanted to give more details about it. To give you the real explanation of Object Oriented Programming  as being one of the main reason of choosing this topic.

Object-oriented programming (OOP) refers to a type of computer programming  in which programmers define not only the data type of a data structure , but also the types of operations functions that can be applied to the data structure.

Now in an object-oriented language, this program would instead be split apart into self-contained objects, almost like having several mini programs. Each object is representing a different part of the application and each object contains its own data and its own logic and they communicate between themselves. Now if that sounds like it could be a little bit confusing, the idea here is that these objects represent the way you would talk and think about the actual problem.

It’s meant to make thinking about your program easier. The objects don’t represent mysterious abstract ideas. They first represent things like employees, images, bank accounts, player objects, car objects, whatever actually exists in your program. So object orientation is an idea and it’s an idea that it’s supported in many languages. And for you it’s a shift to thinking about the objects in your program are not just the process. And while object-oriented programming can bring a lot of jargon into the table, there are really only a couple of terms we need to be comfortable with to move forward with it.

The first two terms we need to understand is the difference between a class and an object. And these two terms go hand in hand with object-oriented languages. A class is a blueprint. It’s an idea, it’s a description, it’s a definition. It describes what something is, but it isn’t the thing itself. It’s a well-defined idea, like say a blueprint for house. And classes will exist for different parts of your program. So if you are writing a restaurant review website, you might create classes that represent a restaurant and a review or a user.

Classes could also represent visual parts of your program, things like TextBox and Button and Window. And they can also represent invisible things like dates and times and anything that can be a well-defined idea. A lot of languages come with many classes already defined, even advanced things like VideoPlayer classes, and you can also define your own. Now all classes describe and define two things: Attributes and Behavior.

What are some things characteristics, its attributes, and what can it do, what’s its behavior. So in this case, let’s say we are describing a class to describe a person. We might say that the person attributes are name, height, weight, gender, and age, whereas the person’s behavior is walk, run, jump, speak, sleep. Think about it this way that the attributes are really your data, your variables. And the behavior is what can you do, your functions. And actually attributes and behavior in most object-oriented languages are actually described with other names, which is properties and methods.

These are the most common ways of describing these. But the class is describing these things in abstract. And what I mean by that is it says that a person has a name and it has a height, but it doesn’t say what the name is because the class is just the description of something. But just like there’s no point creating a blueprint if you never intend to make a house, there’s no point defining a class unless you’re going to make an object. So that’s the relationship between the two.

The class is the idea and the object is the thing itself. We create objects based on the class like creating a house based on the blueprint. Not only that, but you can create multiple objects based on one class in the same way you could create multiple houses based on one single blueprint. Now while there is a lot of jargon associated with object orientation, encapsulation is the key idea.

This the idea that classes are self- contained units that represent both the data and the code that works on that data, that we take our properties and our methods and we box them up, we encapsulate them. JavaScript is an object-oriented language. Although it is quite casual with it, there are some other languages where object orientation is very formal and you can do very little without thinking deeplyabout classes and objects. So while some languages like C are not at all object-oriented, if you’re working in Java, you can’t avoid object orientation in most modern programming languages.

From this topic i have learned a lot about Object Oriented Programming. , understand the difference between classes and objects.This will help me better understand any project given to me in java. I know now most of you have gotten the understanding of Object Oriented Programming.

 

 

 

 

Link to the site ::

https://www.edureka.co/blog/object-oriented-programming/

And

https://www.lynda.com/JavaScript-tutorials/Foundations-of-Programming-Fundamentals/83603-2.html?utm_medium=viral&utm_source=youtube&utm_campaign=videoupload-83603-1201

 

Lambda expression in java

A Lambda Expression is a representation of an anonymous function which can be passed around as a parameter thus achieving behavior parameterization. A lambda consists of a list of parameters, a body, a return type and a list of exceptions which can be thrown. I.e. it is very much a function, just anonymous.

An instance of a lambda can be assigned to any functional interface 
 whose single abstract method’s definition matches the definition of the lambda. In fact, a lambda is a less verbose way of defining an instance of an interface provided the interface is functional. Since, the definition of a lambda can match the definition of multiple functional interfaces, hence, a lambda instance can be assigned to any of these matching interfaces.

The reason i picked this topic was because it was something new i have seen in the java language. Also wanted to know more about it and see if i can utilized it on some of my java programming language.

Examples of lambda expression.

First of all. Comparing java 7 to java 8.

public interface StateChangeListener {

public void onStateChange(State oldState, State newState);

}

In java 7 we implement this interface in order to listen for state changes. You do this

public class StateOwner {

public void addStateListener(StateChangeListener listener) { … }

}

But in java 8 you can add an event listener using a java lambda expression. like this.

StateOwner stateOwner = new StateOwner();

stateOwner.addStateListener(

(oldState, newState) -> System.out.println(“State changed”)

);

 

From this topic ( lambda expressions), i learned that previous java or java 7, if i wanted a block of code to be executed, we need to create an object and pass the object around. From Java 8, lambda expressions enable us to treat functionality as method argument and pass a block of code around. Lambda expressions in Java 8 are very powerful and therefore very compelling. For me, lambda expressions is way much better, convenient and very easy.

link to the resource : http://tutorials.jenkov.com/java/lambda-expressions.html