166 lekti

Refactoring 029 - Ki jan yo ranplase NULL ak Koleksyon

pa Maximiliano Contieri6m2025/06/02
Read on Terminal Reader

Twò lontan; Pou li

Remplace nullable atribit opsyonèl ak koleksyon vid yo elimine null tcheke ak pèmèt polymorphism.
featured image - Refactoring 029 - Ki jan yo ranplase NULL ak Koleksyon
Maximiliano Contieri HackerNoon profile picture

Konvèti atribit opsyonèl nan koleksyon vye granmoun pou koòd ki pi limyè, pi an sekirite ak polymorfik, elimine erè milya dola

TL;DR: ranplase nullable atribit opsyonèl ak koleksyon blan yo elimine null tcheke ak levage polymorphism.

TL;DR: ranplase nullable atribit opsyonèl ak koleksyon blan yo elimine null tcheke ak levage polymorphism.

Problèm rezoud

  • Nul referans Eksepsyon
  • Eksepsyonèl Kondisyonèl Logik ak IFs
  • Kòmanse erè fragile
  • Atribisyon opsyonèl
  • Kòd validasyon konplèks
  • Polymorphism kontwole

Etap

  1. Identifye nullable atribit opsyonèl ki ta ka koleksyon
  2. Remplaze objè nullable sèl ak koleksyon vid
  3. Retire tout tcheke null ki gen rapò ak atribit opsyonèl sa yo
  4. Metòd mete ajou pou travay ak koleksyon olye pou objè inik

Kòd echantiyon

Premye

public class ShoppingCart {
    private List<Item> items = new ArrayList<>();
    private Coupon coupon = null;
    
    public void addItem(Item item) {
        this.items.add(item);
    }
    
    public void redeemCoupon(Coupon coupon) {
        this.coupon = coupon;
    }
    
    public double total() {
        double total = 0;
        
        for (Item item : this.items) {
            total += item.getPrice();
        }
        
        // This a polluted IF and null check
        if (this.coupon != null) {
            total -= this.coupon.getDiscount();
        }
        
        return total;
    }
    
    public boolean hasUnsavedChanges() {
        // Explicit null check
        return !this.items.isEmpty() || this.coupon != null;
    }
    
    public boolean hasCoupon() {        
        return this.coupon != null;
    }
}
public class ShoppingCart {
    private final List<Item> items = new ArrayList<>();
  
    // This version uses Optionals
    // Not all programming languages support this feature
    private Optional<Coupon> coupon = Optional.empty();

    public void addItem(Item item) {
        items.add(item);
    }

    public void redeemCoupon(Coupon coupon) {
        // You need to understand how optionals work
        this.coupon = Optional.ofNullable(coupon);
    }
    
    public boolean hasUnsavedChanges() {
        return !items.isEmpty() || !coupon.isPresent();
    }

    public boolean hasCoupon() {
        return coupon.isPresent();
    }
}

Apre

public class ShoppingCart {
  private List<Item> items = new ArrayList<>();
    
  // 1. Identify nullable optional attributes
  // that could be collections
  // 2. Replace single nullable objects with empty collections
  private List<Coupon> coupons = new ArrayList<>();
    
  public void addItem(Item item) {
      this.items.add(item);
  }
    
  // Step 4: Work with collection
  // instead of single nullable object
  public void redeemCoupon(Coupon coupon) {
      this.coupons.add(coupon);
  }
    
  // Step 4: Simplified logic without null checks
  public double total() {
    double total = 0;
      
    for (Item item : this.items) {
        total += item.getPrice();
    }
      
    // 3. Remove all null checks 
    // related to these optional attributes        
    for (Coupon coupon : this.coupons) {
        total -= coupon.getDiscount();
    }
      
    return total;
  }
    
  // Consistent behavior with empty collections
  public boolean hasUnsavedChanges() {
    // 4. Update methods to work with collections
    // instead of single objects 
    return !this.items.isEmpty() || !this.coupons.isEmpty();
  }
    
  // 3. Remove all null checks 
  // related to these optional attributes
  // Collection-based check instead of null check
  public boolean hasCoupon() {
    return !this.coupons.isEmpty();
  }
}

