TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

IF-less programming

64 点作者 alisnic超过 12 年前

28 条评论

raverbashing超过 12 年前
This is getting ridiculous<p>" ifs are a smelly thing in a Object Oriented language."<p>What's smelly is such a absurd assumption. Yes, let's replace every small decision in our program with inheritance and another level of abstraction, that will work out swell<p>Please go read an Assembly manual because you have obviously forgotten what a computer is and does<p>And then we end up with unmaintainable systems with a class hierarchy higher than the Empire State.<p>Of course, as mentioned, replacing an if with a "software structure" (like pattern matching in an functional language) is beneficial, but to call it a code smell is ridiculous
评论 #4977730 未加载
评论 #4977481 未加载
评论 #4977528 未加载
评论 #4977646 未加载
评论 #4978551 未加载
评论 #4977643 未加载
评论 #4979122 未加载
barrkel超过 12 年前
Functional pattern matching (more rigorous IFs) is open for functions but closed for extension. You can write as many functions as you like, but you need to modify all of them if you add a new data type.<p>OO polymorphism is closed for functions but open for extension. You have a fixed number of functions (methods), but you don't need to update all the call sites if you add a new data type - merely implement all the methods.<p>The requirement for what needs to be open and what can be left closed is what determines which choice is better.<p>For example, a GUI framework is best left open for extension, because every application GUI usually ends up with specific widgets custom-designed for that app - sticking with standard widgets tends to make apps form-heavy and lacking in polish. But for the widgets to work in the framework, they need a fixed set of methods to be consistently manipulable.<p>A compiler AST is best left open for functions, because the majority of work on an AST is in algorithms that transform the AST. The language changes at a much slower pace than additional optimizations and analyses, and frequently new language additions can be represented in terms of existing AST constructs (where they are syntax sugar, effectively built-in macros). So having a more fixed set of AST node types is less of an issue.<p>Choosing one or the other on the basis of the orthodox religion of OO or functional programming, meanwhile, is just obtuse.
评论 #4977599 未加载
评论 #4977549 未加载
tallanvor超过 12 年前
Some of this seems petty. For example, the author gives the following "bad" example:<p><pre><code> def method (object) if object.property param = object.property else param = default_param end end </code></pre> And suggests that this is better:<p><pre><code> def method (object) param = object.property || default_param end </code></pre> To me, this is an example of an if statement by another name. Sure, you cut out a few lines, but it's still an if-then construct. Both examples are most likely going to be treated the same way by the compiler as well.
评论 #4977441 未加载
评论 #4977569 未加载
评论 #4977491 未加载
评论 #4977809 未加载
评论 #4977482 未加载
评论 #4977976 未加载
评论 #4977475 未加载
评论 #4977422 未加载
d--b超过 12 年前
No! This practice is absolutely terrible! Object-oriented programming _can_ allow you to make if-free programs, but it will cost you readability/maintainability. Many people have been fighting against the overuse of inheritance and oo patterns that emerged in the 90s. Do not fall in the trap again!
评论 #4977414 未加载
kayoone超过 12 年前
You know whats a smelly thing in OOP ? Overblown abstractions, design patterns and stuff for the sake of flexibility which in the end mostly will never need that kind of flexibility but in turn readability and clearness suffers instantly.<p>I am all for Design Patterns and abstraction, but only when it makes sense.
评论 #4977506 未加载
评论 #4977538 未加载
laurent123456超过 12 年前
In general, this kind of don't-use-this patterns are not very constructive. It reminds of this obsession of not having global objects at all cost. And we end up with singletons, static classes, etc. that are all just global objects in disguise. If I need a global, I use a global and call it that, same if I need an if/else statement.<p>It's an interesting article though, especially the conclusion: "Any language construct must be used when it is the more reasonable thing to do. I like the fact that the presence of if-s can indicate a bad OO design."
评论 #4977400 未加载
rejschaap超过 12 年前
Yeah, I've seen people go down this path. In the next step they realize they need an if-statement to determine whether to instantiate a PDFPrinter or a MSWordPrinter. Which they conveniently hide inside an AbstractPrinterFactory or a ComplexPrinterBuilder. This is probably how the whole Enterprise Java thing got started.
评论 #4977488 未加载
jre超过 12 年前
This is an interesting idea and I think it's interesting to have it somewhere in mind while programming.<p>A few thought though :<p>- If you really push this to the extreme, you'll end up with all the logic hidden in the classes inheritance hierarchy. I'm not sure this is more readable/extensible than if/else statements.<p>- Most of the example given by the author to use "language features" are just syntactic sugar. Using collection.select instead of collection.each or || instead of if else is really just a matter of notation. I doesn't reduce the number of test cases required for your code and it might lead to "magical" one-liners that you have to read 20 times to understand.
davidw超过 12 年前
For those who have never used a functional programming language, those often allow you to do "if-less" or at the very least "if-lite" programming via pattern matching.
评论 #4977451 未加载
评论 #4977419 未加载
praptak超过 12 年前
Those who use <i>if</i> are obviously too flimsy to decide what their programs should do. I would not trust such persons to write any code at all.
Zak超过 12 年前
It's not just an OO thing. If you're using conditionals, you might actually want something else - a dispatch table, for example. Thinking about alternatives to conditionals will probably result in better code most of the time, but actually trying to go if-less seems forced.
Strilanc超过 12 年前
Replacing a switch statement or large if statement with a virtual call (enum -&#62; interface refactoring) can definitely be very beneficial. It can turn [crimes against humanity](<a href="https://github.com/aidanf/Brilltag/blob/master/Tagger_Code/final-state-tagger.c#L145" rel="nofollow">https://github.com/aidanf/Brilltag/blob/master/Tagger_Code/f...</a>) into perfectly respectable code.<p>But, obviously, don't take this too far. If you find yourself not using an if statement (or ternary operator) when writing the absolute value (for non-optimization reasons)... you've gone too far.<p><pre><code> int UnclearAbs(int value) { return value * (value &#62;&#62; 31); }</code></pre>
评论 #4977886 未加载
jwilliams超过 12 年前
This is an aside, but don't use the ruby "to_proc" approach that listed in the article. i.e:<p><pre><code> result = collection.select(&#38;:condition?) </code></pre> The "&#38;:proc" methods are (very, very likely) slower and they also "leak".<p>When I say "leak", the VM doesn't Garbage Collect the parameters of the proc until it is used again. Most of the time this is fine, but when it's not, you're wasting considerable amounts of memory. This is known and is considered within the spec.<p>I know they are semantically equivalent, but the MRI is doing something weird internally. (ps. Learnt this the hard way).
killahpriest超过 12 年前
This is a terrible example of IF-less programming. The conditional is still here, it is just implied.<p>IF:<p><pre><code> def method (object) if object.property param = object.property else param = default_param end end </code></pre> Claimed to be IF-less:<p><pre><code> def method (object) param = object.property || default_param end </code></pre> It may be easier to read, but in the end you are still writing an IF statement.
评论 #4977624 未加载
mwilliamson超过 12 年前
As an example of taking this to an extreme, I was at a coderetreat where we had to implement Conway's Game of Life without any if statements (or similar, such as switches) -- we had to use polymorphism instead. The result was that my partner and I ended up reimplementing a subset of the natural numbers as distinct classes.<p><a href="http://mike.zwobble.org/2012/12/polymorphism-and-reimplementing-integers/" rel="nofollow">http://mike.zwobble.org/2012/12/polymorphism-and-reimplement...</a><p>I'm definitely not advocating this as good programming practice, but the point is that if you're used to always using if statements, then it's hard to learn alternatives. By forcing yourself to use the unfamiliar, you might find some situations where polymorphism is better suited to the problem, whereas you would have previously defaulted to using ifs.<p>(barrkel has already left an excellent comment on when the two styles are useful, so I won't repeat it:<p><a href="http://news.ycombinator.com/item?id=4977487" rel="nofollow">http://news.ycombinator.com/item?id=4977487</a>)
lclarkmichalek超过 12 年前
The first example is an actual example of how removing ifs can reduce complexity, but the last few seem misguided. It is no easier to test `collection.each {|item| result &#60;&#60; item if item.condition? }` than `collections.select(&#38;:condition)`; they are all but equivalent. The exception handling example doesn't actually show the benefit of not using ifs, it shows the benefits of using exceptions over return values. Setting up default values via || is also a nice trick, but it hardly makes a macro difference.<p>Also, "# I slept during functional classes"? I don't know ruby, but the `each` method seems to be just a variant of map, which is a pretty fundamental functional construct.
评论 #4977712 未加载
primitur超过 12 年前
One reason why "ifs are smelly" has become a maxim in some circles is because they represent an under-tested code path. In such areas as safety-critical/life systems, where a different codepath can be taken on the basis of a single var, this can be a very, very dangerous practice. Certainly in safety-critical, a reduction of "if"-based codepaths represents <i>higher quality software</i> in the end.<p>I have seen cases of radiation-derived bit-rot which don't manifest in any way until a certain "if"-path is evaluated by the computer - this seriously does happen and can still happen in modern computers today.<p>Having an abundance of such code switch points in a particularly large codebase can be a degree of complexity that nobody really wants to manage - or in the case of disaster, be responsible for .. so this maxim has been pretty solidly presented in industrial computing for a while. Make the decision-making as minimal as possible to get the job done, and don't over-rely on the ability of the computer to evaluate the expression in order to build robust software.<p>Now, its sort of amusing that this has propagated into the higher-order realms of general application development by which most Class/Object-oriented developers are employed .. but it is still an equally valid position to take. State changes in an application can be implemented in a number of different ways, "if" being one of the more banal mechanisms - there are of course other mechanisms as well (duffs devices, etc.) which are equally testable, yet more robust - simply because they break sooner, and can thus be tested better.<p>I take the position, however, that a well-designed class hierarchy won't need much navel-gazing decision-making, which is what the ol' "if (something == SOMETYPE)" statement really is: a kind of internal house-keeping mechanism being done by the computer at runtime, instead of at compile-time.<p>So there is a balance to this maxim, and the key to it is this: how complex does it need to be, versus how complex can the codebase be before it becomes unmanageable. If you're not doing full code-coverage testing with 100% testing of potential codepaths, then every single if statement represents a potential bug you didn't catch yet.
alter8超过 12 年前
A nice blog series on if-less programming (in Portuguese): <a href="http://alquerubim.blogspot.com/search/label/ifless" rel="nofollow">http://alquerubim.blogspot.com/search/label/ifless</a>
riffraff超过 12 年前
Not endorsing, but much more expanded by the Anti-IF campaign <a href="http://www.antiifcampaign.com/" rel="nofollow">http://www.antiifcampaign.com/</a> (which focuses on "bad IFs")
bane超过 12 年前
I'm a little surprised nobody is lamenting the performance hit this kind of technique will incur vs just using an if statement.<p>(reaching into my way back machine, ifs essentially compile down to a few comparison instructions (which are often just subtractions) and a jmp instruction (depending on the platform), it's literally built into the processor! For a simple if statement we might be talking a handful of cycles to eval the if vs an extended call stack pumping and dumping exercise)
评论 #4978062 未加载
jayvanguard超过 12 年前
2001 called, it wants its debate back. For all the new kids on the internet: OO doesn't enable re-use, inheritance generally sucks, and bloating your code with new types just to solve something three lines of if/then/else could solve isn't worth it.
polskibus超过 12 年前
If you're doing "ifs" on the same condition sets in various functions then you should consider encapsulating the condition in class hierarchy. If there is just one if for a condition set, introducing a class hierarchy is just bloat.
andrewcooke超过 12 年前
how does "try to use less X because Y" become "don't use X"? and why is this considered good?<p>to clarify: my question "why is this considered good?" isn't about "if-less programming", but about taking ideas to dumb extremes.
评论 #4977383 未加载
lucian1900超过 12 年前
Replacing static decisions with polymorphism is indeed often a good idea, but there's nothing wrong with using if when it's appropriate.
PaulHoule超过 12 年前
The problem isn't if, it's "else if".<p>If-then-else ladders tend to evolve to be very difficult to understand, maintain and debug
gbog超过 12 年前
An often better alternative to inheritance for conditionals is configuration with functions as values.
wildranter超过 12 年前
Don't. Just don't. Do you think Da Vinci would've painted just with oil because people think real painters work just with that? No he didn't, and so you shouldn't too.<p>Don't limit yourself just to blindly comply to some silly idea. Use everything you know to get the job done, and once you get it working, make it beautiful.<p>If statements are an incredible tool. Just ask any Erlanger and they will either tell how much they miss it, or just lie to your face. ;)
评论 #4977556 未加载
sublimit超过 12 年前
Oh great. What will you people come up with next? Variableless programming?
评论 #4977619 未加载
评论 #4979168 未加载