Is duplicated code more tolerable in unit tests?

Readability is more important for tests. If a test fails, you want the problem to be obvious. The developer shouldn’t have to wade through a lot of heavily factored test code to determine exactly what failed. You don’t want your test code to become so complex that you need to write unit-test-tests. However, eliminating duplication … Read more

DRY Ruby Initialization with Hash Argument

You don’t need the constant, but I don’t think you can eliminate symbol-to-string: class Example attr_reader :name, :age def initialize args args.each do |k,v| instance_variable_set(“@#{k}”, v) unless v.nil? end end end #=> nil e1 = Example.new :name => ‘foo’, :age => 33 #=> #<Example:0x3f9a1c @name=”foo”, @age=33> e2 = Example.new :name => ‘bar’ #=> #<Example:0x3eb15c @name=”bar”> … Read more

How to avoid code duplication implementing const and non-const iterators?

[The best answer was, unfortunately, deleted by a moderator because it was a link-only answer. I understand why link-only answers are discouraged; deleting it, however, has robbed future seekers of very useful information. The link has remained stable for more than seven years and continues to work at the time of this writing.] I strongly … Read more

How to use mixins properly in Javascript

A mixin is just a different conceptual idea, of how to organize code and inheritance. You can of course combine it with using classical or prototypal inheritance, but it also works stand-alone, so to speak. For instance, instead of creating “delegated” object properties/lookups (like prototypal inheritance), we would truly “form” new stand-alone objects, from multiple … Read more

What’s the recommended way to extend AngularJS controllers?

Perhaps you don’t extend a controller but it is possible to extend a controller or make a single controller a mixin of multiple controllers. module.controller(‘CtrlImplAdvanced’, [‘$scope’, ‘$controller’, function ($scope, $controller) { // Initialize the super class and extend it. angular.extend(this, $controller(‘CtrlImpl’, {$scope: $scope})); … Additional extensions to create a mixin. }]); When the parent controller … Read more