Ki jan

  • [x] Semi otomatik

sekirite ️

Refactoring sa a se anjeneral san danje lè ou kontwole tout pwen aksè nan atribit yo koleksyon an.


Ou bezwen asire w ke pa gen okenn kòd ekstèn espere valè null ak fè fas ak API yo nan la.


refactoring kenbe menm konpòtman ekstèn pandan y ap senplisye logik enteryè.


Èske ou ta dwe tcheke ke tout konstriktè yo ak metòd faktori initialize koleksyon byen.

Poukisa Kòd la se pi bon?

Kòd refactored elimineNul pousantaj Eksepsyonak diminye konpòtman konpòtman konplèksite.


Koleksyon vakyòm ak koleksyon ki pa vakyòm pote polymorfik, ki pèmèt ou trete yo uniformman.


Kòd la vin pi prediktif paske koleksyon toujou egziste (pa gen okenn bwat) ak reponn a menm operasyon yo.


Implemantasyon metòd vin pi kout ak plis konsantre sou logik biznis anvan manipilasyon null.


Pwopozisyon an se align ak prensip la nan fè estats ilegal ki pa reprezante nan modèl domèn ou a, ki mennen nan yon kòd plis robust ak manyen.


Koleksyon vakyòm ak koleksyon ki pa vakyòm sepolymorphic.

Ki jan yo amelyore bijection? ️

Nan mond lan reyèl, konteinè egziste menm lè yo se san danje.


Si ou reprezante koleksyon opsyonèl kòm koleksyon vye granmoun anvan null, ou kreye yon modèl ki pi egzak nan reyalite.


Null pa egziste nan mond lan reyèl, epi li toujou rompeBijection.


Li kenbe yon korespondans yon sèl-a-yon-yon ant konsèp reyèl ak modèl kominikasyon ou, kreye yon bonMap la.


Lè ou retire yon koleksyon olye pou nulls, ou tou diminyeKòmanse.

Limite nan ️

Yon refactoring sa a ka pa apwopriye lè null gen yon vle di semantik diferan de "pòch". Gen kèk APIs legacy ka espere valè null, ki mande pou layers adaptasyon.


Èske ou bezwen asire ke tout chemen kòd inisyalize koleksyon konsistentman pou evite konbine null ak estasyon blan.

Refactor ak AI

Suggested Prompt: 1. Identifye nullable atribit opsyonèl ki ta ka koleksyon 2. Remplaze objè nullable sèl ak koleksyon blan 3. Retire tout null tcheke ki gen rapò ak atribit opsyonèl sa yo 4. Ajou metòd yo travay ak koleksyon olye pou objè inik 5. Teste ke koleksyon blan ak non-kòz ap travay konsistentman

Suggested Prompt: 1. Identifye nullable atribit opsyonèl ki ta ka koleksyon 2. Remplaze objè nullable sèl ak koleksyon blan 3. Retire tout null tcheke ki gen rapò ak atribit opsyonèl sa yo 4. Ajou metòd yo travay ak koleksyon olye pou objè inik 5. Teste ke koleksyon blan ak non-kòz ap travay konsistentman

Without Proper Instructions

With Specific Instructions

ChatGPT

ChatGPT

Claude

Claude

Perplexity

Perplexity

Copilot

Copilot

Gemini

Gemini

DeepSeek

DeepSeek

Meta AI

Meta AI

Grok

Grok

Qwen

Qwen

Chato

Chato

Claude nan

Claude nan

Perpleksite

Perpleksite

Pilòt

Pilòt

Twin nan

Twin nan

DeepSeek

DeepSeek

Objektif nan

Objektif nan

Pwodwi

Pwodwi

Pwen

Pwen

Dapre ️

  • Null nan

Nivèl

  • [x] Mwayen

Li se

Kredi

imaj nannan K.nanPixabay nan


Paj sa a se yon pati nan seri a Refactoring.


Trending Topics

blockchaincryptocurrencyhackernoon-top-storyprogrammingsoftware-developmenttechnologystartuphackernoon-booksBitcoinbooks