<p>I'm researching and experimenting more with Groovy and I'm trying to wrap my mind around the pros and cons of implementing things in Groovy that I can't/don't do in Java.  Dynamic programming is still just a concept to me since I've been deeply steeped static and strongly typed languages.  </p>

<p>Groovy gives me the ability to <a href="http://en.wikipedia.org/wiki/Duck_typing" rel="noreferrer">duck-type</a>, but I can't really see the value.  How is duck-typing more productive than static typing?  What kind of things can I do in my code practice to help me grasp the benefits of it?</p>

<p>I ask this question with Groovy in mind but I understand it isn't necessarily a Groovy question so I welcome answers from every code camp.</p>

[{'answer_id': 47977, 'author': 'Chris Bunch', 'author_id': 422, 'author_profile': 'https://Stackoverflow.com/users/422', 'pm_score': 1, 'selected': False, 'text': "<p>It's not that duck typing is more productive than static typing as much as it is simply different. With static typing you always have to worry that your data is the correct type and in Java it shows up through casting to the right type. With duck typing the type doesn't matter as long as it has the right method, so it really just eliminates a lot of the hassle of casting and conversions between types.</p>\n"}, {'answer_id': 47982, 'author': 'Jason Baker', 'author_id': 2147, 'author_profile': 'https://Stackoverflow.com/users/2147', 'pm_score': 3, 'selected': False, 'text': "<p>It's a little bit difficult to see the value of duck typing until you've used it for a little while.  Once you get used to it, you'll realize how much of a load off your mind it is to not have to deal with interfaces or having to worry about exactly what type something is.</p>\n"}, {'answer_id': 48003, 'author': 'Nick Retallack', 'author_id': 2653, 'author_profile': 'https://Stackoverflow.com/users/2653', 'pm_score': 3, 'selected': False, 'text': '<p>There is nothing wrong with static typing if you are using Haskell, which has an incredible static type system.  However, if you are using languages like Java and C++ that have terribly crippling type systems, duck typing is definitely an improvement.</p>\n\n<p>Imagine trying to use something so simple as "<a href="http://en.wikipedia.org/wiki/Map_(higher-order_function)" rel="nofollow noreferrer">map</a>" in Java (and no, I don\'t mean <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/Map.html" rel="nofollow noreferrer">the data structure</a>).  Even generics are rather poorly supported.</p>\n'}, {'answer_id': 250119, 'author': 'Ken Gentle', 'author_id': 8709, 'author_profile': 'https://Stackoverflow.com/users/8709', 'pm_score': 4, 'selected': False, 'text': "<p>Duck typing cripples most modern IDE's static checking, which can point out errors as you type.  Some consider this an advantage.  I want the IDE/Compiler to tell me I've made a stupid programmer trick as soon as possible.</p>\n\n<p>My most recent favorite argument <strong>against</strong> duck typing comes from a Grails project DTO:</p>\n\n<pre><code>class SimpleResults {\n    def results\n    def total\n    def categories\n}\n</code></pre>\n\n<p>where <code>results</code> turns out to be something like <code>Map&lt;String, List&lt;ComplexType&gt;&gt;</code>, which can be discovered only by following a trail of method calls in different classes until you find where it was created.  For the terminally curious, <code>total</code> is the sum of the sizes of the <code>List&lt;ComplexType&gt;</code>s and <code>categories</code> is the size of the <code>Map</code></p>\n\n<p>It may have been clear to the original developer, but the poor maintenance guy (ME) lost a lot of hair tracking this one down.</p>\n"}, {'answer_id': 275962, 'author': 'Miguel Ping', 'author_id': 22992, 'author_profile': 'https://Stackoverflow.com/users/22992', 'pm_score': 3, 'selected': False, 'text': '<p>IMHO, the advantage of duck typing becomes magnified when you adhere to some conventions, such as naming you variables and methods in a consistent way. Taking the example from <strong>Ken G</strong>, I think it would read best:</p>\n\n<pre><code>class SimpleResults {\n    def mapOfListResults\n    def total\n    def categories\n}\n</code></pre>\n\n<p>Let\'s say you define a contract on some operation named \'calculateRating(A,B)\' where A and B adhere to another contract. In pseudocode, it would read:</p>\n\n<pre><code>Long calculateRating(A someObj, B, otherObj) {\n\n   //some fake algorithm here:\n   if(someObj.doStuff(\'foo\') &gt; otherObj.doStuff(\'bar\')) return someObj.calcRating());\n   else return otherObj.calcRating();\n\n}\n</code></pre>\n\n<p>If you want to implement this in Java, both A and B must implement some kind of interface that reads something like this:</p>\n\n<pre><code>public interface MyService {\n    public int doStuff(String input);\n}\n</code></pre>\n\n<p>Besides, if you want to generalize you contract for calculating ratings (let\'s say you have another algorithm for rating calculations), you also have to create an interface:</p>\n\n<pre><code>public long calculateRating(MyService A, MyServiceB);\n</code></pre>\n\n<p>With duck typing, you can ditch your <strong>interfaces</strong> and just rely that on runtime, both A and B will respond correctly to your <code>doStuff()</code> calls. There is no need for a specific contract definition. This can work for you but it can also work against you.</p>\n\n<p>The downside is that you have to be extra careful in order to guarantee that your code does not break when some other persons changes it (ie, the other person must be aware of the implicit contract on the method name and arguments).</p>\n\n<p>Note that this aggravates specially in Java, where the syntax is not as terse as it could be (compared to <a href="http://www.scala-lang.org" rel="noreferrer">Scala</a> for example). A counter-example of this is the <a href="http://liftweb.net/" rel="noreferrer">Lift framework</a>, where they say that the SLOC count of the framework is similar to <a href="http://www.rubyonrails.org/" rel="noreferrer">Rails</a>, but the test code has less lines because they don\'t need to implement type checks within the tests.</p>\n'}, {'answer_id': 275998, 'author': 'Charlie Martin', 'author_id': 35092, 'author_profile': 'https://Stackoverflow.com/users/35092', 'pm_score': 4, 'selected': True, 'text': '<p>Next, which is better: EMACS or vi?  This is one of the running religious wars.</p>\n\n<p>Think of it this way: any program that is <em>correct</em>, will be correct if the language is statically typed.   What static typing does is let the compiler have enough information to detect type mismatches at compile time instead of run time.  This can be an annoyance if your doing incremental sorts of programming, although (I maintain) if you\'re thinking clearly about your program it doesn\'t much matter; on the other hand, if you\'re building a really big program, like an operating system or a telephone switch, with dozens or hundreds or thousands of people working on it, or with really high reliability requirements, then having he compiler be able to detect a large class of problems for you without needing a test case to exercise just the right code path.</p>\n\n<p>It\'s not as if dynamic typing is a new and different thing: C, for example, is effectively dynamically typed, since I can always cast a <code>foo*</code> to a <code>bar*</code>.  It just means it\'s then my responsibility as a C programmer never to use code that is appropriate on a <code>bar*</code> when the address is really pointing to a <code>foo*</code>.  But as a result of the issues with large programs, C grew tools like lint(1), strengthened its type system with <code>typedef</code> and eventually developed a strongly typed variant in C++.  (And, of course, C++ in turn developed ways around the strong typing, with all the varieties of casts and generics/templates and with RTTI. </p>\n\n<p>One other thing, though --- don\'t confuse "agile programming" with "dynamic languages".  <a href="http://agilemanifesto.org/" rel="noreferrer">Agile programming</a> is about the way people work together in a project: can the project adapt to changing requirements to meet the customers\' needs while maintaining a humane environment for the programmers?  It can be done with dynamically typed languages, and often is, because they can be more productive (eg, Ruby, Smalltalk), but it can be done, has been done successfully, in C and even assembler.  In fact, <a href="http://www.rallydev.com/" rel="noreferrer">Rally Development</a> even uses agile methods (SCRUM in particular) to do marketing and documentation. </p>\n'}, {'answer_id': 2089894, 'author': 'Lypheus', 'author_id': 253587, 'author_profile': 'https://Stackoverflow.com/users/253587', 'pm_score': 5, 'selected': False, 'text': '<p>A lot of the comments for duck typing don\'t really substantiate the claims.  Not "having to worry" about a type is not sustainable for maintenance or making an application extendable.  I\'ve really had a good opportunity to see Grails in action over my last contract and its quite funny to watch really.  Everyone is happy about the gains in being able to "create-app" and get going - sadly it all catches up to you on the back end.</p>\n\n<p>Groovy seems the same way to me.  Sure you can write very succinct code and definitely there is some nice sugar in how we get to work with properties, collections, etc... But the cost of not knowing what the heck is being passed back and forth just gets worse and worse.  At some point your scratching your head wondering why the project has become 80% testing and 20% work.  The lesson here is that "smaller" does not make for "more readable" code.  Sorry folks, its simple logic - the more you have to know intuitively then the more complex the process of understanding that code becomes.  It\'s why GUI\'s have backed off becoming overly iconic over the years - sure looks pretty but WTH is going on is not always obvious.</p>\n\n<p>People on that project seemed to have troubles "nailing down" the lessons learned, but when you have methods returning either a single element of type T, an array of T, an ErrorResult or a null ... it becomes rather apparent.</p>\n\n<p>One thing working with Groovy has done for me however - awesome billable hours woot!</p>\n'}, {'answer_id': 2272415, 'author': 'slim', 'author_id': 7512, 'author_profile': 'https://Stackoverflow.com/users/7512', 'pm_score': 2, 'selected': False, 'text': '<p>Here\'s one scenario where duck typing saves work.</p>\n\n<p>Here\'s a very trivial class</p>\n\n<pre><code>class BookFinder {\n    def searchEngine\n\n    def findBookByTitle(String title) {\n         return searchEngine.find( [ "Title" : title ] ) \n    }\n}\n</code></pre>\n\n<p>Now for the unit test:</p>\n\n<pre><code>void bookFinderTest() {\n    // with Expando we can \'fake\' any object at runtime.\n    // alternatively you could write a MockSearchEngine class.\n    def mockSearchEngine = new Expando()\n    mockSearchEngine.find = {\n        return new Book("Heart of Darkness","Joseph Conrad")\n    }\n\n    def bf = new BookFinder()\n    bf.searchEngine = mockSearchEngine\n    def book = bf.findBookByTitle("Heart of Darkness")\n    assert(book.author == "Joseph Conrad"\n}\n</code></pre>\n\n<p>We were able to substitute an Expando for the SearchEngine, because of the absence of static type checking. With static type checking we would have had to ensure that SearchEngine was an interface, or at least an abstract class, and create a full mock implementation of it. That\'s labour intensive, or you can use a sophisticated single-purpose mocking framework. But duck typing is general-purpose, and has helped us.</p>\n\n<p>Because of duck typing, our unit test can provide any old object in place of the dependency, just as long as it implements the methods that get called.</p>\n\n<p>To emphasise - you can do this in a statically typed language, with careful use of interfaces and class hierarchies. But with duck typing you can do it with less thinking and fewer keystrokes.</p>\n\n<p>That\'s an advantage of duck typing. It doesn\'t mean that dynamic typing is the right paradigm to use in all situations. In my Groovy projects, I like to switch back to Java in circumstances where I feel that compiler warnings about types are going to help me.</p>\n'}, {'answer_id': 20028746, 'author': 'sukrit007', 'author_id': 3001206, 'author_profile': 'https://Stackoverflow.com/users/3001206', 'pm_score': 3, 'selected': False, 'text': '<p>With, <strong>TDD + 100% Code Coverage</strong> + IDE tools to constantly run my tests, I do not feel a need of static typing any more.  With no strong types, my unit testing has become so easy (Simply use Maps for creating mock objects). Specially , when you are using Generics, you can see the difference:</p>\n\n<pre><code>//Static typing \nMap&lt;String,List&lt;Class1&lt;Class2&gt;&gt;&gt; someMap = [:] as HashMap&lt;String,List&lt;Class1&lt;Class2&gt;&gt;&gt;\n</code></pre>\n\n<p><strong>vs</strong></p>\n\n<pre><code>//Dynamic typing\ndef someMap = [:]   \n</code></pre>\n'}, {'answer_id': 49893071, 'author': 'Evan Langlois', 'author_id': 3847182, 'author_profile': 'https://Stackoverflow.com/users/3847182', 'pm_score': 2, 'selected': False, 'text': "<p>To me, they aren't horribly different if you see dynamically typed languages as simply a form of static typing where everything inherits from a sufficiently abstract base class.</p>\n\n<p>Problems arise when, as many have pointed out, you start getting strange with this.  Someone pointed out a function that returns a single object, a collection, or a null.  Have the function return a specific type, not multiple.  Use multiple functions for single vs collection.</p>\n\n<p>What it boils down to is that anyone can write bad code.  Static typing is a great safety device, but sometimes the helmet gets in the way when you want to feel the wind in your hair.</p>\n"}]
['https://Stackoverflow.com/questions/47972', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3030/']