Sunday, January 29, 2012

Type hinting is bad!

Type hinting is bad..if it's done wrong.

Type hinting was introduced in PHP 5 allowing you to force parameters to be specific types of objects or an array. At first glance this is great because of the built-in support for type validation. In the example below there's a type hint on the function transport forcing $car to be of type Car.
class Car {
 public function load(array $cargo) { ... }

 public function go() { ... }
}

function transport(Car $car) {
 $cargo = array('groceries', 'children', 'misc items');
 $car->load($cargo);
 $car->go();
}

$car = new Car();
transport($car);
We can use $car without having to write code to check it's type. A fatal error is thrown if $car is not an instance of type Car.

The problem with this style of programming is you're sacrificing one of the biggest strengths of PHP: the ability to duck type. After all this time of programming with a dynamic language why have we become so concerned with types? Had we not put a type hint on the transport function the code would have still worked. Let's remove the Car type hint.
function transport($car) {
 $cargo = array('groceries', 'children', 'misc items');
 $car->load($cargo);
 $car->go();
}

$car = new Car();
transport($car);
This is better because it is more flexible. $car can be anything as long as it can load() and go(). You can change $car to be a Van and you'll still get your cargo safely loaded and transported assuming Van can load() and go().
$car = new Van();
transport($car);

Can't you use inheritance in this case and still utilize type hinting?
Inheritance could be used and the function would take advantage of subtype polymorphism.
abstract class Vehicle {
  abstract public function load(array $cargo);
  abstract public function go();
}

class Car extends Vehicle { ... }

class Van extends Vehicle { ...}

function transport(Vehicle $vehicle) {
 $cargo = array('groceries', 'children', 'misc items');
 $vehicle->load($cargo);
 $vehicle->go();
}

$vehicle = new Van();
transport($vehicle);
This is still not ideal. What if you wanted to use something other than a Vehicle to do your transportation (e.g. Boat, Train, or Horse and Wagon)? To make this code more reusable we should follow an object-oriented design principle: "Program to an interface, not an implementation". Fundamentally we don't care what an object is; instead we care about what an object can do.
interface ITransporter {
  public function load(array $cargo);
  public function go();
}

class Car implements ITransporter { ... }

class Van implements ITransporter { ... }

class Horse implements ITransporter { ... }

function transport(ITransporter $transporter) {
  $cargo = array('groceries', 'children', 'misc items');
  $transporter->load($cargo);
  $transporter->go();
}

$transporter = new Horse();
transport($transporter);
If you wanted maximum flexibility why even put an object or interface type hint? As long as the parameter can load() and go() the transport function should work. The type hint validation is only enforced at runtime. If an object was passed into the transport function that didn't have a load or go method you would still get a fatal runtime error. It seems like the type hint isn't useful.
That's almost completely true. There is a subtlety. Using a type hint would error sooner. This may or may not be important to you.
function transport(ITransporter $transporter) {
  $cargo = getCargo();
  $transporter->load($cargo);
  $transporter->go();
}
In this example, what if getCargo() uses an external service like a database connection or a web service. It's nice to know $transporter can load() and go() before using resources to getCargo(). If $transporter didn't support the necessary interface then an error would be thrown immediately and no resources would be wasted. It's up to you to decide which is more important: the ability to error early or the flexibility of using duck typing.
I use type hinting because my IDE uses it to provide code completion.
You can use annotations and/or interface type hinting and your IDE will provide code completion. You don't have to sacrifice good object oriented design for the sake of your IDE.

