🍪 Privacy & Transparency

We and our partners use cookies to Store and/or access information on a device. We and our partners use data for Personalised ads and content, ad and content measurement, audience insights and product development. An example of data being processed may be a unique identifier stored in a cookie. Some of our partners may process your data as a part of their legitimate business interest without asking for consent. To view the purposes they believe they have legitimate interest for, or to object to this data processing use the vendor list link below. The consent submitted will only be used for data processing originating from this website. If you would like to change your settings or withdraw consent at any time, the link to do so is in our privacy policy accessible from our home page..

Vendor List | Privacy Policy
Skip to content

Technik Blog

Programmieren | Arduino | ESP32 | MicroPython | Python | Raspberry PI

Menu
  • Projekte
    • LED’s
    • Servo & Schrittmotoren
    • Sound
    • LCD’s
    • Kommunikation
    • Sicherheit
    • Weekend Project
  • Arduino
    • Tutorials
    • ProMini
      • Anschließen & Programmieren
    • Nano
      • Arduino Nano – Übersicht
    • UNO
      • Übersicht
    • MEGA 2560
      • Übersicht
    • Leonardo
      • Übersicht
    • NodeMCU
      • NodeMCU – “Einer für (fast) Alles!”
    • Lilypad
      • Arduino: Lilypad “Jetzt Geht’s Rund!”
    • WEMOS
      • WEMOS D1 – Arduino UNO kompatibles Board mit ESP8266 Chip
      • WEMOS D1 Mini – Übersicht
      • Wemos D1 mini Shields
    • STM32x
      • STM32F103C8T6 – Übersicht
    • Maker UNO
      • Maker UNO – Überblick und Test
    • ATTiny85
      • Mini Arduino mit ATTiny85 Chip
      • ATtiny85 mit dem Arduino UNO beschreiben
  • Android
  • Über mich
  • DeutschDeutsch
  • EnglishEnglish
Menu

ChatGPT – Refactoring von Quellcode

Veröffentlicht am 12. Mai 202327. April 2023 von Stefan Draeger

In diesem Beitrag möchte ich dir zeigen, wie du deinen Quellcode mithilfe von ChatGPT fast automatisch umstrukturieren (engl. Refactoring) lassen kannst.

Die künstliche Intelligenz ChatGPT kann dich bei der Entwicklung von Software sehr gut unterstützen und bietet dir die Möglichkeit zu bestehendem Code Inline Kommentare, neue Features oder auch wie ich dir nachfolgend zeigen möchte ein Refactoring deines Quellcodes an.

Was ist Refactoring von Code?

Beim Refactoring oder zu Deutsch dem Umstrukturieren von Quellcode organisiert man den Code neu, ohne dass dieser an Funktionalität verliert.

Ziel des Refactoring ist es, dass die Lesbarkeit, Wartbarkeit und die Erweiterbarkeit verbessert wird.

Wenn du mehr über das Refactoring von Quellcode lesen möchtest, dann empfehle ich dir den Wikipedia Artikel:

Seite „Refactoring“. In: Wikipedia – Die freie Enzyklopädie. Bearbeitungsstand: 27. Mai 2022, 08:02 UTC. URL: https://de.wikipedia.org/w/index.php?title=Refactoring&oldid=223200456 (Abgerufen: 27. April 2023, 10:48 UTC)

Refactoring anhand eines Beispiels

Starten wir mit einem kleinen Programm, welches wir von ChatGPT umstrukturieren lassen möchten.

Das kleine Pythonskript soll ein Passwort auf Komplexität prüfen. Der Benutzer gibt auf der Konsole ein Passwort ein und dieses wird dann auf die Vorkommnisse von Zahlen, Groß-/Kleinbuchstaben sowie Symbolen geprüft. Zum Schluss erfolgt eine Auswertung, ob dieses Komplex genug ist.

passwort = input('Gebe dein Passwort ein: ')

result = {
    'Zahlen': False,
    'Großbuchstabe': False,
    'Kleinbuchstabe': False,
    'Symbol': False
}

for c in passwort:
    if c.isdigit():
        result['Zahlen'] = True
    if c.isupper():
        result['Großbuchstabe'] = True
    if c.islower():
        result['Kleinbuchstabe'] = True
    if not c.isalnum():
        result['Symbol'] = True

conditions = 0

for key in result:
    if result[key]:
        conditions = conditions + 1

