code smells and its type (with example)

Post on 14-Apr-2017

53 Views

Category:

Engineering

5 Downloads

Preview:

Click to see full reader

TRANSCRIPT

CODE SMELL/ BAD SMELL

CODE SMELL/ BAD SMELL

Anshul

National institute of Technology ,Kurukshetra

April 10, 2016

CODE SMELL/ BAD SMELL

Overview

1 Motivation2 Introduction

DefinitionCode re-factoring

3 Types of Code SmellDuplicate CodeLong methodLarge ClassDivergent ChangeShortgun SurgeryFeature EnvyData ClumpsComments

4 Advanced....Two Level Dynamic Approach for Feature Envy Detection

5 Conclusion6 References

CODE SMELL/ BAD SMELL

Motivation

Though Re-factoring is a old concept, developers are notutilizing it.

To capture and write down the situation which make sense tore-factoring.

Re factoring is directly related to Economics

CODE SMELL/ BAD SMELL

Introduction

Definition

Code smell :- Code smells are indications of poor coding anddesign choices that can cause problems during the later phase ofsoftware development.

Code smells are considered as flags to the developer thatsome parts of the design may be inappropriate.

Such design flaw that can be solved by re-factoring.

According to MARTIN FOWLER ”IF it stinks change it.”

CODE SMELL/ BAD SMELL

Introduction

Code re-factoring

”Refactoring is the process of changing a software system insuch a way that it does not alter the external behavior of thecode yet improves its internal structure.

Refactoring is a form of program transformation whichpreserves the semantics of the program.

Improving the design after it has been written.

It is an iterative process.

CODE SMELL/ BAD SMELL

Types of Code Smell

Duplicate Code

Occurrence of Same code structure more than once.

When we have same expression in two or more methods ofsame class.

Solution for this code smell is to do Extract method andthen invoke the code from both the places.

CODE SMELL/ BAD SMELL

Types of Code Smell

Duplicate Code

Example 1

extern int a[];extern int b[];int sumofa = 0;for (int i = 0; i < 4; i + +)sum += a[i];int averageofa= sum/4;—————-int sumofb = 0;for (int i = 0; i < 4; i + +)sum += b[i];int averageofb = sumofb/4;

Extract method

int calc-average(int* array)int sum= 0;for (int i = 0; i < 4; i + +)sum + =array[i];return sum/4;

CODE SMELL/ BAD SMELL

Types of Code Smell

Duplicate Code

Example1 contd...

Extract method will give source code that has no loop duplicationextern int a[];extern int b[];int averageofa = calcAverage(a[]);int averageofb = calcAverage(b[]);

CODE SMELL/ BAD SMELL

Types of Code Smell

Duplicate Code

Example 2

Another problem is when we have same code in twosubclasses.

Solution:-(Extract method + pull up method ) extractsimilar codes from both the classes in form a method andthen put this method in the superclass.

CODE SMELL/ BAD SMELL

Types of Code Smell

Long method

Brief

Analysis and the experience says that the object programswhich lives best and longest are those with short methods.

To shorten a method all we have to do is to Extract a newmethod

CODE SMELL/ BAD SMELL

Types of Code Smell

Long method

Key points:

IF method has a lot of parameters and variables , then thesethings comes in the form of obstacles to Extract method.

Even if we try to do so , we will end up passing so manyparameters and variables to newly Extracted method.

Solution is to replace temp with query to eliminate temps.

And to slim down the long parameters we may introduce anew parameter object And then preserving whole object.

CODE SMELL/ BAD SMELL

Types of Code Smell

Long method

Replace temp with Query

double basePrice= quantity ∗ itemPrice;if (basePrice > 1000)return basePrice ∗ 0.95;else return basePrice ∗ 0.98;

if (basePrice() > 1000) returnbasePrice() ∗ 0.95;else return basePrice() ∗ 0.98;...———————double basePrice()return quantity ∗ itemPrice;

CODE SMELL/ BAD SMELL

Types of Code Smell

Long method

New Parameter Object

CODE SMELL/ BAD SMELL

Types of Code Smell

Long method

Question: How to decide the clumps of code that wewant to extract ?

CODE SMELL/ BAD SMELL

Types of Code Smell

Long method

Answer see comments ” . Even a single line is worthextracting if it needs explanations.

CODE SMELL/ BAD SMELL

Types of Code Smell

Large Class

1 Signs and symptoms:

When a single class is doing too much , it often shows up toomany variables and instancesOR can say ; A class having many fields/methods/lines of codeis called as LARGE CLASS.

2 Reasons for the Problem:

Classes usually start small. But over time, they get bloated asthe program grows.Programmers usually find it mentally less taxing to place anew feature in an existing class than to create a new class forthe feature.

3 Treatment

Extract Class helps if part of the behavior of the large classcan be spun off into a separate component.Extract SubClass helps if part of the behavior of the largeclass can be implemented in different ways or is used in rarecases.

CODE SMELL/ BAD SMELL

Types of Code Smell

Large Class

Extract Class

CODE SMELL/ BAD SMELL

Types of Code Smell

Divergent Change

When we make a change,we want to be able to a single clearpoint in the system and make the change.

And if you can not do this, you are smelling one of the twoclosely related pungencies.

Divergent change occurs when one class is commonly changedin different ways for different reasons.

Split up the behavior of the class viaExtract Class

PayoffImproves code organization.Reduces code duplication.Simplifies support.

CODE SMELL/ BAD SMELL

Types of Code Smell

