### Python: Required Setup or Teardown Code Example Source: https://luzkan.github.io/smells/required-setup-or-teardown-code Demonstrates the 'Required Setup or Teardown Code' smell in Python, where manual socket shutdown and closing are needed after using a Radio object. The solution refactors the class to include a graceful shutdown within the destructor. ```python class Radio: def __init__(self, ip, port): socket = socket.connection(f"{ip}:{port}") ... radio: Radio = Radio(ip, port) ... # Doing something with the object ... # Finalizing its use radio.socket.shutdown(socket.shut_RDWR) radio.socket.close() ... ``` ```python class Radio: def __init__(self, ip, port): socket = socket.connection(f"{ip}:{port}") def __del__(self): def graceful_shutdown(): self.socket.shutdown(socket.shut_RDWR) self.socket.close() graceful_shutdown() super().__del__() ... radio: Radio = Radio(ip, port) ... # Doing something with the object ... # Finalizing its use no longer requires manual socket closing ... ``` -------------------------------- ### Python: Useful Comment Example (Docstring) Source: https://luzkan.github.io/smells/what-comment Provides an example of a more useful docstring that clearly explains the function's purpose and potential side effects. The function removes a character from the game world. Input is an integer character ID. ```python def destroy_character(character_id: int): """ Removes the character from the main game world scene if it's present, otherwise throws a warning (character could be removed due to some other trigger event). """ ``` -------------------------------- ### Flag Argument Example - Python Source: https://luzkan.github.io/smells/flag-argument Demonstrates the 'Flag Argument' code smell in Python, where a boolean parameter dictates different behaviors. The example contrasts a smelly implementation with a refactored version that uses separate methods for clarity and maintainability. Dependencies include a 'Customer' class (assumed). ```python class Concert: def book(self, customer: Customer, is_premium: bool): if is_premium: print("Booking premium seat...") else: print("Booking regular seat...") # Smelly usage marcel = "Marcel" concert = Concert() concert.book(marcel, False) # Ambiguous class ConcertRefactored: def book_premium(self, customer: Customer): print("Booking premium seat...") def book_regular(self, customer: Customer): print("Booking regular seat...") # Refactored usage concert_refactored = ConcertRefactored() concert_refactored.book_regular(marcel) ``` -------------------------------- ### Smelly Parallel Inheritance Hierarchies Example (Python) Source: https://luzkan.github.io/smells/parallel-inheritance-hierarchies Illustrates the 'Parallel Inheritance Hierarchies' code smell in Python. This example shows how creating new subclasses for one hierarchy necessitates creating corresponding subclasses for another, leading to redundancy. The issue arises when new user types are added, requiring new function subclasses with similar naming conventions. ```python class User(ABC): ... functions: Functions class Functions(ABC): ... class BasicUser(User): ... class BasicFunctions(Functions): ... class PremiumUser(User): ... class PremiumFunctions(Functions): ... # each time a new user is added, so is a new function subclass with the same prefix ``` -------------------------------- ### Python: Useless Comment Example (Docstring) Source: https://luzkan.github.io/smells/what-comment Illustrates a code smell where a docstring provides a useless comment instead of meaningful documentation. The function increases attack value. Input is an integer. ```python def increase_attack(self, value: int): """ Increases attack by the given value. params: - value: integer """ self.attack += value ``` -------------------------------- ### Inappropriate Static - Python Example Source: https://luzkan.github.io/smells/inappropriate-static Demonstrates the 'Inappropriate Static' code smell in Python using static methods for tag wrapping. The solution refactors this into a non-static class that encapsulates the tag wrapping logic. ```python class FooUtils: @staticmethod def wrap_tag_premium(foo: Foo): return f"[TAG]: {foo.action()}" @staticmethod def wrap_tag_special(foo: Foo): return f"[TAG]: {foo.action()}" ``` ```python @dataclass class FooTagWrapper: foo: Foo def wrap_tag_premium(self): return f"[PREMIUM]: {self.foo}" def wrap_tag_special(self): return f"[SPECIAL]: {self.foo}" ``` -------------------------------- ### Python "What" Comment Example - Grouping Label Source: https://luzkan.github.io/smells/what-comment Demonstrates a 'what' comment used as a grouping label in Python. The smelly version uses comments to explain sections of code, while the solution refactors these into separate methods for better readability and maintainability. ```python class Foo: def run(...): ... # Creating Report vanilla_report = get_vanilla_report(...) tweaked_report = tweaking_report(vanilla_report) final_report = format_report(tweaked_report) # Sending Report send_report_to_headquarters_via_email(final_report) send_report_to_developers_via_chat(final_report) ... ``` ```python class Foo: def run(...): ... report = self.create_report(...) self.send_report(report) def create_report(self, ...): vanilla_report = get_vanilla_report(...) tweaked_report = tweaking_report(vanilla_report) return format_report(tweaked_report) def send_report(self, report): send_report_to_headquarters_via_email(final_report) send_report_to_developers_via_chat(final_report) ... ``` -------------------------------- ### Insider Trading Code Smell Example in Python Source: https://luzkan.github.io/smells/insider-trading Illustrates the 'Insider Trading' code smell where classes excessively know about each other's internal details. This leads to high coupling, reduced reusability, and difficulty in testing. The example shows two intertwined classes, Commit and Repo, and suggests refactoring techniques. ```python from dataclasses import dataclass class Repo: def __init__(self, url: str): self.url = url def push(self, name: str): pass def commit(self, commit_obj: 'Commit'): commit_obj.commit(self.url) @dataclass class Commit: name: str def push(self, repo: Repo): repo.push(self.name) def commit(self, url: str): pass ``` -------------------------------- ### Inconsistent Style Example (Python) Source: https://luzkan.github.io/smells/inconsistent-style Demonstrates inconsistent function call formatting, including variations in indentation and argument placement, which disrupts readability and expected code structure. ```python my_first_function( arg1=1, arg2=2, arg3=3 ) my_second_function(arg1=1, arg2=2, arg3=3) my_third_function( arg1=1, arg2=2, arg3=3 ) ``` -------------------------------- ### Sequence Inconsistency Example (Python) Source: https://luzkan.github.io/smells/inconsistent-style Illustrates 'Sequence Inconsistency' where the order of parameters in method calls differs between `rangeAttack` and `meleeAttack`, potentially leading to overlooked errors due to similar parameter types. ```python class Character: DAMAGE_BONUS: float def rangeAttack(self, enemy: Character, damage: int, extra_damage: int): total_damage = damage + extra_damage*self.DAMAGE_BONUS ... def meleeAttack(self, enemy: Character, extra_damage: int, damage: int): total_damage = damage + extra_damage*self.DAMAGE_BONUS ... witcher.rangeAttack(skeleton, 300, 200) witcher.meleeAttack(skeleton, 300, 200) # potentially overlooked error ``` -------------------------------- ### Python: Uncommunicative Name Example and Solution Source: https://luzkan.github.io/smells/uncommunicative-name Demonstrates a 'smelly' Python code snippet with uncommunicative names and provides a refactored 'solution' with descriptive names and a helper function. This highlights how clear naming improves readability and maintainability. ```python data = m1.get_f() data_2 = m2.get_f() value = data_2['dmg'] * data['def'] val = math.rand(value-3, value+3) ``` ```python def wobble_the_value(value: int, wobble_by: int): """ Adds tiny bit of randomness to the output """ return math.rand(value-wobble_by, value+wobble_by) attack_information: FightingInformation = attacking_minion.get_fighting_information() defense_information: FightingInformation = defending_minion.get_fighting_information() calculated_damage: int = attack_information.damage * defense_information.defense final_damage_dealt: int = wobble_the_value(calculated_damage, wobble_by=3) ``` -------------------------------- ### Alternative Classes with Different Interfaces - Python Example Source: https://luzkan.github.io/smells/alternative-classes-with-different-interfaces Demonstrates the 'Alternative Classes with Different Interfaces' code smell in Python. This occurs when two classes have similar functionality but different method names for that functionality. The example shows a 'smelly' version with distinct `hug_snowman()` and `hug_zombie()` methods, and a 'solution' version using a common `hug()` method to adhere to the DRY principle. ```python class Snowman(Humanoid): def hug_snowman(): ... class Zombie(Humanoid): def hug_zombie(): ... ``` ```python class Snowman(Humanoid): def hug(): ... class Zombie(Humanoid): def hug(): ... ``` -------------------------------- ### JavaScript Callback Hell Example Source: https://luzkan.github.io/smells/callback-hell Illustrates the 'smelly' version of Callback Hell in JavaScript, characterized by deeply nested callbacks that hinder readability and maintainability. This pattern is often referred to as 'Pyramid of Doom'. ```javascript const makeSandwich = () => { ... getBread(function(bread) { ... sliceBread(bread, function(slicedBread) { ... getJam(function(jam) { ... brushBread(slicedBread, jam, function(smearedBread) { ... }); }); }); }); }; ``` -------------------------------- ### Python Middle Man Code Smell Example Source: https://luzkan.github.io/smells/middle-man Demonstrates the 'Middle Man' code smell in Python, where a 'Minion' class delegates the 'is_frontline' check to a 'Location' class, which in turn delegates to a 'Field' class. This creates an unnecessary chain of delegation. ```python class Minion: _location: Location def action(self): ... if self.is_frontline(): ... def is_frontline(self) return self._location.is_frontline() class Location: _field: Field def is_frontline(self) return self._field.is_frontline() class Field: def is_frontline(self) ... ``` ```python class Minion: _location: Location def action(self): ... if self._location.field.is_frontline(): ... class Location: field: Field class Field: def is_frontline(self) ... ``` -------------------------------- ### Python: Get Gross Value Calculation Source: https://luzkan.github.io/smells/what-comment Calculates the gross value by considering price and tax. This snippet demonstrates a basic function signature. Dependencies include standard Python float and type hinting. ```python def get_gross_value(price: float, tax: float): ... ``` -------------------------------- ### Hidden Dependencies - Python Example Source: https://luzkan.github.io/smells/hidden-dependencies Illustrates the 'Hidden Dependencies' code smell in Python. The 'smelly' version accesses a global variable, while the 'solution' version explicitly passes the dependency via the constructor, improving testability and clarity. ```python class Customer: pass customer = Customer() class Cart: def __init__(self): self.customer = customer # gets customer from global scope cart = Cart() ``` ```python class Customer: pass customer = Customer() class Cart: def __init__(self, customer): self.customer = customer # gets customer explicitly cart = Cart(customer) ``` -------------------------------- ### Python Mutable Data Example - Smelly Code Source: https://luzkan.github.io/smells/mutable-data This Python code snippet demonstrates the 'smelly' version of Mutable Data using a dataclass. The instance of this class can be passed around and modified, leading to potential issues. ```python @dataclass class Foo: name: str value: float premium: bool # foo object instance will be passed around and modified ``` -------------------------------- ### Primitive Obsession Example in Python Source: https://luzkan.github.io/smells/primitive-obsession Demonstrates the Primitive Obsession code smell where a string is used to represent a date. The 'Smelly' version uses a plain string, while the 'Solution' version introduces a 'Date' dataclass for better abstraction and encapsulation. ```python birthday_date: str = "1998-03-04" name_day_date: str = "2021-03-20" ``` ```python @dataclass(frozen=True) class Date: year: int month: int day: int def __str__(self): return f"{self.year}-{self.month}-{self.day}" birthday: Date = Date(1998, 03, 04) name_day: Date = Date(2021, 03, 20) ``` -------------------------------- ### Python Null Check Solution Example Source: https://luzkan.github.io/smells/null-check This Python code presents a solution to the 'Null Check' code smell by introducing a Null Object pattern. A 'NullBonusDamage' class handles the null case, eliminating the need for explicit checks. ```python class BonusDamage(ABC): @abstractmethod def increase_damage(self, damage: float) -> float: """ Increases the output damage """ class Critical(BonusDamage): multiplier: float def increase_damage(self, damage: float): def additional_damage() -> float: return damage * self.multiplier * math.random(0, 2) return damage + additional_damage() class Magical(BonusDamage): multiplier: float def increase_damage(self, damage: float): return damage * multiplier class NullBonusDamage(BonusDamage): def increase_damage(self, damage: float): return damage bonus_damage: BonusDamage = perk.get_bonus_damage() def example_of_doing_something_with_bonus_damage(bonus_damage: BonusDamage) -> ...: ... ``` -------------------------------- ### Python Null Check Smelly Example Source: https://luzkan.github.io/smells/null-check This Python code demonstrates the 'Null Check' code smell where a variable can be None, leading to explicit null checks in the surrounding logic. It uses abstract base classes and type hints. ```python class BonusDamage(ABC): @abstractmethod def increase_damage(self, damage: float) -> float: """ Increases the output damage """ class Critical(BonusDamage): multiplier: float def increase_damage(self, damage: float): def additional_damage() -> float: return damage * self.multiplier * math.random(0, 2) return damage + additional_damage() class Magical(BonusDamage): multiplier: float def increase_damage(self, damage: float): return damage * multiplier bonus_damage: BonusDamage | None = perk.get_bonus_damage() def example_of_doing_something_with_bonus_damage(bonus_damage: BonusDamage | None) -> ... | None: if not bonus_damage: return ... ``` -------------------------------- ### Long Parameter List Example - Python Source: https://luzkan.github.io/smells/long-parameter-list Demonstrates the 'Long Parameter List' code smell in Python, where a function has an excessive number of parameters. It also shows a refactored solution using a data class to group related parameters. ```python def foo(author: str, commit_id: str, files: List[str], sha_id: str, time: str): ... author, commit_id, files, sha_id, time = get_last_commit() foo(author, commit_id, files, sha_id, time) ``` ```python @dataclass(frozen=True) class Commit: author: str commit_id: str files: List[str] sha_id: str time: str def foo(self): ... commit = Commit(**get_last_commit()) commit.foo() ``` -------------------------------- ### Feature Envy Code Smell Example (Python) Source: https://luzkan.github.io/smells/feature-envy Demonstrates the 'Feature Envy' code smell in Python, where a method in one class manipulates data from another class excessively. It shows a 'smelly' version and a 'solution' version after refactoring by moving behavior closer to the data. ```python @dataclass(frozen=True) class ShoppingItem: name: str price: float tax: float class Order: ... # Assume other methods and initializations here def get_bill_total(self, items: list[ShoppingItem]) -> float: return sum([item.price * item.tax for item in items]) def get_receipt_string(self, items: list[ShoppingItem]) -> list[str]: return [f"{item.name}: {item.price * item.tax}$\" for item in items] def create_receipt(self, items: list[ShoppingItem]) -> float: bill = self.get_bill_total(items) receipt = self.get_receipt_string(items).join('\n') return f"{receipt}\nBill {bill}" ``` ```python @dataclass(frozen=True) class ShoppingItem: name: str price: float tax: float @property def taxed_price(self) -> float: return self.price * self.tax def get_receipt_string(self) -> str: return f"{self.name}: {self.price * self.tax}$\" class Order: ... # Assume other methods and initializations here def get_bill_total(items: list[ShoppingItem]) -> float: return sum([item.taxed_price for item in items]) def get_receipt_string(items: list[ShoppingItem]) -> list[str]: return [item.get_receipt_string() for item in items] def create_receipt(items: list[ShoppingItem]) -> float: bill = self.get_bill_total(items) receipt = self.get_receipt_string(items).join('\n') return f"{receipt}\nBill: {bill}$\" ``` -------------------------------- ### Oddball Solution Example - Python Source: https://luzkan.github.io/smells/oddball-solution Illustrates the 'Oddball Solution' code smell in Python, where similar 'Instrument' classes (USB2 and USB3) have different initialization and method names despite serving a similar purpose. The refactored solution demonstrates unifying the interface using a 'SocketAdapter'. ```python class Instrument: ... class USB2(Instrument): def __init__(self, ip, port): connection = socket.new_connection(f"{ip}:{port}") ... def ask(self, command): ... self.connection.query(command) class USB3(Instrument): def __init__(self, address): connection = socket.new_connection(address) ... def read(self, command): ... self.connection.query(command) ``` ```python class SocketAdapter: def __init__(self, ip, port): connection = socket.new_connection(f"{ip}:{port}") ... def query(self, command): ... class Instrument: connection: SocketAdapter ... class USB2(Instrument): def __init__(self, ip, port): self.connection = SocketAdapter(ip, port) ... class USB3(Instrument): def __init__(self, ip, port): self.connection = SocketAdapter(ip, port) ... ``` -------------------------------- ### Complicated Boolean Expression Refactoring Examples (Python) Source: https://luzkan.github.io/smells/complicated-boolean-expression Demonstrates refactoring complex boolean expressions into more readable methods. The first example shows encapsulating a conditional into a named function. The second example extracts nested conditions and helper functions to improve clarity. ```python if (timer.has_expired() and not timer.is_recurrent()): ... # Refactored: if (should_be_deleted(timer)): ... ``` ```python def cook(ready: bool, bag: list): if (ready): if (['raspberry', 'apple', 'tomato'] in bag and ['carrot', 'spinach', 'garlic'] not in bag): ... # Refactored: def cook(bag: list): def hasFruit(container: list) -> bool: return ['raspberry', 'apple', 'tomato'] in container def hasVeggie(container: list) -> bool: return ['carrot', 'spinach', 'garlic'] in container if not hasFruit(bag): return if hasVeggie(bag): return ... ``` -------------------------------- ### Vertical Separation in Python - Solution Example Source: https://luzkan.github.io/smells/vertical-separation The refactored version of the Python 'Vertical Separation' example, bringing the 'repeat' variable declaration closer to its usage in the loop. ```python ... doing_something() doing_something_else() ... repeat = 5 for index in range(0, repeat): ... ``` -------------------------------- ### Clever Code: Custom Default Dictionary Implementation Source: https://luzkan.github.io/smells/clever-code This example illustrates the Clever Code smell by providing a custom implementation of a dictionary with a default value, rather than using Python's built-in `collections.defaultdict`. This approach can lead to performance issues and requires others to understand a non-standard implementation. ```python class MyDefaultDict: def __init__(self, default_value): self._data = {} self.default_value = default_value def __getitem__(self, key): if key not in self._data: self._data[key] = self.default_value return self._data[key] def __setitem__(self, key, value): self._data[key] = value def __str__(self): return str(self._data) d = MyDefaultDict(0) d['a'] += 1 print(d) ``` -------------------------------- ### Vertical Separation in Python - Smelly Example Source: https://luzkan.github.io/smells/vertical-separation A Python code example showcasing the 'Vertical Separation' smell where a variable 'repeat' is declared far from its usage in a loop. ```python repeat = 5 ... doing_something() doing_something_else() ... for index in range(0, repeat): ... ``` -------------------------------- ### Exporting with Complex Conditionals (Python) Source: https://luzkan.github.io/smells/conditional-complexity This Python code demonstrates the 'Increased Test Complexity' smell using a long if-elif chain to handle different export formats. It requires manual testing for each format and becomes cumbersome as more formats are added. The refactored version uses a factory pattern to delegate format-specific logic. ```python class Exporter: def export(self, export_format: str): if export_format == 'wav': self.exportInWav() elif export_format == 'flac': self.exportInFlac() elif export_format == 'mp3': self.exportInMp3() elif export_format == 'ogg': self.exportInOgg() ``` ```python class Exporter: def export(self, export_format: str): exporter = self.get_format_factory(export_format) exporter.export() def get_format_factory(self, export_format: str): if export_format in self.export_format_factories: return render_factory[export_format] raise MissingFormatException ... ``` -------------------------------- ### Obscured Intent Example - C (Quake 3 Fast Inverse Square Root) Source: https://luzkan.github.io/smells/obscured-intent This C code snippet is a famous example of Obscured Intent from Quake 3 Arena. It uses bitwise operations and magic numbers for a fast inverse square root calculation, making it extremely difficult to understand without prior knowledge of the technique. ```c float Q_rsqrt( float number ) { long i; float x2, y; const float threehalfs = 1.5F; x2 = number * 0.5F; y = number; i = * ( long * ) &y; // evil floating point bit level hacking i = 0x5f3759df - ( i >> 1 ); // what the f*ck? y = * ( float * ) &i; y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration // y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed return y; } ``` -------------------------------- ### Speculative Generality Example - Solution Hierarchy Source: https://luzkan.github.io/smells/speculative-generality This Python code snippet presents the 'Solution' to the Speculative Generality code smell. It refactors the 'Smelly' example by simplifying the class hierarchy. Instead of an intermediate 'Human' class, the specific roles (Swordsman, Archer, Pikeman) directly inherit from a more generalized 'Animal' class or are structured more appropriately. This approach reduces unnecessary abstraction and complexity, adhering to the 'You Ain't Gonna Need It' principle by only including what is currently needed, thus making the code cleaner and easier to maintain. ```python class Human: name: str health: int attack: int defense: int class Swordsman(Human): ... class Archer(Human): ... class Pikeman(Human): ... ``` -------------------------------- ### Combinatorial Explosion Code Smell Example (Python) Source: https://luzkan.github.io/smells/combinatorial-explosion Demonstrates the 'Combinatorial Explosion' code smell where multiple similar methods exist due to varying data or conditions. The 'Smelly' version uses conditional logic, while the 'Solution' version refactors to a state pattern for better extensibility and adherence to DRY and Open-Closed principles. ```python class Minion: name: str state: 'ready' def action(self): if self.state == 'ready': self.animate('standing') elif self.state == 'fighting': self.animate('fighting') elif self.state == 'resting': self.animate('resting') def next_state(self): if self.state == 'ready': return 'fighting' elif self.state == 'fighting': return 'resting' elif self.state == 'resting': return 'ready' def animate(self, animation: str): print(f"{self.name} is {animation}!") ``` ```python from abc import ABC, abstractmethod from enum import Enum class State(ABC): @abstractmethod def next() -> 'State': """ Return next State """ @abstractmethod def animate() -> str: """ Returns a text-based animation """ class Ready(State): def next(): return States.FIGHT def animate(): return 'standing' class Fight(State): def next(): return States.REST def animate(): return 'fighting' class Rest(State): def next(): return States.READY def animate(): return 'resting' class States(Enum): READY: State = Ready FIGHT: State = Fight REST: State = Rest class Minion: name: str state: State = States.Ready def action(self): self.state.animate() def next_state(self): self.state = self.state.next() def animate(self, animation: str): print(f"{self.name} is {self.state.animate()}!") ``` -------------------------------- ### JavaScript Callback Hell Solution with Promises Source: https://luzkan.github.io/smells/callback-hell Demonstrates a refactored approach to Callback Hell in JavaScript using Promises. This solution improves code readability and maintainability by chaining asynchronous operations in a more linear fashion. ```javascript const getBread = doNext => { ... doNext(bread); }; const sliceBread = doNext => { ... doNext(breadSlice); }; ... const makeSandwich = () => { return getBread() .then(bread => sliceBread(bread)) .then(jam => getJam(beef)) .then(slicedBread, jam => brushBread(slicedBread, jam)); }; ``` -------------------------------- ### Magic Number - Refactored Code Example Source: https://luzkan.github.io/smells/magic-number This Python snippet shows the refactoring of a 'Magic Number' by replacing the literal with a named constant (MAX_DAMAGE_CAP), significantly improving code readability and intent. ```python import math def calculateDamage(...) -> int: total_damage = ... MAX_DAMAGE_CAP: int = 100 return math.max(MAX_DAMAGE_CAP, total_damage) ``` -------------------------------- ### Magic Number - Smelly Code Example Source: https://luzkan.github.io/smells/magic-number This Python snippet demonstrates the 'Magic Number' code smell where an unexplained integer literal (100) is used directly in a function, reducing readability and maintainability. ```python import math def calculateDamage(...) -> int: total_damage = ... return math.max(100, damage) ``` -------------------------------- ### Python "What" Comment Example - Uncommunicative Name Cover Source: https://luzkan.github.io/smells/what-comment Illustrates a 'what' comment in Python that attempts to explain a function with uncommunicative parameter names. The smelly version includes a docstring that merely restates parameter types, indicating the underlying issue of poor naming. ```python def get_gross_value(p, t): """ params - price: float - tax: float """ ... ``` -------------------------------- ### Python: Inconsistent vs. Consistent Method Naming Source: https://luzkan.github.io/smells/inconsistent-names Demonstrates the 'Inconsistent Names' code smell in Python, where similar functionalities are represented by different method names across classes. The solution shows how to refactor to use consistent naming by introducing an abstract base class and overriding methods. ```python class Human: def talk(): ... class Elf: def chat(): ... ``` ```python from abc import ABC, abstractmethod class Character(ABC): @abstractmethod def talk(): """ Converse """ class Human(Character): def talk(): ... class Elf(Character): def talk(): ... ```