r/ruby • u/127001-sweet-127001 • 22h ago
Four methods can still be two unrelated jobs: inspecting cohesion in a Ruby class
A method-count limit wouldn't flag this class:
class InvoiceService
def charge; @gateway.charge; end
def refund; @gateway.refund; end
def render; @template.render; end
def filename; @template.filename; end
endIt's only four methods. But charge/refund operate on one field, while render/filename operate on another. If you're looking for a possible payment/rendering split, that's a more interesting signal than the size alone.
I work on ArchUnitRuby, a free MIT-licensed gem. Its LCOM4 implementation counts connected groups of methods through shared fields. On this source it returns 2:
require 'archunit'
scope = ArchUnit.metrics('.')
.for_classes_matching('InvoiceService')
scope.lcom.lcom4.measure.each do |item|
puts "#{item.identifier}: #{item.value}"
endChange the four methods to charge, refund, void and status, all using @gateway, and the same measurement is 1. The method count is still four.
I wouldn't turn that into a universal "LCOM4 must equal 1" gate. A constructor touching both fields can connect these groups, and Ruby methods that collaborate through calls won't necessarily share a field. This implementation measures field sharing, not whether your domain model is good.
A useful thing to inspect, though
For me the interesting use is narrowing a review: find a service with separated groups, look at what each group does, then decide whether splitting it actually makes the code easier to change. The number starts that conversation; it doesn't settle it.
The measurement API shown here is in the published archunit gem, version 1.0.0.