sanger/sequencescape

View on GitHub
app/sample_manifest_excel/sample_manifest_excel/upload/processor/base.rb

Summary

Maintainability
B
5 hrs
Test Coverage
A
100%

Class Base has 22 methods (exceeds 20 allowed). Consider refactoring.
Open

      class Base
        MANDATORY_FIELDS = %w[country_of_origin date_of_sample_collection].freeze

        include ActiveModel::Model
        include SequencescapeExcel::SubclassChecker

    Method _check_mandatory_field has a Cognitive Complexity of 13 (exceeds 5 allowed). Consider refactoring.
    Open

            def _check_mandatory_field(mandatory_field) # rubocop:todo Metrics/CyclomaticComplexity, Metrics/AbcSize
              return unless upload.respond_to?(:rows)
              upload.rows.each do |row|
                next if row.columns.blank? || row.data.blank?
                col_num = row.columns.find_column_or_null(:name, mandatory_field).number

    Cognitive Complexity

    Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.

    A method's cognitive complexity is based on a few simple rules:

    • Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
    • Code is considered more complex for each "break in the linear flow of the code"
    • Code is considered more complex when "flow breaking structures are nested"

    Further reading

    Method duplicate_barcodes has a Cognitive Complexity of 13 (exceeds 5 allowed). Consider refactoring.
    Open

            def duplicate_barcodes # rubocop:todo Metrics/CyclomaticComplexity
              return unless upload.respond_to?(:rows)
    
              unique_bcs = []
              upload.rows.each do |row|

    Cognitive Complexity

    Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.

    A method's cognitive complexity is based on a few simple rules:

    • Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
    • Code is considered more complex for each "break in the linear flow of the code"
    • Code is considered more complex when "flow breaking structures are nested"

    Further reading

    Complex method SampleManifestExcel::Upload::Processor::Base#_check_mandatory_field (26.3)
    Open

            def _check_mandatory_field(mandatory_field) # rubocop:todo Metrics/CyclomaticComplexity, Metrics/AbcSize
              return unless upload.respond_to?(:rows)
              upload.rows.each do |row|
                next if row.columns.blank? || row.data.blank?
                col_num = row.columns.find_column_or_null(:name, mandatory_field).number

    Flog calculates the ABC score for methods. The ABC score is based on assignments, branches (method calls), and conditions.

    You can read more about ABC metrics or the flog tool

    SampleManifestExcel::Upload::Processor::Base#_check_mandatory_field refers to 'row' more than self (maybe move it to another class?)
    Open

                next if row.columns.blank? || row.data.blank?
                col_num = row.columns.find_column_or_null(:name, mandatory_field).number
                next unless col_num.present? && col_num.positive?
    
                value = row.at(col_num)

    Feature Envy occurs when a code fragment references another object more often than it references itself, or when several clients do the same series of manipulations on a particular type of object.

    Feature Envy reduces the code's ability to communicate intent: code that "belongs" on one class but which is located in another can be hard to find, and may upset the "System of Names" in the host class.

    Feature Envy also affects the design's flexibility: A code fragment that is in the wrong class creates couplings that may not be natural within the application's domain, and creates a loss of cohesion in the unwilling host class.

    Feature Envy often arises because it must manipulate other objects (usually its arguments) to get them into a useful form, and one force preventing them (the arguments) doing this themselves is that the common knowledge lives outside the arguments, or the arguments are of too basic a type to justify extending that type. Therefore there must be something which 'knows' about the contents or purposes of the arguments. That thing would have to be more than just a basic type, because the basic types are either containers which don't know about their contents, or they are single objects which can't capture their relationship with their fellows of the same type. So, this thing with the extra knowledge should be reified into a class, and the utility method will most likely belong there.

    Example

    Running Reek on:

    class Warehouse
      def sale_price(item)
        (item.price - item.rebate) * @vat
      end
    end

    would report:

    Warehouse#total_price refers to item more than self (FeatureEnvy)

    since this:

    (item.price - item.rebate)

    belongs to the Item class, not the Warehouse.

    SampleManifestExcel::Upload::Processor::Base#duplicate_barcodes has approx 10 statements
    Open

            def duplicate_barcodes # rubocop:todo Metrics/CyclomaticComplexity

    A method with Too Many Statements is any method that has a large number of lines.

    Too Many Statements warns about any method that has more than 5 statements. Reek's smell detector for Too Many Statements counts +1 for every simple statement in a method and +1 for every statement within a control structure (if, else, case, when, for, while, until, begin, rescue) but it doesn't count the control structure itself.

    So the following method would score +6 in Reek's statement-counting algorithm:

    def parse(arg, argv, &error)
      if !(val = arg) and (argv.empty? or /\A-/ =~ (val = argv[0]))
        return nil, block, nil                                         # +1
      end
      opt = (val = parse_arg(val, &error))[1]                          # +2
      val = conv_arg(*val)                                             # +3
      if opt and !arg
        argv.shift                                                     # +4
      else
        val[0] = nil                                                   # +5
      end
      val                                                              # +6
    end

    (You might argue that the two assigments within the first @if@ should count as statements, and that perhaps the nested assignment should count as +2.)

    SampleManifestExcel::Upload::Processor::Base#_check_mandatory_field has approx 7 statements
    Open

            def _check_mandatory_field(mandatory_field) # rubocop:todo Metrics/CyclomaticComplexity, Metrics/AbcSize

    A method with Too Many Statements is any method that has a large number of lines.

    Too Many Statements warns about any method that has more than 5 statements. Reek's smell detector for Too Many Statements counts +1 for every simple statement in a method and +1 for every statement within a control structure (if, else, case, when, for, while, until, begin, rescue) but it doesn't count the control structure itself.

    So the following method would score +6 in Reek's statement-counting algorithm:

    def parse(arg, argv, &error)
      if !(val = arg) and (argv.empty? or /\A-/ =~ (val = argv[0]))
        return nil, block, nil                                         # +1
      end
      opt = (val = parse_arg(val, &error))[1]                          # +2
      val = conv_arg(*val)                                             # +3
      if opt and !arg
        argv.shift                                                     # +4
      else
        val[0] = nil                                                   # +5
      end
      val                                                              # +6
    end

    (You might argue that the two assigments within the first @if@ should count as statements, and that perhaps the nested assignment should count as +2.)

    SampleManifestExcel::Upload::Processor::Base#duplicate_barcodes refers to 'row' more than self (maybe move it to another class?)
    Open

                next if row.columns.blank? || row.data.blank?
    
                col_num = row.columns.find_column_or_null(:name, 'sanger_tube_id').number
                next unless col_num.present? && col_num.positive?
    
    

    Feature Envy occurs when a code fragment references another object more often than it references itself, or when several clients do the same series of manipulations on a particular type of object.

    Feature Envy reduces the code's ability to communicate intent: code that "belongs" on one class but which is located in another can be hard to find, and may upset the "System of Names" in the host class.

    Feature Envy also affects the design's flexibility: A code fragment that is in the wrong class creates couplings that may not be natural within the application's domain, and creates a loss of cohesion in the unwilling host class.

    Feature Envy often arises because it must manipulate other objects (usually its arguments) to get them into a useful form, and one force preventing them (the arguments) doing this themselves is that the common knowledge lives outside the arguments, or the arguments are of too basic a type to justify extending that type. Therefore there must be something which 'knows' about the contents or purposes of the arguments. That thing would have to be more than just a basic type, because the basic types are either containers which don't know about their contents, or they are single objects which can't capture their relationship with their fellows of the same type. So, this thing with the extra knowledge should be reified into a class, and the utility method will most likely belong there.

    Example

    Running Reek on:

    class Warehouse
      def sale_price(item)
        (item.price - item.rebate) * @vat
      end
    end

    would report:

    Warehouse#total_price refers to item more than self (FeatureEnvy)

    since this:

    (item.price - item.rebate)

    belongs to the Item class, not the Warehouse.

    SampleManifestExcel::Upload::Processor::Base has at least 22 methods
    Open

          class Base

    Too Many Methods is a special case of LargeClass.

    Example

    Given this configuration

    TooManyMethods:
      max_methods: 3

    and this code:

    class TooManyMethods
      def one; end
      def two; end
      def three; end
      def four; end
    end

    Reek would emit the following warning:

    test.rb -- 1 warning:
      [1]:TooManyMethods has at least 4 methods (TooManyMethods)

    Complex method SampleManifestExcel::Upload::Processor::Base#duplicate_barcodes (23.5)
    Open

            def duplicate_barcodes # rubocop:todo Metrics/CyclomaticComplexity
              return unless upload.respond_to?(:rows)
    
              unique_bcs = []
              upload.rows.each do |row|

    Flog calculates the ABC score for methods. The ABC score is based on assignments, branches (method calls), and conditions.

    You can read more about ABC metrics or the flog tool

    SampleManifestExcel::Upload::Processor::Base assumes too much for instance variable '@sample_manifest_updated'
    Open

          class Base

    Classes should not assume that instance variables are set or present outside of the current class definition.

    Good:

    class Foo
      def initialize
        @bar = :foo
      end
    
      def foo?
        @bar == :foo
      end
    end

    Good as well:

    class Foo
      def foo?
        bar == :foo
      end
    
      def bar
        @bar ||= :foo
      end
    end

    Bad:

    class Foo
      def go_foo!
        @bar = :foo
      end
    
      def foo?
        @bar == :foo
      end
    end

    Example

    Running Reek on:

    class Dummy
      def test
        @ivar
      end
    end

    would report:

    [1]:InstanceVariableAssumption: Dummy assumes too much for instance variable @ivar

    Note that this example would trigger this smell warning as well:

    class Parent
      def initialize(omg)
        @omg = omg
      end
    end
    
    class Child < Parent
      def foo
        @omg
      end
    end

    The way to address the smell warning is that you should create an attr_reader to use @omg in the subclass and not access @omg directly like this:

    class Parent
      attr_reader :omg
    
      def initialize(omg)
        @omg = omg
      end
    end
    
    class Child < Parent
      def foo
        omg
      end
    end

    Directly accessing instance variables is considered a smell because it breaks encapsulation and makes it harder to reason about code.

    If you don't want to expose those methods as public API just make them private like this:

    class Parent
      def initialize(omg)
        @omg = omg
      end
    
      private
      attr_reader :omg
    end
    
    class Child < Parent
      def foo
        omg
      end
    end

    Current Support in Reek

    An instance variable must:

    • be set in the constructor
    • or be accessed through a method with lazy initialization / memoization.

    If not, Instance Variable Assumption will be reported.

    SampleManifestExcel::Upload::Processor::Base#duplicate_barcodes manually dispatches method call
    Open

              return unless upload.respond_to?(:rows)

    Reek reports a Manual Dispatch smell if it finds source code that manually checks whether an object responds to a method before that method is called. Manual dispatch is a type of Simulated Polymorphism which leads to code that is harder to reason about, debug, and refactor.

    Example

    class MyManualDispatcher
      attr_reader :foo
    
      def initialize(foo)
        @foo = foo
      end
    
      def call
        foo.bar if foo.respond_to?(:bar)
      end
    end

    Reek would emit the following warning:

    test.rb -- 1 warning:
      [9]: MyManualDispatcher manually dispatches method call (ManualDispatch)

    SampleManifestExcel::Upload::Processor::Base#duplicate_barcodes calls 'row.columns' 2 times
    Open

                next if row.columns.blank? || row.data.blank?
    
                col_num = row.columns.find_column_or_null(:name, 'sanger_tube_id').number

    Duplication occurs when two fragments of code look nearly identical, or when two fragments of code have nearly identical effects at some conceptual level.

    Reek implements a check for Duplicate Method Call.

    Example

    Here's a very much simplified and contrived example. The following method will report a warning:

    def double_thing()
      @other.thing + @other.thing
    end

    One quick approach to silence Reek would be to refactor the code thus:

    def double_thing()
      thing = @other.thing
      thing + thing
    end

    A slightly different approach would be to replace all calls of double_thing by calls to @other.double_thing:

    class Other
      def double_thing()
        thing + thing
      end
    end

    The approach you take will depend on balancing other factors in your code.

    SampleManifestExcel::Upload::Processor::Base#_check_mandatory_field calls 'row.columns' 2 times
    Open

                next if row.columns.blank? || row.data.blank?
                col_num = row.columns.find_column_or_null(:name, mandatory_field).number

    Duplication occurs when two fragments of code look nearly identical, or when two fragments of code have nearly identical effects at some conceptual level.

    Reek implements a check for Duplicate Method Call.

    Example

    Here's a very much simplified and contrived example. The following method will report a warning:

    def double_thing()
      @other.thing + @other.thing
    end

    One quick approach to silence Reek would be to refactor the code thus:

    def double_thing()
      thing = @other.thing
      thing + thing
    end

    A slightly different approach would be to replace all calls of double_thing by calls to @other.double_thing:

    class Other
      def double_thing()
        thing + thing
      end
    end

    The approach you take will depend on balancing other factors in your code.

    SampleManifestExcel::Upload::Processor::Base assumes too much for instance variable '@downstream_aliquots_updated'
    Open

          class Base

    Classes should not assume that instance variables are set or present outside of the current class definition.

    Good:

    class Foo
      def initialize
        @bar = :foo
      end
    
      def foo?
        @bar == :foo
      end
    end

    Good as well:

    class Foo
      def foo?
        bar == :foo
      end
    
      def bar
        @bar ||= :foo
      end
    end

    Bad:

    class Foo
      def go_foo!
        @bar = :foo
      end
    
      def foo?
        @bar == :foo
      end
    end

    Example

    Running Reek on:

    class Dummy
      def test
        @ivar
      end
    end

    would report:

    [1]:InstanceVariableAssumption: Dummy assumes too much for instance variable @ivar

    Note that this example would trigger this smell warning as well:

    class Parent
      def initialize(omg)
        @omg = omg
      end
    end
    
    class Child < Parent
      def foo
        @omg
      end
    end

    The way to address the smell warning is that you should create an attr_reader to use @omg in the subclass and not access @omg directly like this:

    class Parent
      attr_reader :omg
    
      def initialize(omg)
        @omg = omg
      end
    end
    
    class Child < Parent
      def foo
        omg
      end
    end

    Directly accessing instance variables is considered a smell because it breaks encapsulation and makes it harder to reason about code.

    If you don't want to expose those methods as public API just make them private like this:

    class Parent
      def initialize(omg)
        @omg = omg
      end
    
      private
      attr_reader :omg
    end
    
    class Child < Parent
      def foo
        omg
      end
    end

    Current Support in Reek

    An instance variable must:

    • be set in the constructor
    • or be accessed through a method with lazy initialization / memoization.

    If not, Instance Variable Assumption will be reported.

    SampleManifestExcel::Upload::Processor::Base#_check_mandatory_field manually dispatches method call
    Open

              return unless upload.respond_to?(:rows)

    Reek reports a Manual Dispatch smell if it finds source code that manually checks whether an object responds to a method before that method is called. Manual dispatch is a type of Simulated Polymorphism which leads to code that is harder to reason about, debug, and refactor.

    Example

    class MyManualDispatcher
      attr_reader :foo
    
      def initialize(foo)
        @foo = foo
      end
    
      def call
        foo.bar if foo.respond_to?(:bar)
      end
    end

    Reek would emit the following warning:

    test.rb -- 1 warning:
      [9]: MyManualDispatcher manually dispatches method call (ManualDispatch)

    SampleManifestExcel::Upload::Processor::Base#check_for_barcodes_unique performs a nil-check
    Open

              return if duplicated_barcode_row.nil?

    A NilCheck is a type check. Failures of NilCheck violate the "tell, don't ask" principle.

    Additionally, type checks often mask bigger problems in your source code like not using OOP and / or polymorphism when you should.

    Example

    Given

    class Klass
      def nil_checker(argument)
        if argument.nil?
          puts "argument isn't nil!"
        end
      end
    end

    Reek would emit the following warning:

    test.rb -- 1 warning:
      [3]:Klass#nil_checker performs a nil-check. (NilCheck)

    Complex method SampleManifestExcel::Upload::Processor::Base#update_samples_and_aliquots (20.7)
    Open

            def update_samples_and_aliquots(tag_group)
              upload.rows.each do |row|
                row.update_sample(tag_group, upload.override)
                substitutions.concat(row.aliquots.filter_map(&:substitution_hash)) if row.reuploaded?
              end

    Flog calculates the ABC score for methods. The ABC score is based on assignments, branches (method calls), and conditions.

    You can read more about ABC metrics or the flog tool

    There are no issues that match your filters.

    Category
    Status