Table of Contents
Code Smell 09 - Dead Code
Maxi Contieri ・ Oct 24 '22
Code Smell 54 - Anchor Boats
Maxi Contieri ・ Jan 2 '22
Code Smell 148 - ToDos
Maxi Contieri ・ Jul 13 '22
Refactoring 003 - Extract Constant
How to Improve your Code With easy Refactorings
Home Backend Development Python Tutorial Refactoring - Remove Dead Code

Refactoring - Remove Dead Code

Dec 29, 2024 pm 05:34 PM

Clean up the trash

TL;DR: Eliminate unused functions, constants, and "just-in-case" code.

Problems Addressed

  • Dead Code

  • Just-in-case code

  • Reduced maintainability

  • Anchor Boats

  • Cognitive Load

Related Code Smells

Refactoring  - Remove Dead Code

Code Smell 09 - Dead Code

Maxi Contieri ・ Oct 28 '20

#codenewbie #tutorial
Refactoring  - Remove Dead Code

Code Smell 54 - Anchor Boats

Maxi Contieri ・ Jan 6 '21

#codenewbie #webdev #tutorial #cleancode
Refactoring  - Remove Dead Code

Code Smell 148 - ToDos

Maxi Contieri ・ Jul 13 '22

#javascript #webdev #beginners #programming

Steps

  1. Ensure your code has good functional coverage.

  2. Identify unused functions and constants by reviewing your code or using static analysis tools.

  3. Analyze the added speculative code, just in case.

  4. Remove anything unnecessary or unused.

  5. Perform comprehensive regression testing on your code.

Sample Code

Before

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

from flask import Flask, jsonify, make_response

 

app = Flask(__name__)

 

HTTP_100_CONTINUE = 100

HTTP_202_ACCEPTED = 202  # Not used

HTTP_204_NO_CONTENT = 204 # Not Used

HTTP_302_FOUND = 302 # Not Used

HTTP_400_BAD_REQUEST = 400  # Not Used

HTTP_401_UNAUTHORIZED = 401 # Not Used

HTTP_403_FORBIDDEN = 403

HTTP_404_NOT_FOUND = 404

HTTP_410_GONE = 410

HTTP_500_INTERNAL_SERVER_ERROR = 500

HTTP_501_NOT_IMPLEMENTED = 501

 

probe_telemetry = {

    "temperature": {"solar_panels": 150, "instrument_1": 50},

    "position": {"x": 1000000, "y": 2000000, "z": 3000000,

    "velocity": {"vx": 100, "vy": 200, "vz": 300}},

    "status": {"power_level": 95, "communication_status": "OK"}

}

 

@app.route('/api/v1/probe/telemetry', methods=['GET'])

def get_telemetry():

    return jsonify(probe_telemetry), HTTP_200_OK

 

# The following function is not invoked

# and not implemented

# It is a dead placeholder

@app.route('/api/v1/probe/send_command', methods=['POST'])

def send_command():

    return jsonify({"message": "Command endpoint not implemented yet."}),

       HTTP_501_NOT_IMPLEMENTED

 

@app.route('/api/v1/probe/data', methods=['GET'])

def get_data():

    return jsonify({"message": "Data not found"}),

       HTTP_404_NOT_FOUND

 

@app.route('/api/v1/probe/redirect', methods=['GET'])

def redirect_endpoint():

    response = make_response(jsonify({"message": "Redirecting..."}),

       HTTP_301_MOVED_PERMANENTLY)

    response.headers['Location'] = '/api/v1/probe/telemetry'

    return response

 

@app.route('/api/v1/probe/not_modified', methods=['GET'])

def not_modified_endpoint():

    response = make_response(jsonify({"message": "Not Modified"}),

       HTTP_304_NOT_MODIFIED)

    response.headers['ETag'] = 'some_etag'

    return response

 

@app.route('/api/v1/probe/gone', methods=['GET'])

def gone_endpoint():

    return jsonify({"message": "Resource permanently gone"}),

       HTTP_410_GONE

Copy after login

After

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

# 1. Ensure your code has good functional coverage.

 

from flask import Flask, jsonify, make_response

from http import HTTPStatus

 

app = Flask(__name__)

 

# 2. Identify unused functions and constants

# by reviewing your code or using static analysis tools.

HTTP_200_OK = HTTPStatus.OK

HTTP_301_MOVED_PERMANENTLY = HTTPStatus.MOVED_PERMANENTLY

HTTP_304_NOT_MODIFIED = HTTPStatus.NOT_MODIFIED

HTTP_404_NOT_FOUND = HTTPStatus.NOT_FOUND

HTTP_410_GONE = HTTPStatus.GONE

HTTP_501_NOT_IMPLEMENTED = HTTPStatus.NOT_IMPLEMENTED

 

probe_telemetry = {

    "temperature": {"solar_panels": 150, "instrument_1": 50},

    "position": {"x": 1000000, "y": 2000000, "z": 3000000,

    "velocity": {"vx": 100, "vy": 200, "vz": 300}},

    "status": {"power_level": 95, "communication_status": "OK"}

}

 

@app.route('/api/v1/probe/telemetry', methods=['GET'])

def get_telemetry():

    return jsonify(probe_telemetry), HTTP_200_OK

 

# 3. Analyze the added speculative code, just in case.

 

@app.route('/api/v1/probe/send_command', methods=['POST'])

def send_command():

    return jsonify({"message": "Command endpoint not implemented yet."}),

       HTTP_501_NOT_IMPLEMENTED

 

@app.route('/api/v1/probe/data', methods=['GET'])

def get_data():

    return jsonify({"message": "Data not found"}),

      HTTP_404_NOT_FOUND

 

# 4. Remove anything unnecessary or unused.

 

# 5. Perform comprehensive regression testing on your code.

Copy after login

Type

[X] Semi-Automatic

Safety

This refactoring is safe if you thoroughly test your application after the changes. Static analysis tools can help ensure you don't remove anything still in use.

Why is the Code Better?

You improve clarity and reduce complexity by removing unused elements.

Your code becomes easier to understand and maintain.

Reducing speculative code also keeps your focus on current, actual requirements.

How Does it Improve the Bijection?

Dead code and speculative elements break Bijection between your software and the real-world model.

Removing these elements ensures your code accurately represents your
MAPPER, making it cleaner and closer to reality.

Limitations

Removing dead code requires confidence that it's truly unused.

This process relies on static analysis or thorough codebase knowledge, which can be error-prone without robust tools.

Refactor with AI

Without Proper Instructions With Specific Instructions
ChatGPT ChatGPT
Claude Claude
Perplexity Perplexity
Copilot Copilot
Gemini Gemini

Tags

  • Bloaters

Related Refactorings

Refactoring  - Remove Dead Code

Refactoring 003 - Extract Constant

Maxi Contieri ・ Jan 2 '22

#oop #programming #refactoring #cleancode

Credits

Image by Peter H from Pixabay


This article is part of the Refactoring Series.

Refactoring  - Remove Dead Code

How to Improve your Code With easy Refactorings

Maxi Contieri ・ Oct 24 '22

#webdev #beginners #programming #tutorial

The above is the detailed content of Refactoring - Remove Dead Code. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

See all articles