pwLength = len(passwort)

if pwLength <= 25 and conditions <= 2:
    print('Das Passwort ist weniger komplex!')
elif pwLength > 12 and conditions > 2:
    print('Das Passwort ist kurz aber komplex!')

print(result)

Der Code ist so wie er steht lauffähig, aber kann noch verbessert werden. Dieses wollen wir uns von ChatGPT umsetzen lassen.

Normalerweise würde man vor dem Refactoring noch Unittests erstellen, um sicherzustellen, dass der Code wie gewünscht funktioniert.

Wie du Unittest mit ChatGPT erstellen kannst, zeige ich dir noch in einem weiteren Beitrag.

Refactoring von ChatGPT

Ich starte nachfolgende Anfrage und gebe zusätzlich noch den Hinweis, dass die CleanCode Regeln beachtet werden sollen. Bei ChatGPT gilt, je genauer man die Anfrage stellt, umso besser wird das Ergebnis.

Mache nachfolgenden Code eleganter und beachte dabei die CleanCode Regeln:
passwort = input('Gebe dein Passwort ein: ')

...

Als Ausgabe erhalte ich ein Pythonscript, welches um 5 Zeilen länger ist, aber deutlich aufgeräumter und lesbarer daherkommt.

Vergleich - original & umstrukturierter Code
Vergleich – original & umstrukturierter Code

Was aber noch fehlt, sind die Inline Kommentare. Diese können wir uns auch generieren lassen, indem wir die passende Anfrage stellen.

Erzeuge mir noch zusätzlich die Inline kommentare.
Quellcode mit Inline Kommentaren nach dem Refactoring
Quellcode mit Inline Kommentaren nach dem Refactoring

Ergebnis von ChatGPT

Nachfolgend findest du jetzt den neuen Code, welcher durch ChatGPT optimiert wurde. Zusätzlich wurden noch Inline Kommentare hinzugefügt.

def check_password_complexity(password):
    """
    Checks the complexity of a password and returns a dictionary with the following keys:
    - 'has_numbers': True if password contains at least one digit, False otherwise.
    - 'has_uppercase': True if password contains at least one uppercase letter, False otherwise.
    - 'has_lowercase': True if password contains at least one lowercase letter, False otherwise.
    - 'has_symbols': True if password contains at least one non-alphanumeric character, False otherwise.
    """
    complexity = {
        'has_numbers': False,
        'has_uppercase': False,
        'has_lowercase': False,
        'has_symbols': False
    }

    # Check each character in the password and update the complexity dictionary accordingly
    for c in password:
        if c.isdigit():
            complexity['has_numbers'] = True
        elif c.isupper():
            complexity['has_uppercase'] = True
        elif c.islower():
            complexity['has_lowercase'] = True
        elif not c.isalnum():
            complexity['has_symbols'] = True

    return complexity


# Prompt user for password input and check its complexity
password = input('Gebe dein Passwort ein: ')
password_complexity = check_password_complexity(password)
conditions_met = sum(password_complexity.values())

# Check if password meets complexity requirements and print appropriate message
if len(password) <= 25 and conditions_met <= 2:
    print('Das Passwort ist weniger komplex!')  # Password is not complex enough
elif len(password) > 12 and conditions_met > 2:
    print('Das Passwort ist kurz aber komplex!')  # Password is short but complex

# Print the complexity dictionary for debugging purposes
print(password_complexity)

Der komplette Chatverlauf mit ChatGPT

Nachfolgend findest du den kompletten Chatverlauf mit ChatGPT.

ChatGPT_refactor_PasswordcheckerHerunterladen

Schreibe einen Kommentar Antworten abbrechen

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Kategorien

Tools

  • 8×8 LED Matrix Tool
  • 8×16 LED Matrix Modul von Keyestudio
  • 16×16 LED Matrix – Generator
  • Widerstandsrechner
  • Rechner für Strom & Widerstände
  • ASCII Tabelle

Meta

  • Videothek
  • Impressum
  • Datenschutzerklärung
  • Disclaimer
  • Kontakt
  • Cookie-Richtlinie (EU)

Links

Blogverzeichnis Bloggerei.de Blogverzeichnis TopBlogs.de das Original - Blogverzeichnis | Blog Top Liste Blogverzeichnis trusted-blogs.com
©2023 Technik Blog | Built using WordPress and Responsive Blogily theme by Superb
x
x