Improve encapsulation: Add shallowClone() method to vidMap

Added a shallowClone() method to vidMap to improve encapsulation and prevent
MasterClient from directly accessing vidMap's internal fields.

Changes:
1. Added vidMap.shallowClone() in vid_map.go
   - Encapsulates the shallow copy logic within vidMap
   - Makes vidMap responsible for its own state representation
   - Documented that caller is responsible for thread safety

2. Simplified resetVidMap() in masterclient.go
   - Uses tail := mc.vidMap.shallowClone() instead of manual field access
   - Cleaner, more maintainable code
   - Better adherence to encapsulation principles

Benefits:
- Improved code organization and maintainability
- vidMap internals are now properly encapsulated
- Easier to modify vidMap structure in the future
- More self-documenting code

Verified with: go test -race ./weed/wdclient/... (passes)
This commit is contained in:
chrislu
2025-10-30 20:56:13 -07:00
parent c238153a3b
commit bba8931d64
2 changed files with 14 additions and 7 deletions
+3 -7
View File
@@ -592,14 +592,10 @@ func (mc *MasterClient) resetVidMap() {
mc.vidMapLock.Lock()
defer mc.vidMapLock.Unlock()
tail := &vidMap{
vid2Locations: mc.vidMap.vid2Locations,
ecVid2Locations: mc.vidMap.ecVid2Locations,
DataCenter: mc.vidMap.DataCenter,
cache: mc.vidMap.cache,
}
// Create a shallow clone to preserve in the cache chain
tail := mc.vidMap.shallowClone()
nvm := newVidMap(mc.vidMap.DataCenter)
nvm := newVidMap(tail.DataCenter)
nvm.cache = tail
mc.vidMap = nvm
+11
View File
@@ -53,6 +53,17 @@ func newVidMap(dataCenter string) *vidMap {
}
}
// shallowClone creates a shallow copy of the vidMap for use in cache chaining.
// The caller is responsible for ensuring thread safety.
func (vc *vidMap) shallowClone() *vidMap {
return &vidMap{
vid2Locations: vc.vid2Locations,
ecVid2Locations: vc.ecVid2Locations,
DataCenter: vc.DataCenter,
cache: vc.cache,
}
}
func (vc *vidMap) getLocationIndex(length int) (int, error) {
if length <= 0 {
return 0, fmt.Errorf("invalid length: %d", length)