Divergent Change

Example:

class Userdef full−name”#{first − name}#{last −name}”enddef authorized?(action)is−admin?endendclass User

class UserPresenter<SimpleDelegatordef full−name”#{first − name}#{last −name}”endendclass ActionAuthorizer defauthorized?(action, user)user.is−admin?endend# nothing here?end

CODE SMELL/ BAD SMELL

Types of Code Smell

Shortgun Surgery

Shortgun surgery is opposite to divergent change

This happens when, you want to make some kind ofchange, you are forced to make a lot of changes to a lotof different classes

And when changes are all over the place, they are hard to find,and it’s easy to miss an important change

Use MOVE METHOD and MOVE FIELD to pull all thechanges to a single class.

CODE SMELL/ BAD SMELL

Types of Code Smell

Shortgun Surgery

Example:Move Method

class Project {Person[] participants;}class Person{int id;boolean participate(Project p){ for(int i = 0; i < p.participants .length ; i + +) {if (p.participants[i ].id ==id)return(true);} return(false); } }... if (x .participate(p)) ...

class Project {Person[] participants;boolean participate(Person x) {for(int i= 0;i<participants.length; i++){if (participants[i].id == x.id)return(true); }return(false);}}class Person{int id;}... if (p.participate(x)) ...

CODE SMELL/ BAD SMELL

Types of Code Smell

Shortgun Surgery

Example: Move Field

A field is, or will be, used by another class more than the class onwhich it is defined.

CODE SMELL/ BAD SMELL

Types of Code Smell

Shortgun Surgery

Why ”Move Field”

Often fields are moved as part of the Extract Class technique

Deciding which class to leave the field in can be tough.

Here is our rule of thumb: put a field in the same place as themethods that use it (or else where most of these methods are).

This rule will help in other cases when a field is simply locatedin the wrong place.

CODE SMELL/ BAD SMELL

Types of Code Smell

Feature Envy

The whole point of objects is that; they are kind of techniquethat package data with the processes used on that data.

When a method seems more interesting in a class, other thanthe one in actually it is.

The most common of focus of envy is data

For example; we have a method that invokes half a dozengetting methods on another object to calculate some value.

The indication is obvious that the methods wants to beelsewhere, so we can simply use MOVE METHOD to givethe method ,its dream home.

We are reducing the coupling and enhancing the cohesion

CODE SMELL/ BAD SMELL

Types of Code Smell

Feature Envy

Move method

CODE SMELL/ BAD SMELL

Types of Code Smell

Data Clumps

Data items enjoy hanging around in groups together.

Often we see the same three or four data items together inlots of places like : fields in a couple of classes, parameters inmethod signatures

These bunches of data ought to be made into their own object

Then apply Introduce parameter Object re-factoring ”

CODE SMELL/ BAD SMELL

Types of Code Smell

Comments

Comments are not bad smell.

Author has named them a Sweet Smell

When you feel the need to write comment,first try to re-factorthe code so that any comment becomes superfluous.

Comments are often used as Deodorant to the bad smell.

For example if we need a comment to explain what a block ofcode does; try Extract method,if extract method is alreadydone , then Rename Method.

The purpose of Comments should be only ”Why you areDoing Something(To help future modifiers)” rather than”What code is doing ”

CODE SMELL/ BAD SMELL

Advanced....

Two Level DynamicApproach for Feature Envy

Detection

CODE SMELL/ BAD SMELL

Advanced....

Two Level Dynamic Approach for Feature Envy Detection

To refactor the code, it must be known which part of codeneeds to be refactored.

For this purpose code smells are used.

In this field dynamic analysis is still in dark, which is anopportunity to explore in this direction also.

To tackle this problem, we have devised a two levelmechanism

. First level filters out the methods which are suspects of beingfeature enviousSecond level analyzes those suspects to identify the actualculprits.

CODE SMELL/ BAD SMELL

Advanced....

Two Level Dynamic Approach for Feature Envy Detection

Advantage Over Static Techniques

Static Techniques analyze the source code statically, whichis less accurate in object oriented environment.

The detection mechanism is applied over complete codeblindly, irrespective of whether they are completely free of anykind of smell or not, which is an overhead

Dynamic analysis is a technique that analyzes the datagathered during program executions , instead of analysing itssource code.

By executing a program, we can obtain an actual programbehaviour , which cannot be obtained from only analysing itssource code.

CODE SMELL/ BAD SMELL

Advanced....

Two Level Dynamic Approach for Feature Envy Detection

Purposed Work

CODE SMELL/ BAD SMELL

Advanced....

Two Level Dynamic Approach for Feature Envy Detection

Working of feature envy detection mechanism

CODE SMELL/ BAD SMELL

Conclusion

Conclusion

Code Smell detection is a challenging task.

it can be said that use of dynamic analysis can beadvantageous in detection of other types of code smells alsoand will be a useful and efficient approach for softwaremaintainers.

CODE SMELL/ BAD SMELL

References

References

1 M. Fowler, K. Beck, J. Brant, W. Opdyke, and D. Roberts,Refactoring: Improving the Design of Existing Code.Addison-Wesley, 1999.

Swati, Jitender Kumar Chhabra,Two Level Dynamic Approachfor Feature Envy Detection;ICCCT [2014].

https://www.youtube.com/watch?v=vqEg37e4Mkw; aseminar by Martin Fowler on ”Workflows of Refactoring”

CODE SMELL/ BAD SMELL

References

Thank you !

top related