Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Would that copy-paste code ever amount to more than some getter methods, like the get_speed() example you provided? If the speed field had some special behaviour, couldn't you wrap it in its own Speed type, with its own methods, and use that from the enclosing types?


I think the solution you've proposed is probably how you'd do it - but isn't inheritance more elegant in this case (i.e. using a language which supports inheritance if this is important to you)


No, inheritance is not an elegant way to mix in shared data and behavior. It can seem like it is in a simple case where there is only one set of data and behavior you want to mix in, but it scales very poorly. Nothing is fundamentally a single kind of thing, and multiple inheritance is a mess. It is more elegant to mix the behavior in through delegation, because it scales to however many things you want to mix in. Carrying on the synthetic example in this thread, you can mix in Speed and Pedals into Bicycle but Speed and Cylinders into Car.


Maybe not on every situation, but I do agree that inheritance is more elegant in a lot of situations, in the sense that it gets some behaviour "out of the way".




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: