This document discusses code smells, which are indications of poor coding practices that can cause problems later. It defines code smells and code refactoring. Several types of code smells are described in detail, including duplicate code, long methods, large classes, divergent change, shotgun surgery, feature envy, and data clumps. Advanced techniques for dynamically detecting feature envy are also discussed. The document provides examples and explanations for how to identify and refactor code to address these smells.
The document discusses refactoring tips provided by Martin Fowler. It defines refactoring as improving the internal structure of software without changing its external behavior. It provides examples of common refactoring techniques like extract method, inline method, move method, and consolidate conditional expressions. The goal of refactoring is to improve code quality by making software easier to understand and modify over time.
The document discusses refactoring code to improve its internal structure without changing external behavior. It defines refactoring and provides reasons for refactoring like improving design and readability. It also categorizes different types of refactorings like decomposing methods, moving features between objects, and organizing data. Specific refactorings are explained like extract method, inline method, move method, and encapsulate field.
This document discusses code smells and refactoring. It begins by defining a code smell as a surface indication of deeper problems in code, such as weaknesses in design that could slow development or increase bugs. Various types of code smells are described, including bloaters (e.g. long methods), object-orientation abusers, change preventers, dispensables, and couplers. Refactoring is introduced as a process of changing code structure without altering external behavior to improve code quality and make it easier to understand and modify. The importance of refactoring to address code smells and keep code maintainable over time is emphasized.
This Presentation contains all the topics in design concept of software engineering. This is much more helpful in designing new product. You have to consider some of the design concepts that are given in the ppt
This document discusses code smells, which are indications of poor coding practices that can cause problems later. It defines code smells and code refactoring. Several types of code smells are described in detail, including duplicate code, long methods, large classes, divergent change, shotgun surgery, feature envy, and data clumps. Advanced techniques for dynamically detecting feature envy are also discussed. The document provides examples and explanations for how to identify and refactor code to address these smells.
The document discusses refactoring tips provided by Martin Fowler. It defines refactoring as improving the internal structure of software without changing its external behavior. It provides examples of common refactoring techniques like extract method, inline method, move method, and consolidate conditional expressions. The goal of refactoring is to improve code quality by making software easier to understand and modify over time.
The document discusses refactoring code to improve its internal structure without changing external behavior. It defines refactoring and provides reasons for refactoring like improving design and readability. It also categorizes different types of refactorings like decomposing methods, moving features between objects, and organizing data. Specific refactorings are explained like extract method, inline method, move method, and encapsulate field.
This document discusses code smells and refactoring. It begins by defining a code smell as a surface indication of deeper problems in code, such as weaknesses in design that could slow development or increase bugs. Various types of code smells are described, including bloaters (e.g. long methods), object-orientation abusers, change preventers, dispensables, and couplers. Refactoring is introduced as a process of changing code structure without altering external behavior to improve code quality and make it easier to understand and modify. The importance of refactoring to address code smells and keep code maintainable over time is emphasized.
This Presentation contains all the topics in design concept of software engineering. This is much more helpful in designing new product. You have to consider some of the design concepts that are given in the ppt
This document discusses code refactoring. It begins by defining refactoring as restructuring source code to improve readability, fix bugs easily, enhance design, and introduce flexibility without changing functionality. It then provides examples of when to refactor, such as when duplicating logic exists, or to enable sharing of logic between methods. The document also discusses problems that can occur with refactoring, like interface changes breaking other applications, and signs that refactoring is needed, such as duplicate code, long methods, or large classes. It provides guidance on how to identify code that needs refactoring and techniques for refactoring different structures. In the end, it discusses the potential benefits of refactoring, such as increased
This document discusses bottom-up parsing and handle pruning. It begins with an example grammar and string. Bottom-up parsing works by repeatedly reducing substrings matching production bodies until reaching the start symbol. A handle is a substring matching a production body whose reduction moves backward through a rightmost derivation. Handle pruning is removing nonterminal children from a parse tree, allowing reconstruction of a rightmost derivation by working backward from handles. The document provides steps for using handle pruning to rebuild a rightmost derivation in reverse from a given string. An example demonstrates finding the handles in a string and reducing based on the corresponding productions to reach the start symbol.
How to improve your code quality? The answer is continuous refactoring. Learn more about refactoring. Know the most frequent code smells (antipatterns), telling when to refactor. Go through the catalog of well-known refactorings, telling how to improve your code.
Refactoring is changing code without altering its external behavior to improve its structure and understandability. Reasons to refactor include making code easier to fix bugs or add features. Testing during refactoring prevents breaking changes. Techniques include renaming, extracting variables/methods, removing temporary variables, moving code between classes, and other object-oriented improvements.
This document discusses functions in C++. It defines what a function is and explains that functions are the building blocks of C++ programs. Functions allow code to be reused, making programs easier to code, modify and maintain. The document covers function definitions, declarations, calls, parameters, return types, scope, and overloading. It also discusses local and global variables as well as pass by value and pass by reference.
Refactoring of code for more readable, scalable modules based on The book titled "Refactoring - Improving the Design of Existing Code" written by Martin Fowler
This presentation is part of one of my webinar in clean code webinar series. The contents are slightly edited to share the information in public domain. In this presentation, I tried to provide detailed introduction to code refactoring practice.
This presentation will be useful for software architects/Managers,developers and QAs. Do share your feedback in comments.
This presentation will introduce you to programming languages that support different programming paradigms and to give you the knowledge of basic concepts and techniques that will allow them to differentiate between various programming paradigms.
Control structures in C++ Programming LanguageAhmad Idrees
This document discusses various control structures in C++ for selection and branching, including if/else statements, switch statements, logical operators, and the assert function. If/else statements allow for two-way selection based on a logical expression being true or false. Switch statements allow for multi-way branching depending on the value of an expression. Logical operators like && and || are used to combine logical expressions. The assert function halts a program if a specified condition is false, which is useful for debugging.
This document discusses refactoring code to improve its design without changing its external behavior. It defines refactoring as changing code structure without modifying functionality. The author is an experienced PHP developer who gives tips on when and how to refactor code, including drivers like preventing decay, reducing duplication, and improving maintainability. Examples are provided of code smells that indicate refactoring may be helpful, like duplicate code, long methods, and large classes. The document concludes by emphasizing the importance of testing before and after refactoring.
The document discusses use case diagrams in object oriented design and analysis. It defines use cases as descriptions of system functionality from a user perspective. Use case diagrams depict system behavior, users, and relationships between actors, use cases, and other use cases. The key components of use case diagrams are described as actors, use cases, the system boundary, and relationships. Common relationships include association, extend, generalization, uses, and include. An example use case diagram for a cellular telephone is provided to illustrate these concepts.
Software connectors are architectural elements that model interactions between components. They define rules governing interactions and provide channels for transferring control and data. In software systems, connectors are often not explicitly implemented but distributed across code, while in architectures they are first-class entities with identities. Treating connectors independently from components supports separation of interaction from computation and facilitates software evolution.
This document summarizes code smells and heuristics related to comments, environment setup, function design, and general coding practices from Chapter 17 of Clean Code. It provides 29 guidelines for writing clean code, such as avoiding redundant comments, ensuring building and testing require only one step, keeping functions small with few arguments, removing dead code, and following standard naming conventions.
This presentation discusses peephole optimization. Peephole optimization is performed on small segments of generated code to replace sets of instructions with shorter or faster equivalents. It aims to improve performance, reduce code size, and reduce memory footprint. The working flow of peephole optimization involves scanning code for patterns that match predefined replacement rules. These rules include constant folding, strength reduction, removing null sequences, and combining operations. Peephole optimization functions by replacing slow instructions with faster ones, removing redundant code and stack instructions, and optimizing jumps.
This document provides an overview of problem solving and Python programming. It discusses computational thinking and problem solving, including identifying computational problems, algorithms, building blocks of algorithms, and illustrative problems. It also discusses algorithmic problem solving techniques like iteration and recursion. Finally, it briefly introduces the course titled "GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING".
This document discusses syntax-directed translation and type checking in programming languages. It explains that in syntax-directed translation, attributes are attached to grammar symbols and semantic rules compute attribute values. There are two ways to represent semantic rules: syntax-directed definitions and translation schemes. The document also discusses synthesized and inherited attributes, dependency graphs, and the purpose and components of type checking, including type synthesis, inference, conversions, and static versus dynamic checking.
This document provides an overview of the SOLID principles of object-oriented design:
1. The Single Responsibility Principle states that a class should have one, and only one, reason to change. Having multiple responsibilities makes classes more complex and brittle.
2. The Open-Closed Principle states that software entities should be open for extension but closed for modification. New functionality should be added by extending existing classes rather than modifying them.
3. The Liskov Substitution Principle states that subclasses must be substitutable for their base classes. They should not break the expected behavior of the program.
4. The Interface Segregation Principle states that interfaces should be tailored to specific client needs
When a software program is modularized, there are measures by which the quality of a design of modules and their interaction among them can be measured. These measures are called coupling and cohesion.
This document discusses the SOLID principles of object-oriented design:
- The Single Responsibility Principle states that a class should have one, and only one, reason to change.
- The Open/Closed Principle specifies that software entities should be open for extension but closed for modification.
- The Liskov Substitution Principle dictates that subclasses should behave in the same way as their parent classes.
- The Interface Segregation Principle indicates that client classes should not depend on interfaces they do not use.
- The Dependency Inversion Principle asserts that high-level modules should not depend on low-level modules, but both should depend on abstractions.
The presentation provides examples of
This document discusses code refactoring. It begins by defining refactoring as restructuring source code to improve readability, fix bugs easily, enhance design, and introduce flexibility without changing functionality. It then provides examples of when to refactor, such as when duplicating logic exists, or to enable sharing of logic between methods. The document also discusses problems that can occur with refactoring, like interface changes breaking other applications, and signs that refactoring is needed, such as duplicate code, long methods, or large classes. It provides guidance on how to identify code that needs refactoring and techniques for refactoring different structures. In the end, it discusses the potential benefits of refactoring, such as increased
This document discusses bottom-up parsing and handle pruning. It begins with an example grammar and string. Bottom-up parsing works by repeatedly reducing substrings matching production bodies until reaching the start symbol. A handle is a substring matching a production body whose reduction moves backward through a rightmost derivation. Handle pruning is removing nonterminal children from a parse tree, allowing reconstruction of a rightmost derivation by working backward from handles. The document provides steps for using handle pruning to rebuild a rightmost derivation in reverse from a given string. An example demonstrates finding the handles in a string and reducing based on the corresponding productions to reach the start symbol.
How to improve your code quality? The answer is continuous refactoring. Learn more about refactoring. Know the most frequent code smells (antipatterns), telling when to refactor. Go through the catalog of well-known refactorings, telling how to improve your code.
Refactoring is changing code without altering its external behavior to improve its structure and understandability. Reasons to refactor include making code easier to fix bugs or add features. Testing during refactoring prevents breaking changes. Techniques include renaming, extracting variables/methods, removing temporary variables, moving code between classes, and other object-oriented improvements.
This document discusses functions in C++. It defines what a function is and explains that functions are the building blocks of C++ programs. Functions allow code to be reused, making programs easier to code, modify and maintain. The document covers function definitions, declarations, calls, parameters, return types, scope, and overloading. It also discusses local and global variables as well as pass by value and pass by reference.
Refactoring of code for more readable, scalable modules based on The book titled "Refactoring - Improving the Design of Existing Code" written by Martin Fowler
This presentation is part of one of my webinar in clean code webinar series. The contents are slightly edited to share the information in public domain. In this presentation, I tried to provide detailed introduction to code refactoring practice.
This presentation will be useful for software architects/Managers,developers and QAs. Do share your feedback in comments.
This presentation will introduce you to programming languages that support different programming paradigms and to give you the knowledge of basic concepts and techniques that will allow them to differentiate between various programming paradigms.
Control structures in C++ Programming LanguageAhmad Idrees
This document discusses various control structures in C++ for selection and branching, including if/else statements, switch statements, logical operators, and the assert function. If/else statements allow for two-way selection based on a logical expression being true or false. Switch statements allow for multi-way branching depending on the value of an expression. Logical operators like && and || are used to combine logical expressions. The assert function halts a program if a specified condition is false, which is useful for debugging.
This document discusses refactoring code to improve its design without changing its external behavior. It defines refactoring as changing code structure without modifying functionality. The author is an experienced PHP developer who gives tips on when and how to refactor code, including drivers like preventing decay, reducing duplication, and improving maintainability. Examples are provided of code smells that indicate refactoring may be helpful, like duplicate code, long methods, and large classes. The document concludes by emphasizing the importance of testing before and after refactoring.
The document discusses use case diagrams in object oriented design and analysis. It defines use cases as descriptions of system functionality from a user perspective. Use case diagrams depict system behavior, users, and relationships between actors, use cases, and other use cases. The key components of use case diagrams are described as actors, use cases, the system boundary, and relationships. Common relationships include association, extend, generalization, uses, and include. An example use case diagram for a cellular telephone is provided to illustrate these concepts.
Software connectors are architectural elements that model interactions between components. They define rules governing interactions and provide channels for transferring control and data. In software systems, connectors are often not explicitly implemented but distributed across code, while in architectures they are first-class entities with identities. Treating connectors independently from components supports separation of interaction from computation and facilitates software evolution.
This document summarizes code smells and heuristics related to comments, environment setup, function design, and general coding practices from Chapter 17 of Clean Code. It provides 29 guidelines for writing clean code, such as avoiding redundant comments, ensuring building and testing require only one step, keeping functions small with few arguments, removing dead code, and following standard naming conventions.
This presentation discusses peephole optimization. Peephole optimization is performed on small segments of generated code to replace sets of instructions with shorter or faster equivalents. It aims to improve performance, reduce code size, and reduce memory footprint. The working flow of peephole optimization involves scanning code for patterns that match predefined replacement rules. These rules include constant folding, strength reduction, removing null sequences, and combining operations. Peephole optimization functions by replacing slow instructions with faster ones, removing redundant code and stack instructions, and optimizing jumps.
This document provides an overview of problem solving and Python programming. It discusses computational thinking and problem solving, including identifying computational problems, algorithms, building blocks of algorithms, and illustrative problems. It also discusses algorithmic problem solving techniques like iteration and recursion. Finally, it briefly introduces the course titled "GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING".
This document discusses syntax-directed translation and type checking in programming languages. It explains that in syntax-directed translation, attributes are attached to grammar symbols and semantic rules compute attribute values. There are two ways to represent semantic rules: syntax-directed definitions and translation schemes. The document also discusses synthesized and inherited attributes, dependency graphs, and the purpose and components of type checking, including type synthesis, inference, conversions, and static versus dynamic checking.
This document provides an overview of the SOLID principles of object-oriented design:
1. The Single Responsibility Principle states that a class should have one, and only one, reason to change. Having multiple responsibilities makes classes more complex and brittle.
2. The Open-Closed Principle states that software entities should be open for extension but closed for modification. New functionality should be added by extending existing classes rather than modifying them.
3. The Liskov Substitution Principle states that subclasses must be substitutable for their base classes. They should not break the expected behavior of the program.
4. The Interface Segregation Principle states that interfaces should be tailored to specific client needs
When a software program is modularized, there are measures by which the quality of a design of modules and their interaction among them can be measured. These measures are called coupling and cohesion.
This document discusses the SOLID principles of object-oriented design:
- The Single Responsibility Principle states that a class should have one, and only one, reason to change.
- The Open/Closed Principle specifies that software entities should be open for extension but closed for modification.
- The Liskov Substitution Principle dictates that subclasses should behave in the same way as their parent classes.
- The Interface Segregation Principle indicates that client classes should not depend on interfaces they do not use.
- The Dependency Inversion Principle asserts that high-level modules should not depend on low-level modules, but both should depend on abstractions.
The presentation provides examples of
When and Why Your Code Starts to Smell BadCarlos Eduardo
O documento discute quando e por que códigos começam a feder mal, resumindo:
1) Analisou quando vários tipos de code smells surgem em projetos de software, encontrando que a maioria aparece logo após a criação da classe.
2) Classificou commits que introduziram code smells, encontrando que a maioria ocorreu para corrigir bugs ou adicionar novas funcionalidades.
3) Discutiu ameaças à validade do estudo como possíveis falsos positivos na detecção de code smells.
This document discusses the results of a study on how code smells impact kids' ability to complete different programming tasks. The study found that:
1) Code smells did significantly impact kids' performance, with kids performing better on programs without smells.
2) However, the type of task mattered - explanation tasks were unaffected by smells, while understanding tasks were more impacted by long methods and modification tasks by duplication.
3) In general, smells had a negative effect on kids' ability to understand, modify, and work with code.
This document discusses the history and future directions of code smell research. It covers the origins of refactoring and code smells, definitions of various code smells, methods for identifying code smells, prioritizing refactoring opportunities based on risk analysis, and the need to consider refactoring dependencies and conflicts. The goal is to improve software maintainability and quality through addressing code smells.
A Textual-based Technique for Smell DetectionFabio Palomba
In this paper, we present TACO (Textual Analysis for Code Smell Detection), a technique that exploits textual analysis to detect a family of smells of different nature and different levels of granularity. We run TACO on 10 open source projects, comparing its performance with existing smell detectors purely based on structural information extracted from code components. The analysis of the results indicates that TACO’s precision ranges between 67% and 77%, while its recall ranges between 72% and 84%. Also, TACO often outperforms alternative structural approaches confirming, once again, the usefulness of information that can be derived from the textual part of code components.
The document discusses detecting and removing bad code smells from source code. It describes a tool called HIST that uses change history information to detect code smells. The tool extracts change history from version control logs, analyzes the code changes, and uses the information to detect five types of code smells: divergent change, shotgun surgery, parallel inheritance, blob, and feature envy. An evaluation of HIST shows it improves on static code analysis techniques in detecting these code smells, with F-measure scores for detection ranging from 64-92% compared to 0-48% for static analysis alone. The document concludes by discussing some of the researcher's ongoing and future work related to code smells and refactoring.
Detecting Bad Smells in Source Code using Change History InformationFabio Palomba
Code smells represent symptoms of poor implementation choices. Previous studies found that these smells make source code more difficult to maintain, possibly also increasing its fault-proneness. There are several approaches that identify smells based on code analysis techniques. However, we observe that many code smells are intrinsically characterized by how code elements change over time. Thus, relying solely on structural information may not be sufficient to detect all the smells accurately. We propose an approach to detect five different code smells, namely Divergent Change, Shotgun Surgery, Parallel Inheritance, Blob, and Feature Envy, by exploiting change history information mined from versioning systems. We applied approach, coined as HIST (Historical Information for Smell deTection), to eight software projects written in Java, and wherever possible compared with existing state-of-the-art smell detectors based on source code analysis. The results indicate that HIST’s precision ranges between 61% and 80%, and its recall ranges between 61% and 100%. More importantly, the results confirm that HIST is able to identify code smells that cannot be identified through approaches solely based on code analysis.
Slides from DevOps Pro, Vilnius, Lithuania.
Abstract: The wide adoption of configuration management and the increasing size and complexity of the associated code, prompt for assessing, maintaining, and improving the configuration code’s quality. We can leverage traditional software engineering knowledge and best practices to develop and maintain high quality configuration code. This talk brings the smell metaphor to configuration domain. This talk introduces configuration smells, their types with various examples, tools to detect them, and suggestions to refactor them.
The document discusses code smells, which are surface indications that may suggest deeper problems in the code. It lists several types of code smells such as long methods, large classes, primitive obsession, and duplicate code. It then provides examples of refactoring code to eliminate code smells by improving structure, reducing complexity, increasing readability and modifying classes, methods and names for better organization and design.
Refactoring: Improve the design of existing codeValerio Maggio
Refactoring: Improve the design of existing code
Software Engineering class on main refactoring techniques and bad smells reported in the famous Fawler's book on this topic!
This document discusses bad smells in code that indicate refactoring may be needed. It defines refactoring as restructuring code without changing its external behavior to improve design, readability, and maintainability. Common bad smells include duplicated code, long or complex methods and classes, unused variables, primitive data types when objects could be used, and code that depends too much on other classes rather than being self-contained. The document provides examples of refactoring techniques to address each smell, such as extracting methods, replacing conditionals with polymorphism, and removing unnecessary dependencies between classes.
The document discusses refactoring code to improve its design. It defines refactoring as improving code design without changing its external behavior. Refactoring involves identifying "design smells" - symptoms of poor design quality like rigidity, fragility, and opacity. Common smells include long methods, large classes, primitive obsessions, and duplicate code. The document outlines different categories of smells like "bloaters", "object-orientation abusers", and "couplers" that increase coupling between classes. It advises using refactoring tools and techniques to address smells one by one in a refactoring cycle to continuously improve code quality.
This document discusses refactoring, which involves restructuring existing code without changing its external behavior or functionality. It provides definitions of refactoring and describes best practices for refactoring code, such as taking small, incremental steps and verifying that automated tests still pass after each change. Specific refactoring techniques are also explained, like extracting duplicate code into methods, removing unnecessary complexity or duplication, and consolidating conditional expressions for clarity. The document cautions against fixing bugs during refactoring and emphasizes making changes in a way that simplifies the code and removes code smells.
Code smells are not bugs or errors. Instead, these are absolute violations of the fundamentals of developing software that decrease the quality of code.
Refactoring is changing code without altering its external behavior but improving its internal structure and design. It makes code more maintainable, understandable and flexible. Some signs that refactoring is needed include duplicated code, long methods, large classes, and code that is difficult to modify. Common refactoring techniques include extracting methods, moving methods between classes, introducing new classes/objects, and simplifying conditional statements. Refactoring helps developers write better code more quickly and prevents design deterioration over time.
The document discusses the importance of clean code and avoiding software rot. It outlines characteristics of rotting software like rigidity, fragility, immobility and viscosity. The solution discussed is adopting good practices like those in software craftsmanship and clean code skills. These include principles like DRY, keeping methods small, using descriptive names and comments, following SOLID principles, and prioritizing readability and maintainability over optimizations.
Some of the most common and easy-to-calculate/easy-to-measure code metrics. Understanding these can help you make your code better: avoiding code rot and writing maintainable code all starts here. Content is created for C# .net, however, the underlying principles apply to other languages/frameworks as well.
The document contains interview questions and answers about various C# concepts. Some of the key points covered include:
- C# supports single inheritance but not multiple inheritance, instead interfaces should be used.
- Abstract classes cannot be instantiated and must be inherited from, while interfaces contain only abstract method signatures that must be implemented.
- The System.String class is immutable while System.StringBuilder is mutable and more efficient for string manipulation.
- Exceptions should generally not be thrown within application code, and instead the proper error handling code should be written.
- Debugging tools that come with the .NET SDK include CorDBG and DbgCLR, while the Visual Studio debugger uses DbgCLR.
-
Code Refactoring is a disciplined technique for restructuring existing code without changing its external behavior. It improves code efficiency, readability, and maintainability. Bad code smells indicate deeper problems, such as classes or methods that are too large ("bloaters"), code that prevents changes ("change preventers"), or duplicated code fragments ("data clumps"). Refactoring techniques extract, move, or rename code elements to eliminate bad smells and clarify the code structure. Regular refactoring transforms code into a more efficient and maintainable form.
Rails Conf 2014 Concerns, Decorators, Presenters, Service-objects, Helpers, H...Justin Gordon
Slides Ruby Conf 2014 on using simple techniques to create slimer, clearer models, controllers, and views in Ruby on Rails.
blog: http://www.railsonmaui.com
Code samples: https://github.com/justin808/fat-code-refactoring-techniques
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...DevDay.org
People talk about ‘clean code’ and ‘best practices’ but what do they really mean? We are going to explore these topics and share with you the fundamentals of clean code and how to be a good teammate and a coder people will respect even after they read your code!
The document summarizes the second meeting of a Software Craftsmanship group. The agenda included discussing bad and good code, code smells, tools, and hands-on activities. Examples of code smells like duplicated code, long methods, large classes, and long parameter lists were presented. Attendees participated in demo activities to identify code smells in code samples and refactor code. The goals were to learn how to recognize poor code quality and refactor code to eliminate code smells.
C# coding standards, good programming principles & refactoringEyob Lube
The document discusses C# coding standards and principles of good programming. It covers topics such as the importance of coding standards, principles like KISS and SOLID, general naming conventions, and refactoring code for better design. Specific points made include that coding standards create consistency, enable quicker understanding of code, and facilitate collaboration. The SOLID principles of single responsibility, open/closed, Liskov substitution, interface segregation and dependency inversion are explained. Meaningful naming is also emphasized, with examples of how intention-revealing names can greatly improve readability and maintainability of code.
you will learn how to create your own methods with or without return values, invoke a method with or without parameters, and apply method abstraction in the program design.
The document discusses various approaches to implementing object-oriented programming languages, including compilers vs interpreters, virtual method tables, inheritance, and just-in-time compilation. It covers topics like how receivers are passed as arguments, name encoding for unique method identifiers, inherited vs overridden methods, problems with multiple inheritance, bytecode interpreters, and using dispatch tables for dynamic languages. The key implementation techniques are using virtual method tables to dispatch overridden methods at runtime and just-in-time compilers that translate bytecode to native machine code for improved performance.
The document discusses using local variables in methods. Local variables are created when a method begins, are private to the method, and are destroyed when the method exits. While local variables are private to each method, class variables can be used to share data between methods. The compiler will not warn about naming conflicts between local and class variables with the same name.
This document discusses methods in Java. It begins with an introduction that defines methods as collections of statements that perform specific tasks and may return results. It then covers method syntax, declaration, types (predefined and user-defined), ways to create methods (instance and static), method signatures, naming conventions, calling methods, creating static methods, applying instance methods, memory allocation for method calls, and advantages of using methods such as reusability and improved readability. The presentation concludes with an acknowledgement slide thanking faculty, parents, and fellow students for their assistance and support.
A Study on Code Smell Detection with Refactoring Tools in Object Oriented Lan...ijcnes
A code smell is an indication in the source code that hypothetically indicates a design problem in the equivalent software. The Code smells are certain code lines which makes problems in source code. It also means that code lines are bad design shape or any code made by bad coding practices. Code smells are structural characteristics of software that may indicates a code or drawing problem that makes software hard to evolve and maintain, and may trigger refactoring of code. In this paper, we proposed some success issues for smell detection tools which can assistance to develop the user experience and therefore the acceptance of such tools. The process of detecting and removing code smells with refactoring can be overwhelming.
The document summarizes new features in C# 3.0 and VB 9.0 in Visual Studio 2008, including extension methods, lambda expressions, LINQ, and expression trees. Extension methods allow extending existing types without inheritance. Lambda expressions provide a compact way to write anonymous functions. LINQ allows querying over different data sources using a common syntax. Expression trees represent LINQ queries as data structures for translation into other languages like SQL.
These slides, covering the topics of Software Maintenance and Evolution, are introductory slides to the course LINGI2252 “Software Maintenance and Evolution”, given by Prof. Kim Mens at UCL, Belgium
An introductory lecture on Context-Oriented Programming, part of the course LINGI2252 “Software Maintenance and Evolution”, given by Prof. Kim Mens at UCL, Belgium. This particular lecture was made by Dr. Sebastian Gonzalez in close collaboration with Prof. Kim Mens.
Software Reuse and Object-Oriented Programmingkim.mens
These slides on Software Reuse and Object-Oriented Programming are part of the course LINGI2252 “Software Maintenance and Evolution”, given by Prof. Kim Mens at UCL, Belgium
These slides on Object-Oriented Design Heuristics are part of the course LINGI2252 “Software Maintenance and Evolution”, given by Prof. Kim Mens at UCL, Belgium.
This presentation on Object-Oriented Application Frameworks is part of a larger course LINGI2252 on Software Maintenance and Evolution, given at UCL university in Belgium.
Towards a Context-Oriented Software Implementation Frameworkkim.mens
Context-aware systems must manage the dynamic selection, activation, and execution of feature variants according to changing contexts, detected from data gathered from their surrounding execution environment. Many context-oriented programming languages focus only on the implementation level by providing appropriate language abstractions for implementing behavioural variations that can adapt dynamically to changing contexts. They often ignore or presuppose the existence of mechanisms to deal with earlier aspects such as the gathering of sensory input and context discovery. In this presentation we discuss a layered software architecture that reconciles all these aspects in a single implementation framework, which can be customised by application programmers into actual context-aware applications. This framework and a simulator to test applications build using this framework we recently implemented in Ruby and Ruby on Rails.
Towards a Taxonomy of Context-Aware Software Variabilty Approacheskim.mens
Modern software systems demand more and more smart capabilities depending on their context of use, as well as the ability to dynamically adapt these capabilities according to sensed context changes. This requires appropriate techniques for modelling, representing and handling context-aware software variability. While traditional variability modelling approaches like feature orientation and software product lines are evolving to address the increased dynamicity and context specificity required for this new generation of software systems, new paradigms such as context-oriented programming have emerged. Although developed independently, since they address similar issues, many similarities exist between these approaches. The purpose of this work is to define, categorise and compare key concepts shared by these approaches.
Such a taxonomy is a first step towards a better understanding of the differences and similarities between different approaches for managing context-aware software variability, and to achieve a cross-fertilisation between them.
An introductory lecture on context-oriented programming, part of a full course on Programming Paradigms at UCL university in Belgium, focussing on reflection and meta programming techniques in a variety of languages. This particular lecture was made by Sebastian Gonzalez in close collaboration with Kim Mens.
This document provides an overview of reflection and metaprogramming by defining key concepts and terminology. It discusses computational systems, programs, meta systems, and meta programs. Reflection is defined as a program examining or changing its own implementation at runtime. For a system to be reflective, its concepts must be reified and it must have a causal connection between the system and what it represents. Types of reflection include introspection, structural reflection, and computational reflection. Reflective systems can be implemented using towers of interpreters or reflective architectures with meta-objects.
This document discusses advanced reflection features in Java, including dynamic proxies, call stack introspection, and instrumentation. It begins with an overview of dynamic proxies using the Proxy class and InvocationHandler interface. It then covers examining the call stack using Throwable and StackTraceElement. Finally, it describes instrumentation using the java.lang.instrument package to modify bytecode at runtime, such as logging class loads or tracing method calls. Examples are provided for each topic.
An introduction to the basics of reflection in the object-oriented programming language Java, part of a full lecture on Programming Paradigms at UCL university in Belgium, focussing on the programming languages Smalltalk, Ruby and Java, with reflection and meta programming as underlying theme.
An introduction to some advanced language features of the object-oriented programming language Ruby, part of a full lecture on Programming Paradigms at UCL university in Belgium, focussing on the programming languages Smalltalk, Ruby and Java, with reflection and meta programming as underlying theme. This lecture looks into the Ruby features of higher-order programming (lambdas), singleton methods, mixin modules, reflection and metaprogramming.
A quick introduction to the object-oriented programming language Ruby, part of a full lecture on Programming Paradigms at UCL university in Belgium, focussing on the programming languages Smalltalk, Ruby and Java, with reflection and meta programming as underlying theme.
A quick introduction to the object-oriented programming language Smalltalk, part of a full lecture on Programming Paradigms at UCL university in Belgium, focussing on the programming languages Smalltalk, Ruby and Java, with reflection and meta programming as underlying theme.
A gentle and intuitive introduction to reflection and meta programming, part of a full lecture on programming paradigms at UCL university in Belgium, with reflection and meta programming as theme. (Further lectures focus more in depth on reflection and meta programming in a variety of languages such as Smalltalk, Ruby and Java.)
Managing the Evolution of Information Systems with Intensional Views and Rela...kim.mens
This document describes research into managing consistency in evolving information systems. The researchers developed an initial solution to detect inconsistencies when merging data from multiple sources for an IP phone localization case study at a university. This involved scripts to extract data from different sources and merge it daily. Numerous errors and inconsistencies were found in the individual sources and merged data. To address this, the researchers improved the solution by combining intensional views and relational algebra to define and check constraints across data tables via a user interface. This allowed expressing and detecting inconsistencies more easily. The approach was validated on the phone localization data.
Usage contracts (presented at SATToSE 2014 in L'Aquila, Italy)kim.mens
Usage Contracts (or uContracts for short) offer a simple unit-testing like way for letting programmers document and check conformance to structural source-code regularities, based on a “contract” metaphor. They provide immediate feedback to developers during coding. Essentially, they can be seen as an embedded DSL which remains close to the host programming language and with a tight but not coercive integration with the host IDE, to avoid adoption issues.
This work was conducted by Angela Lozano, Andy Kellens and Kim Mens.
Developers often encode design knowledge through structural regularities such as API usage protocols, coding idioms and naming conventions. As these regularities express how the source code should be structured, they provide vital information for developers (re)using that code. Adherence to such regularities tends to deteriorate over time when they are not documented and checked explicitly. Our uContracts tool and approach allows to codify and verify such regularities as ‘usage contracts’. The contracts are expressed in an internal domain-specific language that is close to the host programming language, the tool is tightly integrated with the development environment and provides immediate feedback during development when contracts get breached, but the tool is not coercive and allows the developer to decide if, when and how to correct the broken contracts (the tool just highlights the errors and warnings in the integrated development environment). In spirit, the approach is very akin to unit testing, except that we do not test behaviour, but rather verify program structure. The tool, of which some screenshots can be found below, was prototyped in the Pharo dialect of the Smalltalk programming language.
This work was conducted by Angela Lozano, Andy Kellens and Kim Mens.
This presentation was provided by Steph Pollock of The American Psychological Association’s Journals Program, and Damita Snow, of The American Society of Civil Engineers (ASCE), for the initial session of NISO's 2024 Training Series "DEIA in the Scholarly Landscape." Session One: 'Setting Expectations: a DEIA Primer,' was held June 6, 2024.
Strategies for Effective Upskilling is a presentation by Chinwendu Peace in a Your Skill Boost Masterclass organisation by the Excellence Foundation for South Sudan on 08th and 09th June 2024 from 1 PM to 3 PM on each day.
This document provides an overview of wound healing, its functions, stages, mechanisms, factors affecting it, and complications.
A wound is a break in the integrity of the skin or tissues, which may be associated with disruption of the structure and function.
Healing is the body’s response to injury in an attempt to restore normal structure and functions.
Healing can occur in two ways: Regeneration and Repair
There are 4 phases of wound healing: hemostasis, inflammation, proliferation, and remodeling. This document also describes the mechanism of wound healing. Factors that affect healing include infection, uncontrolled diabetes, poor nutrition, age, anemia, the presence of foreign bodies, etc.
Complications of wound healing like infection, hyperpigmentation of scar, contractures, and keloid formation.
Chapter wise All Notes of First year Basic Civil Engineering.pptxDenish Jangid
Chapter wise All Notes of First year Basic Civil Engineering
Syllabus
Chapter-1
Introduction to objective, scope and outcome the subject
Chapter 2
Introduction: Scope and Specialization of Civil Engineering, Role of civil Engineer in Society, Impact of infrastructural development on economy of country.
Chapter 3
Surveying: Object Principles & Types of Surveying; Site Plans, Plans & Maps; Scales & Unit of different Measurements.
Linear Measurements: Instruments used. Linear Measurement by Tape, Ranging out Survey Lines and overcoming Obstructions; Measurements on sloping ground; Tape corrections, conventional symbols. Angular Measurements: Instruments used; Introduction to Compass Surveying, Bearings and Longitude & Latitude of a Line, Introduction to total station.
Levelling: Instrument used Object of levelling, Methods of levelling in brief, and Contour maps.
Chapter 4
Buildings: Selection of site for Buildings, Layout of Building Plan, Types of buildings, Plinth area, carpet area, floor space index, Introduction to building byelaws, concept of sun light & ventilation. Components of Buildings & their functions, Basic concept of R.C.C., Introduction to types of foundation
Chapter 5
Transportation: Introduction to Transportation Engineering; Traffic and Road Safety: Types and Characteristics of Various Modes of Transportation; Various Road Traffic Signs, Causes of Accidents and Road Safety Measures.
Chapter 6
Environmental Engineering: Environmental Pollution, Environmental Acts and Regulations, Functional Concepts of Ecology, Basics of Species, Biodiversity, Ecosystem, Hydrological Cycle; Chemical Cycles: Carbon, Nitrogen & Phosphorus; Energy Flow in Ecosystems.
Water Pollution: Water Quality standards, Introduction to Treatment & Disposal of Waste Water. Reuse and Saving of Water, Rain Water Harvesting. Solid Waste Management: Classification of Solid Waste, Collection, Transportation and Disposal of Solid. Recycling of Solid Waste: Energy Recovery, Sanitary Landfill, On-Site Sanitation. Air & Noise Pollution: Primary and Secondary air pollutants, Harmful effects of Air Pollution, Control of Air Pollution. . Noise Pollution Harmful Effects of noise pollution, control of noise pollution, Global warming & Climate Change, Ozone depletion, Greenhouse effect
Text Books:
1. Palancharmy, Basic Civil Engineering, McGraw Hill publishers.
2. Satheesh Gopi, Basic Civil Engineering, Pearson Publishers.
3. Ketki Rangwala Dalal, Essentials of Civil Engineering, Charotar Publishing House.
4. BCP, Surveying volume 1
This presentation includes basic of PCOS their pathology and treatment and also Ayurveda correlation of PCOS and Ayurvedic line of treatment mentioned in classics.
বাংলাদেশের অর্থনৈতিক সমীক্ষা ২০২৪ [Bangladesh Economic Review 2024 Bangla.pdf] কম্পিউটার , ট্যাব ও স্মার্ট ফোন ভার্সন সহ সম্পূর্ণ বাংলা ই-বুক বা pdf বই " সুচিপত্র ...বুকমার্ক মেনু 🔖 ও হাইপার লিংক মেনু 📝👆 যুক্ত ..
আমাদের সবার জন্য খুব খুব গুরুত্বপূর্ণ একটি বই ..বিসিএস, ব্যাংক, ইউনিভার্সিটি ভর্তি ও যে কোন প্রতিযোগিতা মূলক পরীক্ষার জন্য এর খুব ইম্পরট্যান্ট একটি বিষয় ...তাছাড়া বাংলাদেশের সাম্প্রতিক যে কোন ডাটা বা তথ্য এই বইতে পাবেন ...
তাই একজন নাগরিক হিসাবে এই তথ্য গুলো আপনার জানা প্রয়োজন ...।
বিসিএস ও ব্যাংক এর লিখিত পরীক্ষা ...+এছাড়া মাধ্যমিক ও উচ্চমাধ্যমিকের স্টুডেন্টদের জন্য অনেক কাজে আসবে ...
How to Make a Field Mandatory in Odoo 17Celine George
In Odoo, making a field required can be done through both Python code and XML views. When you set the required attribute to True in Python code, it makes the field required across all views where it's used. Conversely, when you set the required attribute in XML views, it makes the field required only in the context of that particular view.
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPRAHUL
This Dissertation explores the particular circumstances of Mirzapur, a region located in the
core of India. Mirzapur, with its varied terrains and abundant biodiversity, offers an optimal
environment for investigating the changes in vegetation cover dynamics. Our study utilizes
advanced technologies such as GIS (Geographic Information Systems) and Remote sensing to
analyze the transformations that have taken place over the course of a decade.
The complex relationship between human activities and the environment has been the focus
of extensive research and worry. As the global community grapples with swift urbanization,
population expansion, and economic progress, the effects on natural ecosystems are becoming
more evident. A crucial element of this impact is the alteration of vegetation cover, which plays a
significant role in maintaining the ecological equilibrium of our planet.Land serves as the foundation for all human activities and provides the necessary materials for
these activities. As the most crucial natural resource, its utilization by humans results in different
'Land uses,' which are determined by both human activities and the physical characteristics of the
land.
The utilization of land is impacted by human needs and environmental factors. In countries
like India, rapid population growth and the emphasis on extensive resource exploitation can lead
to significant land degradation, adversely affecting the region's land cover.
Therefore, human intervention has significantly influenced land use patterns over many
centuries, evolving its structure over time and space. In the present era, these changes have
accelerated due to factors such as agriculture and urbanization. Information regarding land use and
cover is essential for various planning and management tasks related to the Earth's surface,
providing crucial environmental data for scientific, resource management, policy purposes, and
diverse human activities.
Accurate understanding of land use and cover is imperative for the development planning
of any area. Consequently, a wide range of professionals, including earth system scientists, land
and water managers, and urban planners, are interested in obtaining data on land use and cover
changes, conversion trends, and other related patterns. The spatial dimensions of land use and
cover support policymakers and scientists in making well-informed decisions, as alterations in
these patterns indicate shifts in economic and social conditions. Monitoring such changes with the
help of Advanced technologies like Remote Sensing and Geographic Information Systems is
crucial for coordinated efforts across different administrative levels. Advanced technologies like
Remote Sensing and Geographic Information Systems
9
Changes in vegetation cover refer to variations in the distribution, composition, and overall
structure of plant communities across different temporal and spatial scales. These changes can
occur natural.
A workshop hosted by the South African Journal of Science aimed at postgraduate students and early career researchers with little or no experience in writing and publishing journal articles.
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Bad Code Smells
1. BAD CODE SMELLS
LINGI2252 – PROF. KIM MENS
* These slides are part of the course LINGI2252 “Software Maintenance and Evolution”,
given by Prof. Kim Mens at UCL, Belgium
*
3. Bad Smells in Code
Reference
Martin Fowler, Refactoring: Improving the Design of Existing Code.
Addison Wesley, 2000. ISBN: 0201485672
Chapter 3: Bad Smells in Code, by Kent Beck and Martin Fowler
Overview of this presentation
Introduction
A classification of bad smells, including a
detailed illustration of some of them
Conclusion
3
4. Introduction
Bad Smells = “bad smelling code”
indicate that your code is ripe for refactoring
Refactoring is about
how to change code by applying refactorings
Bad smells are about
when to modify it
4
5. Bad Smells
Allow us to identify
what needs to be changed in order to improve the code
A recipe book to help us choose the right refactoring pattern
No precise criteria
More to give an intuition and indications
Goal : a more “habitable” code.
5
6. Side note: Habitable code
Habitable code is code in which developers feel at home
(even when the code was not written by them)
Symptoms of inhabitable code include
overuse of abstraction or inappropriate compression
Habitable code should be easy to read, easy to change
Software needs to be habitable because it always has to change
[Richard P. Gabriel, Patterns of Software: Tales from the
Software Community, Oxford University Press, 1996]
6
7. B. CLASSIFICATION OF BAD SMELLS
INCLUDING A DETAILED DISCUSSION OF 5 OF THEM
LINGI2252 – PROF. KIM MENS
9. Bad Smells : Classification
The top crime
Class / method organisation
Large class, Long Method, Long Parameter List, Lazy Class, Data Class, …
Lack of loose coupling or cohesion
Inappropriate Intimacy, Feature Envy, Data Clumps, …
Too much or too little delegation
Message Chains, Middle Man, …
Non Object-Oriented control or data structures
Switch Statements, Primitive Obsession, …
Other : Comments
9
10. Bad Smells : Alternative Classification
Bloaters are too large to handle
Object-orientation abusers
do not respect OO principles
Change preventers stand in the way of change
Dispensables are things you could do without
Couplers contribute to excessive coupling between
classes
Other smells
10
11. Bad Smells : Classification
The top crime
Class / method organisation
Large class, Long Method, Long Parameter List, Lazy Class, Data Class, …
Lack of loose coupling or cohesion
Inappropriate Intimacy, Feature Envy, Data Clumps, …
Too much or too little delegation
Message Chains, Middle Man, …
Non Object-Oriented control or data structures
Switch Statements, Primitive Obsession, …
Other : Comments
11
13. Code duplication
Duplicated code is the number 1 in the stink parade !
We have duplicated code when we have
the same code structure in more than one place
Why is duplicated code bad?
A fundamental rule of thumb :
it’s always better to have a unified code
13
14. 14
Code duplication example 1
public double ringSurface(r1,r2) {
// calculate the surface of the first circle
double surf1 = bigCircleSurface(r1);
// calculate the surface of the second circle
double surf2 = smallCircleSurface(r2);
return surf1 - surf2;
}
private double bigCircleSurface(r1) {
pi = 4* ( arctan 1/2 + arctan 1/3 );
return pi*sqr(r1);
}
private double smallCircleSurface(r2) {
pi = 4* ( arctan 1/2 + arctan 1/3 );
return pi*sqr(r2);
}
15. 15
Code duplication example 2
Class
method1
method2
method3
code
code
code
code
Same expression in two
or more methods of the
same class
16. 16
Code duplication example 3
methodA
code
Class
methodB
code
SubClassA SubClassB
Same expression in two
sibling classes
inherits
from
17. 17
Code duplication example 4
methodA
code
methodB
code
ClassA ClassB
Same expression in two
unrelated classes
18. 18
Code duplication: Refactoring Patterns (1)
public double ringSurface(r1,r2) {
// calculate the surface of the first circle
double surf1 = surface(r1);
//calculate the surface of the second circle
double surf2 = surface(r2);
return surf1-surf2;
}
private double surface(r) {
pi = 4* ( arctan 1/2 + arctan 1/3 );
return pi*sqr(r); }
Extract method
+
Rename method
19. 19
Code duplication: Refactoring Patterns (2)
Class
method1
method2
method3
code
code
code
code
Same expression in two or
more methods of the same class
Extract
method
Class
method1
method2
Call methX()
Call methX()
Call methX()
method3
Call methX()
methX()
xcodeReturn
20. 20
Code duplication: Refactoring Patterns (3)
Same expression in
two sibling classes
Extract method
+
Pull up field
Same code
Extract method
+
Form Template
Method
Similar
code
Substitute
algorithm
Different
algorithm
Class
SubClass A SubClass B
21. 21
Code duplication: Refactoring Patterns (4)
methodA
ClassA ClassB
Same expression
in two unrelated classes
Call ClassC.methX()
methodB
Call ClassC.methX()
methX()
codereturn
Extract
class
Extract
class
code code
22. 22
Code duplication: Refactoring Patterns (4’)
methodA
ClassA ClassB
Same expression
in two unrelated classes
Call ClassC.methXcode()
methodB
Call ClassA.methodA()
If the method really belongs in one
of the two classes, keep it there
and invoke it from the other class
code code
23. Bad Smells : Classification
The top crime
Class / method organisation
Large class, Long Method, Long Parameter List, Lazy Class, Data Class, …
Lack of loose coupling or cohesion
Inappropriate Intimacy, Feature Envy, Data Clumps, …
Too much or too little delegation
Message Chains, Middle Man, …
Non Object-Oriented control or data structures
Switch Statements, Primitive Obsession, …
Other : Comments
23
24. Large Class
A large class is a class that
is trying to do too much
Often shows up as too many instance variables
Use Extract Class or Extract Subclass to bundle
variables
choose variables that belong together in the extracted class
common prefixes and suffixes may suggest which ones may
go together, e.g. depositAmount and depositCurrency
24* Cartoon borrowed from https://sourcemaking.com/refactoring for didactic purposes only.
*
25. Large Class
A class may also be too large in the sense that it has too much code
likely some code inside the class is duplicated
solve it by extracting the duplicated code in separate methods
using Extract Method
or move part of the code to a new class, using Extract Class
or Extract Subclass
if need be, move existing or extracted methods to another class
using Move Method
25
26. Long Parameter List
In procedural programming
languages, we pass as parameters
everything needed by a subroutine
Because the only alternative is
global variables
With objects you don’t pass
everything the method needs
26* Cartoon borrowed from https://sourcemaking.com/refactoring for didactic purposes only.
*
27. Long Parameter List
Long parameter lists are hard to understand
Pass only the needed number of variables
Use Replace Parameter with Method when
you can get the data in one parameter by making
a request of an object you already know about
27
28. Lazy Class
Each class cost money (and brain cells) to maintain and understand
A class that isn't doing enough to pay for itself should be eliminated
It might be a class that was added because of changes that were
planned but not made
Use Collapse Hierarchy or Inline Class to eliminate the class.
Person
name
getTelephoneNumber
Telephone Number
areaCode
number
getTelephoneNumber
Person
name
areaCode
number
getTelephoneNumber
28* Cartoon borrowed from https://sourcemaking.com/refactoring for didactic purposes only.
*
29. Data Class
Classes with just fields, getters, setters and nothing else
If there are public fields, use Encapsulate Field
For fields that should not be changed use Remove
Setting Method
29* Cartoon borrowed from https://sourcemaking.com/refactoring for didactic purposes only.
*
30. Long Method
Object programs live best and longest with short methods
New OO programmers feel that OO programs are endless sequences
of delegation
Older languages carried an overhead in subroutine calls which deterred
people from small methods
There is still an overhead to the reader of the code because you
have to switch context to see what the subprocedure does (but the
development environment helps us)
Important to have a good name for small methods
Rename Method
30
31. Long Method
The longer a procedure is, the more difficult it is to
understand what the code does
More difficult to read
Bad for maintainability
More difficult to make modifications
To summarise… less habitable !
31* Cartoon borrowed from https://sourcemaking.com/refactoring for didactic purposes only.
*
32. Long Method
Too avoid too long methods, decompose methods in many
small ones
Heuristic: whenever you feel the need to comment
something, write a method instead
containing the code that was commented
named it after the intention of the code
rather than how it does it
Even a single line is worth extracting if it needs explanation
32
33. Long Method: Example
33
void printOwing() {
Enumeration e = _orders.elements();
double outstanding = 0.0;
// Print banner
System.out.println(“******************“);
System.out.println(“***** Customer *****“);
System.out.println(“******************“);
// Calcultate outstanding
While (e.hasMoreElements()) {
Order each = (Order) e.nextElement();
outstanding += each.getAmount();
}
// Print details
System.out.println(“name: “ + _name);
System.out.println(“amount” + outstanding);
}
Example was
shortened to
fit on 1 slide
34. Long Method: Refactoring patterns
99% of the time, all we have to do to shorten a method is
Extract Method
Find parts of the method that seem to go together nicely and
extract them into a new method.
It can lead to problems…
Many temps : use Replace Temp with Query
Long lists of parameters can be slimmed down with
Introduce Parameter Object
34
35. Long Method: Refactoring patterns
But how to identify the clumps of code to extract ?
Look for comments…
A block of code with a comment that tells you what it is
doing can be replaced by a method whose name is based on
the comments
Loops also give signs for extractions…
Extract the loop and the code within the loop into its own
method.
35
36. Long Method Example revisited
36
void printOwing() {
Enumeration e = _orders.elements();
double outstanding = 0.0;
// Print banner
System.out.println(“******************“);
System.out.println(“***** Customer *****“);
System.out.println(“******************“);
// Calcultate outstanding
While (e.hasMoreElements()) {
Order each = (Order) e.nextElement();
outstanding += each.getAmount();
}
// Print details
System.out.println(“name: “ + _name);
System.out.println(“amount” + outstanding);
}
37. Long Method Example revisited
37
void printOwing() {
Enumeration e = _orders.elements();
double outstanding = 0.0;
// Print banner
System.out.println(“******************“);
System.out.println(“***** Customer *****“);
System.out.println(“******************“);
// Calcultate outstanding
While (e.hasMoreElements()) {
Order each = (Order) e.nextElement();
outstanding += each.getAmount();
}
// Print details
System.out.println(“name: “ + _name);
System.out.println(“amount” + outstanding);
}
38. Long Method Example revisited
38
void printOwing() {
Enumeration e = _orders.elements();
double outstanding = 0.0;
printBanner();
// Calcultate outstanding
While (e.hasMoreElements()) {
Order each = (Order) e.nextElement();
outstanding += each.getAmount();
}
// Print details
System.out.println(“name: “ + _name);
System.out.println(“amount” + outstanding);
}
void printBanner() {
System.out.println(“******************“);
System.out.println(“***** Customer ****“);
System.out.println(“******************“);
}
1.
Extract Method
Trivially easy !
39. Long Method Example revisited
39
void printOwing() {
Enumeration e = _orders.elements();
double outstanding = 0.0;
printBanner();
// Calcultate outstanding
While (e.hasMoreElements()) {
Order each = (Order) e.nextElement();
outstanding += each.getAmount();
}
// Print details
System.out.println(“name: “ + _name);
System.out.println(“amount” + outstanding);
}
void printBanner() {
System.out.println(“******************“);
System.out.println(“***** Customer ****“);
System.out.println(“******************“);
}
40. Long Method Example revisited
40
2.
Extract Method
Using Local Variables
void printOwing() {
Enumeration e = _orders.elements();
double outstanding = 0.0;
printBanner();
// Calcultate outstanding
While (e.hasMoreElements()) {
Order each = (Order) e.nextElement();
outstanding += each.getAmount();
}
printDetails(outstanding);
}
void printDetails(double outstanding) {
System.out.println(“name: “ + _name);
System.out.println(“amount” + outstanding);
}
void printBanner() { … }
41. Long Method Example revisited
41
void printOwing() {
Enumeration e = _orders.elements();
double outstanding = 0.0;
printBanner();
// Calcultate outstanding
While (e.hasMoreElements()) {
Order each = (Order) e.nextElement();
outstanding += each.getAmount();
}
printDetails(outstanding);
}
void printDetails(double outstanding) {
System.out.println(“name: “ + _name);
System.out.println(“amount” + outstanding);
}
void printBanner() { … }
42. Long Method Example revisited
42
3.
Extract Method
Reassigning a Local
Variable
void printOwing() {
printBanner();
double outstanding = getOutstanding();
printDetails(outstanding);
}
double getOutstanding() {
Enumeration e = _orders.elements();
double result = 0.0;
While (e.hasMoreElements()) {
Order each = (Order) e.nextElement();
result += each.getAmount();
}
return result;
}
void printDetails(double outstanding) {…}
void printBanner() { … }
43. Bad Smells : Classification
The top crime
Class / method organisation
Large class, Long Method, Long Parameter List, Lazy Class, Data Class, …
Lack of loose coupling or cohesion
Inappropriate Intimacy, Feature Envy, Data Clumps, …
Too much or too little delegation
Message Chains, Middle Man, …
Non Object-Oriented control or data structures
Switch Statements, Primitive Obsession, …
Other : Comments
43
44. Coupling and cohesion
Coupling is the degree to which different software
components depend on each other
Cohesion is the degree to which the elements within a
software module belong together
Low cohesion and tight coupling are bad smells (why?)
44
45. Inappropriate Intimacy
Pairs of classes that know too much
about each other's private details
Use Move Method and Move
Field to separate the pieces to
reduce the intimacy
If subclasses know more about their
parents than their parents would like
them to know
Apply Replace Inheritance
with Delegation
45* Cartoon borrowed from https://sourcemaking.com/refactoring for didactic purposes only.
*
46. Data Clumps
A certain number of data items in lots of places
Examples: fields in a couple of classes, parameters in many
method signatures
Ought to be made into their own object
When the clumps are fields, use Extract Class to turn them
into an object
When the clumps are parameters, use Introduce Parameter
Object to slim them down
46
47. Feature Envy
When a method seems more interested in a class
other than the one it actually is in
47* Cartoon borrowed from https://sourcemaking.com/refactoring for didactic purposes only.
*
48. Feature Envy
In other words, When a method invokes too many times
methods on another object to calculate some value
Why is it bad to invoke a zillion times methods from
another class?
Because, in general, it is not logical from an OO
point of view.
Put things together that change together !
48
49. Feature Envy: Example (1)
public Void mainFeatureEnvy () {
OtherClass.getMethod1();
OtherClass.getMethod2();
OtherClass.getMethod3();
OtherClass.getMethod4();
}
public Void getMethod1 () { … }
public Void getMethod2 () { … }
public Void getMethod3 () { … }
public Void getMethod4 () { … }
OtherClass
49
50. Feature Envy: Refactoring Patterns (1)
First solution : Move Method
Public Void getMethod1 () { … }
Public Void getMethod2 () { … }
Public Void getMethod3 () { … }
Public Void getMethod4 () { … }
Public Void mainFeatureEnvy () {
getMethod1();
getMethod2();
getMethod3();
getMethod4();
}
OtherClass
Could we use
Extract method ?
Yes ! If only a part
of the method
suffers from envy
50
51. Feature Envy: Example (2)
Public Void mainFeatureEnvy () {
Class1.getMethod1();
Class1.getMethod2();
Class2.getMethod3();
Class2.getMethod4();
}
Public Void getMethod1 () { … }
Public Void getMethod2 () { … }
Class1
Public Void getMethod3 () { … }
Public Void getMethod4 () { … }
Class2
?
51
52. Feature Envy: Refactoring Patterns (2)
Use the same method as the first example :
Extract Method or Move Method
To choose the good class we use the
following heuristic :
determine which class has most of the data and
put the method with that data
52
53. Shotgun Surgery
When making one kind of change requires many
small changes to a lot of different classes
53* Cartoon borrowed from https://sourcemaking.com/refactoring for didactic purposes only.
*
54. Shotgun Surgery
Hard to find all changes needed; easy to miss an
important change
Use Move Method and Move Field to put all
change sites into one class
Put things together that change together !
If a good place to put them does not exist, create
one.
54
55. Parallel Inheritance Hierarchies
Special case of Shotgun Surgery
Each time I add a subclass to one hierarchy, I need
to do it for all related hierarchies
Use Move Method
and Move Field
55* Cartoon borrowed from https://sourcemaking.com/refactoring for didactic purposes only.
*
56. Bad Smells : Classification
The top crime
Class / method organisation
Large class, Long Method, Long Parameter List, Lazy Class, Data Class, …
Lack of loose coupling or cohesion
Inappropriate Intimacy, Feature Envy, Data Clumps, …
Too much or too little delegation
Message Chains, Middle Man, …
Non Object-Oriented control or data structures
Switch Statements, Primitive Obsession, …
Other : Comments
56
57. Message Chains
A client asks an object for another object who then asks
that object for another object, etc.
Bad because client depends on the structure of the
navigation
Use Extract Method and Move Method to break
up or shorten such chains
57* Cartoon borrowed from https://sourcemaking.com/refactoring for didactic purposes only.
*
58. Middle Man
Objects hide internal details (encapsulation)
Encapsulation leads to delegation
It is a good concept but...
Sometimes it goes to far…
58
59. Middle Man
Real-life example:
You ask a director whether she is free for a
meeting
She delegates the message to her secretary that
delegates it to the diary.
Everything is good… but, if the secretary has
nothing else to do, it is better to remove her !
59
60. Middle Man
If a class performs only one
action, delegating work to
other classes, why does it
exist at all?
Sometimes most methods
of class just delegate to
another class
60* Cartoon borrowed from https://sourcemaking.com/refactoring for didactic purposes only.
*
61. Middle Man: Example
61
class Person
Department _department;
public Person getManager() {
return _department.getManager();
}
class Department
private Person _manager;
public Department (Person manager) {
_manager = manager; }
public Person getManager() {
return _manager(); }
}
The class Person is hiding the Department class.
To find a person’s manager, clients ask :
Manager = john.getManager();
and the person then needs to ask :
_department.getManager();
client class
Person
getManager()
Department
getManager()
62. 62
Middle Man: Refactoring
Remove Middle
Man
client class
Person
getDepartment()
Department
getManager()
client class
Person
getManager()
Department
getManager()
63. 63
Middle Man: Refactoring
Remove Middle Man…
First step : Create an accessor for the delegate.
class Person {
Department _department;
public Person getManager() {
return _department.getManager(); }
public Department getDepartment() {
return _department; }
}
client class
Person
getManager()
getDepartment()
Department
getManager()
64. 64
Middle Man: Refactoring
Second step : For each client use of a delegated method,
remove the method from the middle man and replace the
call in the client to call a method directly on the delegate
Last step : Compile and test.
client class
Person
getManager()
getDepartment()
Department
getManager()
client class
Person
getManager()
getDepartment()
Department
getManager()
Manager = john.getDepartment().getManager();
65. Bad Smells : Classification
The top crime
Class / method organisation
Large class, Long Method, Long Parameter List, Lazy Class, Data Class, …
Lack of loose coupling or cohesion
Inappropriate Intimacy, Feature Envy, Data Clumps, …
Too much or too little delegation
Message Chains, Middle Man, …
Non Object-Oriented control or data structures
Switch Statements, Primitive Obsession, …
Other : Comments
65
66. Switch Statements
Switch statements (“cases”)
often cause duplication
adding a new clause to the switch requires finding
all such switch statements throughout your code
OO has a better ways to deal with actions depending on types:
polymorphism !
Use Extract Method to extract the switch statement and then Move
Method to get it into the class where polymorphism is needed.
Then use Replace Conditional with Polymorphism after you
setup the inheritance structure.
66* Cartoon borrowed from https://sourcemaking.com/refactoring for didactic purposes only.
*
67. Primitive Obsession
Characterised by a reluctance
to use classes instead of
primitive data types
The difference between classes and primitive types is
hard to define in OO
Use Replace Data Value with Object on individual
data value.
Use Extract Class to put together a group of fields
67* Cartoon borrowed from https://sourcemaking.com/refactoring for didactic purposes only.
*
68. Bad Smells : Classification
The top crime
Class / method organisation
Large class, Long Method, Long Parameter List, Lazy Class, Data Class, …
Lack of loose coupling or cohesion
Inappropriate Intimacy, Feature Envy, Data Clumps, …
Too much or too little delegation
Message Chains, Middle Man, …
Non Object-Oriented control or data structures
Switch Statements, Primitive Obsession, …
Other : Comments, …
68
69. Some more bad smells
Temporary Field
Divergent Change
Speculative Generality
Alternative Classes with Different Interfaces
Incomplete Library
Refused Bequest
Comments
69
70. Temporary Field
Instance variables that are only set sometimes are
hard to understand; you expect an object to need
all its variables.
Use Extract Class to put the orphan variable
and all the code that concerns it in one place.
Use Introduce Null Object when the variable is
just around to deal with the null special case.
70
71. Divergent Change
When one class is commonly changed
in different ways for different reasons.
When we make a change we want to be able to jump
to a single clear point in the system and make the
change. If you can’t do this you’ve got a bad smell.
To clean this up you identify everything that changes
for a particular cause and use Extract Class to put
them all together.
71* Cartoon borrowed from https://sourcemaking.com/refactoring for didactic purposes only.
*
72. Speculative Generality
When someone says “I think
we may need the ability to do
this someday ”
At this time you need all sorts of hooks and special
cases to handle things that are not required
Use Collapse Hierarchy – Inline Class –
Remove Parameter – Rename Method
72* Cartoon borrowed from https://sourcemaking.com/refactoring for didactic purposes only.
*
73. Alternative Classes with Different Interfaces
Methods in different classes
that do the same thing but
have different signatures.
Use Rename Method
Keep using Move Method to move behaviour
until protocols are the same
73* Cartoon borrowed from https://sourcemaking.com/refactoring for didactic purposes only.
*
74. Incomplete Library Class
When a library or framework class doesn't provide all the
functionality you need
But the solution to the problem, changing the library, is
impossible since it is read-only.
Use Introduce Foreign Method and Introduce Local
Extension
See details of these refactorings for more information on how they
solve the problem
74
75. Refused Bequest
When a subclass ignores
and doesn’t need most of
the functionality provided
by its superclass
Can give confusion and problems
You need to create a new sibling class and use Push
Down Method and Push Down Field to push all
the unused methods to the sibling.
75* Cartoon borrowed from https://sourcemaking.com/refactoring for didactic purposes only.
*
76. Comments
Are comments bad?
Of course not! In general comments are a good thing to have.
But… sometimes comments are just an excuse for bad
code
It stinks when you have a big comment which tries to explain
bad code
such comments are used as a deodorant to hide the rotten
code underneath
76* Cartoon borrowed from https://sourcemaking.com/refactoring for didactic purposes only.
*
77. Comments: Example
while (i<NRULES) {
while (j<COL-1 && !(grammar[i][j+1].equals("N"))) {
init(first);
if (matrix[k][l] != 'R') {
if (cs.indexOf(q)!=-1) {
init(second);
for (int p=0;p < stIndex.size();indexHeadGram++){
…
« Look which rule to choose, and after we know which
rule to take we initialize the array matrix with the correct
value (depending on the rule). We do that until we have
tested all rules and after that we … blablabla »
77
78. Comments: Refactoring Patterns
Using refactorings, our first action is to remove the bad
smells in the commented code
After having done this, we often find that the comments
have become superfluous
To avoid bad smells we can often use Extract Method
Usually the name of the new method is enough then to
explain what the code does
78
80. Comments: Refactoring Patterns
Sometimes the method is already extracted but
still needs a comment to explain what it does
One solution could be : Rename Method
80
82. Comments: Refactoring Patterns
A section of code assumes something about the
state of the program.
A comment is required to state the rule.
To avoid it, we can use Introduce Assertion
82
83. Comments: Example
Public double getExpenseLimit() {
// should have either expense limit or a primary project
return (_expenseLimit != NULL_EXPENSE) ?
_expenseLimit:
_primaryProject.getMemberExpenseLimit(); }
Public double getExpenseLimit() {
assert.isTrue (_expenseLimit != NULL_EXPENSE || _primaryProject != null);
return (_expenseLimit != NULL_EXPENSE) ?
_expenseLimit:
_primaryProject.getMemberExpenseLimit(); }
Introduce Assertion
83
85. Comments: some last remarks…
When is a comment needed / useful ?
Tip : Whenever you feel the need to write a comment, first try to
refactor the code so that any comment becomes superfluous
A good time to use a comment is when you don’t know exactly what to do
A comment is a good place to say why you did something.
This kind of information helps future modifiers, especially forgetful
ones, including yourself
A last case is to use comments when something has not been done during
development
85
87. Problems with bad smells
Only a good recipe book and nothing more
It isn't always easy or even useful to use
Sometimes depends on context
and personal style / taste
Most of them are specific to OO
87
88. Conclusion
To have a good habitable code:
How? Refactorings
When? Bad Smells
Bad smells are only a recipe book to help us find
the right refactoring patterns to apply
88
89.
90. BAD CODE SMELLS
POSSIBLE QUESTIONS (1)
▸ Which bad smell could be corrected by applying the “Introduce Parameter Object”
refactoring?
▸ Which refactorings would you probably apply to address the “Large Class” bad smell?
▸ Explain and illustrate one of the following bad smells: Long Method, Feature Envy or Middle
Man.
▸ Explain the Long Parameter List bad smell in detail. Why is it a bad smell? How could it be
solved with a refactoring?
▸ What’s the relation between the Long Parameter List bad smell and the Data Clumps bad
smell?
91. BAD CODE SMELLS
POSSIBLE QUESTIONS (2)
▸ Explain and illustrate what the notion of “coupling” is. Should we strive for loose coupling or
tight coupling? What bad smell describes a situation that violates this principle? Name and
explain at least one.
▸ Explain and illustrate what the notion of “cohesion” is. Should we strive for low cohesion or high
cohesion? What bad smell describes a situation that violates this principle? Name and explain at
least one.
▸ Some bad smells are based on the principle that “things that change together should go
together”. Explain one of these bad smells, and the principle on which they are based, in detail.
▸ Name and explain at least one bad smell that explains a problem related to bad use of
inheritance.
▸ When talking about “Comments” in the bad smells theory session, it was stated that comments
are sometimes just there because the code is bad. Can you give an example of this and how
such comments could become superfluous simply by refactoring the code?