Search Results

Search found 161 results on 7 pages for 'the rubber duck'.

Page 1/7 | 1 2 3 4 5 6 7  | Next Page >

  • Is duck typing a subset of polymorphism

    - by Raynos
    From Polymorphism on WIkipedia In computer science, polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface. From duck typing on Wikipedia In computer programming with object-oriented programming languages, duck typing is a style of dynamic typing in which an object's current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface. My interpretation is that based on duck typing, the objects methods/properties determine the valid semantics. Meaning that the objects current shape determines the interface it upholds. From polymorphism you can say a function is polymorphic if it accepts multiple different data types as long as they uphold an interface. So if a function can duck type, it can accept multiple different data types and operate on them as long as those data types have the correct methods/properties and thus uphold the interface. (Usage of the term interface is meant not as a code construct but more as a descriptive, documenting construct) What is the correct relationship between ducktyping and polymorphism ? If a language can duck type, does it mean it can do polymorphism ?

    Read the article

  • Python Forgiveness vs. Permission and Duck Typing

    - by darkfeline
    In Python, I often hear that it is better to "beg forgiveness" (exception catching) instead of "ask permission" (type/condition checking). In regards to enforcing duck typing in Python, is this try: x = foo.bar except AttributeError: pass else: do(x) better or worse than if hasattr(foo, "bar"): do(foo.bar) else: pass in terms of performance, readability, "pythonic", or some other important factor?

    Read the article

  • Is a rubber keyboard suitable for heavy use?

    - by Vilx-
    Every keyboard wears out with time, and mine has some age already. The day it fails is coming closer and closer. So I'm slowly starting to look around for a new one. I use the keyboard for gaming and programming, so it gets some pretty solid use. I also tend to eat by the computer, so there's plenty of... uhh... lifeforms down there. Anyway, I was looking at these rubber keyboards. They come pretty cheap (my local computer shop has one for less than $20) and they seem to have some nice properties. They can be easily cleaned, they're quiet, and can be rolled up when needed (plus no worries about spilled drinks). However I'm wondering what their type-ability is. If I can't write on it at a decent speed, the rest of the features don't matter. Not that I'm a fast typer, but being a professional progammer does give a boost to the skill. I couldn't find any reviews on the net so I'm turning to you. Who has used these keyboards and what was your experience? Perhaps there is something else I haven't though of why such a keyboard would not be a good idea?

    Read the article

  • What's an example of duck typing in Java?

    - by Cuga
    I just recently heard of duck typing and I read the Wikipedia article about it, but I'm having a hard time translating the examples into Java, which would really help my understanding. Would anyone be able to give a clear example of duck typing in Java and how I might possibly use it?

    Read the article

  • Most Up-To-Date C# Duck-Typing Library

    - by Anton Gogolev
    The title says it all, basically. What is the current state of the art on duck typing for C# below version 4.0? I know about Duck Typing Project, I know that BLTookit has something to that end, but I'd like to know if I'm missing something really wicked apart from DLR languages and C# 4.0. The inevitable:

    Read the article

  • Duck type testing with C# 4 for dynamic objects.

    - by Tracker1
    I'm wanting to have a simple duck typing example in C# using dynamic objects. It would seem to me, that a dynamic object should have HasValue/HasProperty/HasMethod methods with a single string parameter for the name of the value, property, or method you are looking for before trying to run against it. I'm trying to avoid try/catch blocks, and deeper reflection if possible. It just seems to be a common practice for duck typing in dynamic languages (JS, Ruby, Python etc.) that is to test for a property/method before trying to use it, then falling back to a default, or throwing a controlled exception. The example below is basically what I want to accomplish. If the methods described above don't exist, does anyone have premade extension methods for dynamic that will do this? Example: In JavaScript I can test for a method on an object fairly easily. //JavaScript function quack(duck) { if (duck && typeof duck.quack === "function") { return duck.quack(); } return null; //nothing to return, not a duck } How would I do the same in C#? //C# 4 dynamic Quack(dynamic duck) { //how do I test that the duck is not null, //and has a quack method? //if it doesn't quack, return null }

    Read the article

  • what is duck typing?

    - by ashish yadav
    I recently read an article about duck-typing.It said about calling functions of different classes using object of any class. Is it true?And how will the compiler do it on runtime? I apologize if i am not clear.But it really fascinates me , if we could do it dynamically. So if u people got any idea.I am all ears. thank you!! how will the function be accessed by object of any other class. that violates the basic principle of OOP.and that too dynamically during runtime. And is this feature possible in case of OOP languages?

    Read the article

  • Duck checker in Python: does one exist?

    - by elliot42
    Python uses duck-typing, rather than static type checking. But many of the same concerns ultimately apply: does an object have the desired methods and attributes? Do those attributes have valid, in-range values? Whether you're writing constraints in code, or writing test cases, or validating user input, or just debugging, inevitably somewhere you'll need to verify that an object is still in a proper state--that it still "looks like a duck" and "quacks like a duck." In statically typed languages you can simply declare "int x", and anytime you create or mutate x, it will always be a valid int. It seems feasible to decorate a Python object to ensure that it is valid under certain constraints, and that every time that object is mutated it is still valid under those constraints. Ideally there would be a simple declarative syntax to express "hasattr length and length is non-negative" (not in those words. Not unlike Rails validators, but less human-language and more programming-language). You could think of this as ad-hoc interface/type system, or you could think of it as an ever-present object-level unit test. Does such a library exist to declare and validate constraint/duck-checking on Python-objects? Is this an unreasonable tool to want? :) (Thanks!) Contrived example: rectangle = {'length': 5, 'width': 10} # We live in a fictional universe where multiplication is super expensive. # Therefore any time we multiply, we need to cache the results. def area(rect): if 'area' in rect: return rect['area'] rect['area'] = rect['length'] * rect['width'] return rect['area'] print area(rectangle) rectangle['length'] = 15 print area(rectangle) # compare expected vs. actual output! # imagine the same thing with object attributes rather than dictionary keys.

    Read the article

  • Simulating aspects of static-typing in a duck-typed language

    - by Mike
    In my current job I'm building a suite of Perl scripts that depend heavily on objects. (using Perl's bless() on a Hash to get as close to OO as possible) Now, for lack of a better way of putting this, most programmers at my company aren't very smart. Worse, they don't like reading documentation and seem to have a problem understanding other people's code. Cowboy coding is the game here. Whenever they encounter a problem and try to fix it, they come up with a horrendous solution that actually solves nothing and usually makes it worse. This results in me, frankly, not trusting them with code written in duck typed language. As an example, I see too many problems with them not getting an explicit error for misusing objects. For instance, if type A has member foo, and they do something like, instance->goo, they aren't going to see the problem immediately. It will return a null/undefined value, and they will probably waste an hour finding the cause. Then end up changing something else because they didn't properly identify the original problem. So I'm brainstorming for a way to keep my scripting language (its rapid development is an advantage) but give an explicit error message when an an object isn't used properly. I realize that since there isn't a compile stage or static typing, the error will have to be at run time. I'm fine with this, so long as the user gets a very explicit notice saying "this object doesn't have X" As part of my solution, I don't want it to be required that they check if a method/variable exists before trying to use it. Even though my work is in Perl, I think this can be language agnostic.

    Read the article

  • Passthrough Objects – Duck Typing++

    - by EltonStoneman
    [Source: http://geekswithblogs.net/EltonStoneman] Can't see a genuine use for this, but I got the idea in my head and wanted to work it through. It's an extension to the idea of duck typing, for scenarios where types have similar behaviour, but implemented in differently-named members. So you may have a set of objects you want to treat as an interface, which don't implement the interface explicitly, and don't have the same member names so they can't be duck-typed into implicitly implementing the interface. In a fictitious example, I want to call Get on whichever ICache implementation is current, and have the call passed through to the relevant method – whether it's called Read, Retrieve or whatever: A sample implementation is up on github here: PassthroughSample. This uses Castle's DynamicProxy behind the scenes in the same way as my duck typing sample, but allows you to configure the passthrough to specify how the inner (implementation) and outer (interface) members are mapped:       var setup = new Passthrough();     var cache = setup.Create("PassthroughSample.Tests.Stubs.AspNetCache, PassthroughSample.Tests")                             .WithPassthrough("Name", "CacheName")                             .WithPassthrough("Get", "Retrieve")                             .WithPassthrough("Set", "Insert")                             .As<ICache>(); - or using some ugly Lambdas to avoid the strings :     Expression<Func<ICache, string, object>> get = (o, s) => o.Get(s);     Expression<Func<Memcached, string, object>> read = (i, s) => i.Read(s);     Expression<Action<ICache, string, object>> set = (o, s, obj) => o.Set(s, obj);     Expression<Action<Memcached, string, object>> insert = (i, s, obj) => i.Put(s, obj);       ICache cache = new Passthrough<ICache, Memcached>()                     .Create()                     .WithPassthrough(o => o.Name, i => i.InstanceName)                     .WithPassthrough(get, read)                     .WithPassthrough(set, insert)                     .As();   - or even in config:   ICache cache = Passthrough.GetConfigured<ICache>(); ...  <passthrough>     <types>       <typename="PassthroughSample.Tests.Stubs.ICache, PassthroughSample.Tests"             passesThroughTo="PassthroughSample.Tests.Stubs.AppFabricCache, PassthroughSample.Tests">         <members>           <membername="Name"passesThroughTo="RegionName"/>           <membername="Get"passesThroughTo="Out"/>           <membername="Set"passesThroughTo="In"/>         </members>       </type>   Possibly useful for injecting stubs for dependencies in tests, when your application code isn't using an IoC container. Possibly it also has an alternative implementation using .NET 4.0 dynamic objects, rather than the dynamic proxy.

    Read the article

  • Simulate 'Shock absorbtion' with tire rubber in PhysX (2.8.x)

    - by Mungoid
    This is a kinda tricky question and I fear there is no easy enough solution, but I figured I'd hit SE up before giving up on it and just doing what I can. A machine I am working on has no suspension or shocks or springs of any sort in the real machine, so you would think that when it drives over bumps, it would shake like crazy but because its tires (6 of them) are quite large they seem to absorb a lot of shock from the bumps. Part of this is because the machine is around 30k lbs and it just smashes/compresses any bumps in the ground down (This is another issue im still working on) and the other part is that the tires seem to have a lot of flex to them with a lot of air as well. So my current task is to simulate shock absorption in physx without visibly separating the tires from the spindle/axle.. I have been messing with all kinds of NxMaterial, NxSpring, Joints, etc. and have had no luck getting this to work. The main problem is that the spindle attached to the tire is directly in the center and the axle is basically solidly attached to the chassis, so if i give it any spring or suspension travel, that spindle on the tires will move upwards or downwards, looking very odd because now its not any longer in the center of the tire. I tried giving it a higher restitution but that just makes it bouncy without any shock absorption. Another avenue I am messing with is to actively smooth the terrain in front of the tires so that before it hits a bumpy patch, that patch is smoothed and it doesn't bounce. The only issue with this is that it is pretty expensive to do with 6 tires, high tesselation of the terrain and other complex things going on at the same time in this simulation. I am still working on this but I am hoping to mix and match a few different aspects to get the best possible outcome. This is a bit of a complex issue so I'm not expecting anyone to have a definitive answer, just hoping someone may think of something I haven't =-) -Side note: Yes i know PhysX 2.8.x is quite outdated but we have to stick with it for this implementation. We are in the process of going to another physics engine but it is out of scope to apply that engine to this project.

    Read the article

  • Is context inheritance, as shown by Head First Design Patterns' Duck example, irrelevant to strategy pattern?

    - by Korey Hinton
    In Head First Design Patterns it teaches the strategy pattern by using a Duck example where different subclasses of Duck can be assigned a particular behavior at runtime. From my understanding the purpose of the strategy pattern is to change an object's behavior at runtime. Emphasis on "an" meaning one. Could I further simplify this example by just having a Duck class (no derived classes)? Then when implementing one duck object it can be assigned different behaviors based on certain circumstances that aren't dependent on its own object type. For example: FlyBehavior changes based on the weather or QuackBehavior changes based on the time of day or how hungry a duck is. Would my example above constitute the strategy pattern as well? Is context inheritance (Duck) irrelevant to the strategy pattern or is that the reason for the strategy pattern? Here is the UML diagram from the Head First book:

    Read the article

  • Drawing rubber band line during user drag

    - by Pete W
    In my iPhone app, I would like the user to be able to "connect" two of my views by: 1) starting a drag in View A 2) as they drag towards View B, a straight line with one end in View A and the other end under at the current drag point, animates in a rubber-band fashion 3) when/if they release in View B, the line is then shown between the two views I've seen examples of dragging and dropping views, and other examples of animations, but I haven't seen one that is a simple example of this kind of user-directed animation. Any pointers towards examples or the specific docs I should be looking at would be appreciated. If this turns out to be trivial - my apologies. Although I've done quite a bit of development, I'm just getting started in the iPhone SDK and Core Graphics.

    Read the article

  • How do I install rubber pins onto a case fan?

    - by Resorath
    I have the following rubber pins with my new case fan: I'm not sure how to install these. They are obvious to install into the case, the rubber pulls easily into the screw hole and stays in place, however the fan they came with they do not seem to fit in the screw holes at all. I put the thin side into the fan and pulled so hard that it actually snapped the rubber, so obviously that is not the correct method. How do you install these rubber pins into stubborn fans of which they were designed for?

    Read the article

  • Ruby and duck typing: design by contract impossible?

    - by davetron5000
    Method signature in Java: public List<String> getFilesIn(List<File> directories) similar one in ruby def get_files_in(directories) In the case of Java, the type system gives me information about what the method expects and delivers. In Ruby's case, I have no clue what I'm supposed to pass in, or what I'll expect to receive. In Java, the object must formally implement the interface. In Ruby, the object being passed in must respond to whatever methods are called in the method defined here. This seems highly problematic: Even with 100% accurate, up-to-date documentation, the Ruby code has to essentially expose its implementation, breaking encapsulation. "OO purity" aside, this would seem to be a maintenance nightmare. The Ruby code gives me no clue what's being returned; I would have to essentially experiment, or read the code to find out what methods the returned object would respond to. Not looking to debate static typing vs duck typing, but looking to understand how you maintain a production system where you have almost no ability to design by contract. Update No one has really addressed the exposure of a method's internal implementation via documentation that this approach requires. Since there are no interfaces, if I'm not expecting a particular type, don't I have to itemize every method I might call so that the caller knows what can be passed in? Or is this just an edge case that doesn't really come up?

    Read the article

  • Sorting a string in array, making it sparsely populated.

    - by S1syphus
    For example, say I have string like: duck duck duck duck goose goose goose dog And I want it to be as sparsely populated as possible, say in this case duck goose duck goose dog duck goose duck What sort of algorithm would you recommend? Snippets of code or general pointers would be useful, languages welcome Python, C++ and extra kudos if you have a way to do it in bash.

    Read the article

  • Does C# have an equivalent to Scala's structural typing?

    - by Tom Morris
    In Scala, I can define structural types as follows: type Pressable { def press(): Unit } This means that I can define a function or method which takes as an argument something that is Pressable, like this: def foo(i: Pressable) { // etc. The object which I pass to this function must have defined for it a method called press() that matches the type signature defined in the type - takes no arguments, returns Unit (Scala's version of void). I can even use the structural type inline: def foo(i: { def press(): Unit }) { // etc. It basically allows the programmer to have all the benefits of duck typing while still having the benefit of compile-time type checking. Does C# have something similar? I've Googled but can't find anything, but I'm not familiar with C# in any depth. If there aren't, are there any plans to add this?

    Read the article

  • Should I use concrete Inheritance or not?

    - by Mez
    I have a project using Propel where I have three objects (potentially more in the future) Occasion Event extends Occasion Gig extends Occasion Occasion is an item that has the shared things, that will always be needed (Venue, start, end etc) With this - I want to be able to add in extra functionality, say for example, adding "Band" objects to the Gig object, or "Flyers" to an "Event" object. For this, I plan to create objects for these. However, without concrete inheritance, I have to have the foreign key point to the Occasion object - giving the (propel generated) functions for all of these extra bits to anything inherited from Occasion. I could, in theory do this without a foreign constraint, and add in functions to use the Peer or Query classes to get things related to the "Gig" or similar. Whereas with concrete inheritance, I would only have these functions in the things where they are. I think the decision here is whether I should Duck Type the objects (after all they are occasions) or whether I should just use the "Occasion" object as a "template" (only being used to search for things, like, all occasions at a venue) Thoughts? Comments?

    Read the article

  • Optional structural typing possibilty in C++ or anyother language?

    - by ambhai
    In C++ how to tell compiler that Ogre::Vector3 IS_SAME_AS SomeOtherLIB::Vector3 ? I feel that.. in languages like c++ which are not structural typed but there are cases when it makes sense. Normally as game developer when working with 4+ libraries that provide sort or their own Vector3 implementation. The code is littered with ToOgre, ToThis, ToThat conversion function. Thats a lot of Float3 copying around which should not happen on first place. Is in C++ or any other languages where we dont have to convert (copying) from one type to another which is essentially the samething. But any solution in C++ as most of the good gamedevs libs are for c/c++.

    Read the article

  • Better Understand the 'Strategy' Design Pattern

    - by Imran Omar Bukhsh
    Greetings Hope you all are doing great. I have been interested in design patterns for a while and started reading 'Head First Design Patterns'. I started with the first pattern called the 'Strategy' pattern. I went through the problem outlined in the images below and first tried to propose a solution myself so I could really grasp the importance of the pattern. So my question is that why is my solution ( below ) to the problem outlined in the images below not good enough. What are the good / bad points of my solution vs the pattern? What makes the pattern clearly the only viable solution ? Thanks for you input, hope it will help me better understand the pattern. MY SOLUTION Parent Class: DUCK <?php class Duck { public $swimmable; public $quackable; public $flyable; function display() { echo "A Duck Looks Like This<BR/>"; } function quack() { if($this->quackable==1) { echo("Quack<BR/>"); } } function swim() { if($this->swimmable==1) { echo("Swim<BR/>"); } } function fly() { if($this->flyable==1) { echo("Fly<BR/>"); } } } ?> INHERITING CLASS: MallardDuck <?php class MallardDuck extends Duck { function MallardDuck() { $this->quackable = 1; $this->swimmable = 1; } function display() { echo "A Mallard Duck Looks Like This<BR/>"; } } ?> INHERITING CLASS: WoddenDecoyDuck <?php class WoddenDecoyDuck extends Duck { function woddendecoyduck() { $this->quackable = 0; $this->swimmable = 0; } function display() { echo "A Wooden Decoy Duck Looks Like This<BR/>"; } } Thanking you for your input. Imran

    Read the article

  • Questioning pythonic type checking

    - by Pace
    I've seen countless times the following approach suggested for "taking in a collection of objects and doing X if X is a Y and ignoring the object otherwise" def quackAllDucks(ducks): for duck in ducks: try: duck.quack("QUACK") except AttributeError: #Not a duck, can't quack, don't worry about it pass The alternative implementation below always gets flak for the performance hit caused by type checking def quackAllDucks(ducks): for duck in ducks: if hasattr(duck,"quack"): duck.quack("QUACK") However, it seems to me that in 99% of scenarios you would want to use the second solution because of the following: If the user gets the parameters wrong then they will not be treated like a duck and there will be no indication. A lot of time will be wasted debugging why there is no quacking going on until the user finally realizes his silly mistake. The second solution would throw a stack trace as soon the user tried to quack. If the user has any bugs in their quack() method which cause an AttributeError then those bugs will be silently swallowed. Once again time will be wasted digging for the bug when the second solution would simply give a stack trace showing the immediate issue. In fact, it seems to me that the only time you would ever want to use the first method is when: The block of code in question is in an extremely performance critical section of your application. Following the principal of "avoid premature optimization" you would only realize this of course, after you had implemented the safer approach and found it to be a bottleneck. There are many types of quacking objects out there and you are only interested in quacking objects that quack with a very specific set of arguments (this seems to be a very rare case to me). Given this, why is it that so many people prefer the first approach over the second approach? What is it that I am missing? Also, I realize there are other solutions (such as using abcs) but these are the two solutions I seem to see most often for the basic case.

    Read the article

  • HOW-TO Make computer sing

    - by Ofir
    Hi, I'm trying to develop an online application where the user writes some text and the software sings it back to the user. I can currently generate the audio file with the words spoken by the computer using espeak, but I have no idea how to make it sound like a song, how to add rhythm to it. I'm able to change the pitch and tempo using rubberband, but that's as far as I've gotten. Does anyone have a clue how to make this happen?

    Read the article

1 2 3 4 5 6 7  | Next Page >