36 comments:

  1. So, it's very good for you to know something about interfaces :)
    You are on the right way :)

    ReplyDelete
  2. Wow amazing i saw the article with execution models you had posted. It was such informative. Really its a wonderful article. Thank you for sharing and please keep update like this type of article because i want to learn more relevant to this topic.


    Salesforce Training

    ReplyDelete



  3. This content creates a new hope and inspiration with in me. Thanks for sharing article like this. The way you have stated everything above is quite awesome. Keep blogging like this. Thanks.


    SAP training in Chennai

    ReplyDelete
  4. Excellent and very cool idea and the subject at the top of magnificence and I am happy to this post..Interesting post! Thanks for writing it. What's wrong with this kind of post exactly? It follows your previous guideline for post length as well as clarity..

    Digital marketing company in Chennai

    ReplyDelete
  5. Wonderful blog.. Thanks for sharing informative blog.. its very useful to me..

    iOS Training in Chennai

    ReplyDelete
  6. Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing.Blue Prism Training Institute in Chennai | RPA Training Institute in Chennai | UiPath Training in Chennai

    ReplyDelete
  7. You have provided a nice article, Thank you very much for this one. And I hope this will be useful for many people. And I am waiting for your next post keep on updating these kinds of knowledgeable things.
    Loadrunner Training in Chennai
    JAVA Training in Chennai
    Hadoop Training in Chennai
    Selenium Training in Chennai
    German Classes in chennai
    PHP Training in Chennai
    php course

    ReplyDelete
  8. To get the best Assignment Help, connect with the reliable and trustworthy service provider. If you need to explore your knowledge how these writing services work and impact of these in your academic performance, visit greatassignmenthelp
    Assignment Help Online
    Online Assignment Help
    Assignment Help Online Services
    Assignment Helper
    Assignment Assistance
    Assignment Help Experts
    Online Assignment Help Services

    ReplyDelete
  9. A very high level post with a knowledgeable information .thanks you for giving me such a nice information. If you need any college level
    Assignment Help at reliable quality with better work. Kindly visit livewebtutors website we providing best assignment help services in
    Australia, USA, UK, UAE, and Canada etc.
    Read more now :- Finance Assignment Help

    ReplyDelete
  10. Great blog! It gives the ideas how to enjoy Nepal tour. It is very helpful for booking Nepal tour packages. Thanks for sharing this blog.
    Nepal Tour Packages
    Nepal Tour Package
    Nepal Tourism Packages
    Nepal Tourist Packages
    Nepal Tour
    Most Beautiful Places In The World

    ReplyDelete
  11. Nice Blog, I have get enough information from your blog and I appreciate your way of writing.
    Thanks for everything and dial our Outlook support phone number for technical support and information of Outlook.
    How do I contact Microsoft tech support?”
    How do I contact Microsoft Outlook support
    Is there a phone number for Outlook support
    Outlook support
    Outlook support Phone Number
    Outlook support Number
    How Do I Call Outlook Support

    ReplyDelete
  12. Understand the importance of Assignment Help services before placing your order. Talk to our academic writer for more clarification on assignment writing services. Time to deal with your assignment stress using professional services.
    Assignment Help Online
    Best Assignment Help
    Assignment Helper
    Assignment Help In USA
    Online Assignment Help
    Assignment Help Experts
    Online Assignment Help Services

    ReplyDelete
  13. I suggest everyone to choose Assignment Help Australia for getting the best guidance in their academia. The proficient experts assist as per the requirements and learning styles desired by the university.

    ReplyDelete
  14. Heel erg bedankt voor het delen van deze prachtige blog. Ik moet zeggen dat je een ongelooflijke schrijver bent, ik hou van de manier waarop je de dingen beschrijft. Blijf delen. Ondersteuning krijgen klik hier

    Garmin Express
    garmin navigatie
    garmin update
    windows update werkt niet
    garmin navigatie update
    www.garmin.com/express
    garmin navigatie auto
    garmin express werkt niet

    ReplyDelete
  15. Do you know the genuine possible behind the non-working of HP Printer? Well, you do not feel worse as you come in the strong grip of Printer office. This is the invalidate condition as there lies some break for the Printer Is Offline Windows 10. No matter how many times you jump on the print command using the file menu of word file and other concerning page, the printer cannot yield the quality result. It is the best option that you would have to come on our third party professional as you are firm minded to eradicate the maximum problems. Feel free to contact our team.
    how to get printer online
    how do i get my printer online
    HP Solution Center
    HP Solution Center Windows 10
    Error Printing
    Printer Error
    hp printer driver is unavailable
    printer driver unavailable
    driver is unavailable printer

    ReplyDelete
  16. Thanks for sharing is so amazing and helpful to us.
    Buy Hydrocodone online

    ReplyDelete
  17. Myassignmenthelp offers the best assignment help service online by a team of professional and experienced academic writers.

    ReplyDelete
  18. Make your assignment submission more effective using Assignment Help services. This Online Assignment Help service allows students to discuss their concerns with qualified Assignment Helper and finish their assignment on time.

    ReplyDelete
  19. 'I'm highly impressed by the piece of thoughts you have shared on this portal. all the best
    connect us on Assignment Help can shed your burden of assignments with a return of qualitative assignments.

    ReplyDelete

  20. Best Article buy Pain Pills online Excellent post. I appreciate this site. Stick with it! Because the admin of this web page is working, no doubt very quickly it will be well-known, due to its quality contents.This website was how do you say it? Relevant!! Finally, I’ve found something that helped me.
    Best Article buy Roxicodone online Excellent post
    buy Xanax online
    buy Oxycodone online

    Best Article buy Pain Medications online Excellent post. I appreciate this site. Stick with it! Because the admin of this web page is working, no doubt very quickly it will be well-known, due to its quality contents.This website was how do you say it? Relevant!! Finally, I’ve found something that helped me.

    buy Research Chemicals online

    buy Roxicodone online

    buy Cbd Isolate online

    ReplyDelete
  21. Taking assignment orders and just randomly fulfilling the needs is not something that our expert writers do at My Assignment Help. Our My Assignment Help services are of top quality, for every assignment that we deliver, we make sure that we deliver best quality papers.

    ReplyDelete
  22. Great Article. Thank you for sharing! Really an awesome post for every one.

    IEEE Final Year projects Project Centers in Chennai are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes, while specialists like the enjoyment in interfering with innovation. For experts, it's an alternate ball game through and through. Smaller than expected IEEE Final Year project centers ground for all fragments of CSE & IT engineers hoping to assemble. Final Year Project Domains for IT It gives you tips and rules that is progressively critical to consider while choosing any final year project point.

    JavaScript Training in Chennai

    JavaScript Training in Chennai

    ReplyDelete
  23. Our online assignment writers aim to become a helping hand of the students who need a proficient assignment writing help to balance out their academics with work. We understand the struggle to ace academic, in the cut-throat competition. We also know how heated up pressures you go through. Stressing out does no good, but playing smart does. Play smart, and reach out to us for resolute academic help.

    ReplyDelete
  24. i-LEND is an online marketplace connecting borrowers and lenders for loans. Although i-LEND verifies credentials of registered users on the site, it does not guarantee any loan offers by lenders nor does it guarantee any repayments by borrowers. Users make offers/loan requests at their own discretion with the understanding of the risks involved in such transactions including loss of entire capital and/or no guarantee of recovery. Please read our Legal agreements to understand more. https://www.i-lend.in/

    ReplyDelete
  25. KloudWIFI truly believes that reliable, fast networks have been the game changers in driving innovation, productivity and instant collaboration supported by the relentless growth of convenient cloud-hosted applications. Even with a powerful, proven network infrastructure like Cisco Meraki and Ekahau, the end user experience can only be truly optimized by considering all the internal and external factors to the end user experiences. https://www.kloudwifi.com wireless lan solutions partner in Hyderabad

    ReplyDelete