TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Ask HN: What are the best programming tricks you know?

86 pointsby kacperlukawskialmost 3 years ago
During my studies, I was surprised that even a variable swap might be optimized to work in place by using XOR. Since then, I got surprised at least a few times more. For example when I was working a lot with SQL and found some engine-specific optimizations.<p>What were the simplest, or the most clever neat tricks you faced in your career? I mean both things simple and elegant, but also some really dirty hacks it&#x27;s hard to believe can work.

79 comments

mabboalmost 3 years ago
The most clever trick I&#x27;ve learned as a programmer is not to use clever tricks.<p>Write code that is obvious, clearly readable by future programmers maintaining the code. Don&#x27;t do clever things that are hard to read and reason about until there is a strong motivating reason to do so.<p>Honestly most of the clever things you&#x27;re about to do, the compiler is already going to do for you, but better and without the bugs you&#x27;ll introduce when you do it wrong.
评论 #32224105 未加载
评论 #32224429 未加载
评论 #32224708 未加载
评论 #32225664 未加载
评论 #32224260 未加载
评论 #32224885 未加载
评论 #32224108 未加载
vascoalmost 3 years ago
Get really good at googling and bias to do it in more situations than you think you need and always earlier than you think you need. If you&#x27;re working remotely do it live in meetings &#x2F; planning as well and use it as an extension of your brain. There&#x27;s no advantage in discussing a problem and only investigating it after you speak to someone if you can do it in parallel right away. If you treat the search engine as an extension of your brain rather than a crutch that means every google is you admiting you don&#x27;t know something, you&#x27;ll reap many rewards.<p>I&#x27;ve definitely gotten way more value of learning to google better and faster than being good at some editor or IDE shortcuts.<p>This also includes getting very familiar with the docs of the tools you use, knowing the ins and outs of them. Something you learn when you study for Red Hat &#x2F; AWS &#x2F; k8s certifications where you can consult docs is that the best way to be efficient during the exam is to be efficient looking at docs. Apply that to everything.
评论 #32224120 未加载
评论 #32224158 未加载
评论 #32224190 未加载
评论 #32225585 未加载
jakevoytkoalmost 3 years ago
Understand the problem and solution before coding.<p>It sounds simple, but it&#x27;s hard to have perfect discipline. Especially if you have a strong bias towards action like I do.<p>It&#x27;s shocking how applicable this is! Don&#x27;t code an algorithm before having a firm grasp of the solution. Don&#x27;t write code in an interview before you&#x27;re sure you&#x27;ve uncovered everything your interviewer wants. Don&#x27;t slam out a UI before understanding how all of the edge cases should act. Unless the point of the code is exploratory, the code should be a foregone conclusion by the time you start.<p>The more you practice this, the more you&#x27;ll uncover bugs and underspecifications before you&#x27;ve spent days going down the wrong path.
评论 #32224220 未加载
评论 #32223987 未加载
评论 #32224386 未加载
评论 #32224101 未加载
评论 #32224106 未加载
评论 #32224117 未加载
评论 #32224649 未加载
评论 #32224803 未加载
substation13almost 3 years ago
Defunctionalisation.<p>Instead of writing code that does what you want to do, have it return a <i>description</i> of what you want to do.<p>Then write an simple executor for such descriptions.<p>Why do this? Well it allows you to manipulate, test, store and inspect the description.
评论 #32224499 未加载
评论 #32225617 未加载
评论 #32224713 未加载
评论 #32224037 未加载
评论 #32224898 未加载
评论 #32224276 未加载
评论 #32224047 未加载
评论 #32227157 未加载
评论 #32224022 未加载
BoppreHalmost 3 years ago
1. The Best Regex Trick[1], where you want to match Tarzan but not &quot;Tarzan&quot;: use the regex &quot;Tarzan&quot;|(Tarzan) and ignore matches where the capturing group is empty.<p>2. When making UI adjustments of color, speed, position, or any other continuous value, find a way to map them to the mouse position (could be a slider, or simply reading the mouse position on a loop). It&#x27;s a lot easier to find the right value when you can make 60 adjustments per second.<p>3. When creating a cache, think hard about what errors are temporary and what errors are permanent. Then make sure the permanent ones are also cached.<p>4. Always include a version number in your output, be it a field in your persisted data structures or your CLI stdout. Greatly helps troubleshooting deployments and the inevitable schema migrations.<p>5. Creating a concise Domain Specific Language to represent your inputs and outputs makes writing tests a breeze. For example, if you&#x27;re writing a calculator, assertResult(FIVE+PLUS+THREE+EQUALS, &quot;8&quot;).<p>6. The more you avoid strings, the more reliable will be your program. Trailing spaces, empty strings, wrong case, homoglyphs, smart quotes, typos, escape characters, ambiguous parsing, CRLF vs LF, tabs vs spaces, legacy encodings, NFC&#x2F;NFD normalization, BIDI... If it was not typed on a keyboard by a human, there&#x27;s probably a better data structure.<p>7. On a more practical note, Bash brace expansion[2]:<p><pre><code> echo word{1,2,3} # word1 word2 word3 cp my_file.txt{,.bkp} # cp my_file.txt my_file.txt.bkp curl https:&#x2F;&#x2F;example.com&#x2F;page&#x2F;{1..100} touch file_{001..100}.txt # Zero-padded! rm {file_a,file_b}{.c,.h} # rm file_a.c file_a.h file_b.c file_b.h </code></pre> [1]: <a href="https:&#x2F;&#x2F;www.rexegg.com&#x2F;regex-best-trick.html" rel="nofollow">https:&#x2F;&#x2F;www.rexegg.com&#x2F;regex-best-trick.html</a><p>[2]: <a href="https:&#x2F;&#x2F;wiki.bash-hackers.org&#x2F;syntax&#x2F;expansion&#x2F;brace" rel="nofollow">https:&#x2F;&#x2F;wiki.bash-hackers.org&#x2F;syntax&#x2F;expansion&#x2F;brace</a>
评论 #32298200 未加载
评论 #32230204 未加载
chriswarboalmost 3 years ago
You could harden a Linux server by killing the init process. That would cause a kernel panic, and prevent new processes running (e.g. shells). Existing processes like Web servers would continue to function, so you could put this at the end of the boot script :)
评论 #32224956 未加载
评论 #32226109 未加载
评论 #32224147 未加载
评论 #32225254 未加载
评论 #32224067 未加载
taneqalmost 3 years ago
Brute force.<p>So very often you see programmers spending days or weeks trying to think up an elegant, efficient way to do something that will never ever make a meaningful contribution to the footprint of their code. It&#x27;s one of those traps that becomes more subtle the more skilled you get, so nobody&#x27;s safe.<p>Try the simple, obvious thing first. Need to store an arbitrary number of something? Stick them in a vector. Need to find something in an array? Loop through the array. Yes, there are exceptions, but by the time you find one you&#x27;ve already saved the time it took to identify and optimize that one case, ten times over, by not wasting time in the other 99% of your project.
next_xibalbaalmost 3 years ago
Fast inverse square root for computer graphics programming! [1] Popularized by leaked Quake III code (attributed to John Carmack), but dates back much further.<p>[1] <a href="https:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;Fast_inverse_square_root" rel="nofollow">https:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;Fast_inverse_square_root</a>
评论 #32224356 未加载
tsujpalmost 3 years ago
When implementing something:<p>Figure out enough to get started. Then start. Don&#x27;t think you can get a perfect view of something before wading into it, you&#x27;ll just be wasting time. Likely your first attempt will suck so with your new found experience from starting and trying you can improve for your next attempt.
评论 #32228933 未加载
评论 #32224463 未加载
评论 #32224042 未加载
iveqyalmost 3 years ago
Change the requirements. Understanding the requirements and adding your domain knowledge, often makes it possible to slightly change the requirements (in agreement with stakeholders) in a way that seriously reduces implementation time.
评论 #32226430 未加载
评论 #32224192 未加载
kiliancsalmost 3 years ago
This might not be exactly what you were asking, but I found it to work well as the means to end with the best possible (given current knowledge) outcome, including considerations such as avoiding code that is too smart, or otherwise justifying and documenting it well.<p>Good commit messages. Why did I do what I did? How does it serve the end goal? What key decisions did I make? What were the trade-offs? What are the alternatives?<p>If I can&#x27;t justify the commit, I can improve—and by doing this exercise, I will know where.<p>Ask reviewers to also review your commit messages. They might find gaps you missed, and it will help them in their code review.
jack_codesalmost 3 years ago
Maybe not a &#x27;trick&#x27; but writing comments before I dive into the code helps me structure my thoughts and then piecemeal the work.
评论 #32224468 未加载
评论 #32224041 未加载
评论 #32223959 未加载
kaesvealmost 3 years ago
A &#x27;trick&#x27; that I&#x27;ve grown fond of is for iterating over a circular list where the current and previous items form an edge, with a special case for the first edge, that is composed of the first and last items of the list (making it circular).<p>The &#x27;normal&#x27; way to write a loop over this is something like:<p>for (let i = 0; i &lt; ls.length; i++) {<p><pre><code> const j = i &gt; 0 ? i - 1 : ls.length - 1; ...</code></pre> }<p>A trick I got from sean barretts website (<a href="https:&#x2F;&#x2F;nothings.org&#x2F;" rel="nofollow">https:&#x2F;&#x2F;nothings.org&#x2F;</a>), is to use the for-loop initialization clause for the special case:<p>for (let i = 0, j = ls.length - 1; i &lt; ls.length; j = i++) {<p><pre><code> ... </code></pre> }<p>The work I do usually does not care about the performance improvement if there is any, but it feels good to avoid that per-iteration check.
评论 #32225716 未加载
gwbas1calmost 3 years ago
Write simple, clear code. Make sure it&#x27;s readable. If you come back to something a few days later and you think it&#x27;s hard to understand, add a comment.<p>Be as consistent as possible with your styles and naming conventions. A large project is significantly easier to read when every class, method, ect, follows very similar style guidelines.<p>Make sure that you don&#x27;t need to &quot;think&quot; when reading code. (IE, you shouldn&#x27;t have to page up and down to remember what type a variable is.) Often this is solved by including type in a variable name, and using some kind of convention to determine scope. (For example, always use &quot;this.&quot; so you can tell that a field is a field instead of a locally-scoped variable.)<p>Try to follow a consistent pattern for line breaks, especially for when a line gets over ~120 characters.<p>IDEs that let you view code side-by-side on a wide monitor are very useful.<p>Invest in a giant monitor. I use a 50&quot; 4k TV that I picked up on sale.<p>Edit: Always be skeptical of frameworks and 3rd party libraries. Put a lot of time into evaluating them, and choose wisely. It&#x27;s always significantly more work to remote &#x2F; replace a bad 3rd party framework &#x2F; library than the time you put into choosing it.<p>Sometimes &quot;no framework&quot; is easier than a framework. Only writing a few queries? Consider skipping a complicated ORM. A clear startup sequence that builds a shared data structure of long-lived objects might, in the long term, be easier to debug than a complicated dependency injection framework.<p>Sometimes &quot;no framework&quot; is easier to learn than a complicated framework. Newcomers to your team may appreciate that it&#x27;s easier to read 1000 lines of simple code instead of needing to spend days understanding a 3rd party framework.<p>Edit2: Don&#x27;t underestimate the power of unit tests and automated tests; especially for long-lived industrial-strength software. Take the time to learn how to write good unit tests that you can quickly run in both your development environment and in CI. (Continuous integration)
评论 #32226372 未加载
chriswarboalmost 3 years ago
When interacting with a system, e.g. to test it, or reproduce an error, etc. I try to build up a &#x27;self-contained&#x27; command, rather than relying on state. For example, in a REPL we can usually press UP to get a copy of the previous command, which we can then tweak (I&#x27;ve added &#x2F;&#x2F; comments to explain the though process; I wouldn&#x27;t actually write them down!)<p><pre><code> &#x2F;&#x2F; Make sure we can load our dependencies, etc. &gt; import foo Imported foo.bar, foo.baz, foo.theProblematicFunction &#x2F;&#x2F; Great, now let&#x27;s try calling the problematic code &gt; import foo; foo.theProblematicFunction() Type Error: foo.theProblematicFunction requires an argument of type User &#x2F;&#x2F; Hmm, it needs some arguments; let&#x27;s keep plugging things in until it runs &gt; import foo; foo.theProblematicFunction(User()) Type Error: User require arguments of type (Name, Email) &gt; import foo; foo.theProblematicFunction(User(Name(&quot;Alice&quot;), Email(&quot;alice&quot;))) Type Error: Email requires username and host parts &gt; import foo; foo.theProblematicFunction(User(Name(&quot;Alice&quot;), Email(&quot;alice&quot;, &quot;example.com&quot;))) LOG.INFO: Sent welcome email to alice@example.com &#x2F;&#x2F; Great, we can run the code. Now let&#x27;s try reproducing the error. Maybe it was spaces in the Name? &gt; import foo; foo.theProblematicFunction(User(Name(&quot;Alice Doe&quot;), Email(&quot;alice&quot;, &quot;example.com&quot;))) LOG.INFO: Sent welcome email to alice@example.com &#x2F;&#x2F; Nope that works. Maybe it was the lack of a top-level domain? &gt; import foo; foo.theProblematicFunction(User(Name(&quot;Alice&quot;), Email(&quot;alice&quot;, &quot;localhost&quot;))) Uncaught InvalidInputException: Email domain must contain a dot &#x2F;&#x2F; Aha, we&#x27;ve found the problem! </code></pre> We now have a single line `import foo; ... &quot;localhost&quot;)))` which reproduces what we&#x27;re after. We can put that in a test suite to make a regression test; or email it to a colleague for their opinion; or file a bug in an upstream library; etc. This would be trickier we had done separate lines like `import foo`, `let name = Name(&quot;alice&quot;)`, etc.
msluyteralmost 3 years ago
One that a professor of mine used when I was in grad school which I don&#x27;t see that often these days is the use of sentinel values. For arrays&#x2F;lists of unknown sizes, it&#x27;s sometimes nice to do something like:<p><pre><code> while val != SENTINEL: # ...stuff... val = some_iterator() </code></pre> You just have to be careful that you can never have real data equal the sentinel.<p>A variation on this can be used to stop queue processing in a multi-threaded&#x2F;processing environment. You can put N sentinels (aka, poison) in the queue for N readers, and when a reader gets the poison, it quits.
评论 #32224862 未加载
评论 #32227120 未加载
d--balmost 3 years ago
Replacing arrays of structures with structures of arrays.<p><a href="https:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;AoS_and_SoA" rel="nofollow">https:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;AoS_and_SoA</a>
yellowstuffalmost 3 years ago
Eric Lippert taught me that if you see a bug in some tricky code, rewrite the code with a simpler approach, rather than put in a fix which will make the code even trickier and quite possibly create new bugs.<p>More specifically, if you have a bunch of bugs related to storing data in an inconvenient way, convert the data to a simpler format rather than write a bunch of complex logic around the bad data format.<p>Article here: <a href="https:&#x2F;&#x2F;docs.microsoft.com&#x2F;en-us&#x2F;archive&#x2F;blogs&#x2F;ericlippert&#x2F;bug-psychology" rel="nofollow">https:&#x2F;&#x2F;docs.microsoft.com&#x2F;en-us&#x2F;archive&#x2F;blogs&#x2F;ericlippert&#x2F;b...</a><p>As a tangent, this article took me ages to find, even though I remembered the author, most of the details, and the string &quot;SensibleDate&quot;. I&#x27;m not sure if the lesson is that MS is at fault for moving old content and having a lousy internal search tool, or Google is getting worse because it couldn&#x27;t find it anyway, or I&#x27;ve gotten worse at finding stuff. But a few years ago I would&#x27;ve been shocked to not quickly find an article where I remembered a few relevant details, and now it seems like the norm.
chriswarboalmost 3 years ago
Using cryptographic hashes for &quot;deterministic randomness&quot;, i.e. values which are reproducible, but unpredictable beforehand.<p>I&#x27;ve used this for benchmarking, seeding pseudorandom number generators with the SHA256 of the project&#x27;s source code. That way, anyone can reproduce the benchmark, but it&#x27;s hard to &quot;cheat&quot; since tweaking the code (e.g. to favour the current benchmark) will alter the benchmark in an unpredictable way!
评论 #32225607 未加载
qweryalmost 3 years ago
I suppose I might try being the grump that says the best trick is to not do any tricks. As in <i>don&#x27;t be cute</i>[a], I guess.<p>There was a series[b] of &#x27;Dirty Coding Tricks&#x27;[0], originally posted on Gamasutra from 2009. I remember getting something out of them at&#x2F;around the time, maybe you&#x27;ll find something of interest. I think most were more like &quot;hacks I can&#x27;t believe we shipped&quot; rather than tricks, but you did mention dirty hacks, so...<p>* [a] Is &quot;don&#x27;t be cute&quot; not a thing? -- I&#x27;m struggling to find usages&#x2F;source of the phrase right now<p>* [b] Well, I remember a series of them but I could be wrong. To find out either way would require navigating the hellscape that is informa&#x27;s gamedeveloper magazine&#x27;s website&#x27;s repackaged Gamasutra content which happens to be unavailable due to &quot;navigating some downtime on our legacy web pages&quot;.<p>* [0] <a href="https:&#x2F;&#x2F;web.archive.org&#x2F;web&#x2F;20220707000222&#x2F;https:&#x2F;&#x2F;www.gamedeveloper.com&#x2F;programming&#x2F;dirty-coding-tricks" rel="nofollow">https:&#x2F;&#x2F;web.archive.org&#x2F;web&#x2F;20220707000222&#x2F;https:&#x2F;&#x2F;www.gamed...</a>
carapacealmost 3 years ago
It&#x27;s not necessarily something you&#x27;d use today(?), but Duff&#x27;s Device has always struck me as particularly beautiful:<p><pre><code> send(to, from, count) register short *to, *from; register count; { register n = (count + 7) &#x2F; 8; switch (count % 8) { case 0: do { *to = *from++; case 7: *to = *from++; case 6: *to = *from++; case 5: *to = *from++; case 4: *to = *from++; case 3: *to = *from++; case 2: *to = *from++; case 1: *to = *from++; } while (--n &gt; 0); } } </code></pre> &gt; In the C programming language, Duff&#x27;s device is a way of manually implementing loop unrolling by interleaving two syntactic constructs of C: the do-while loop and a switch statement. Its discovery is credited to Tom Duff in November 1983, when Duff was working for Lucasfilm and used it to speed up a real-time animation program.<p><a href="https:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;Duff%27s_device" rel="nofollow">https:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;Duff%27s_device</a>
vivegialmost 3 years ago
Around 25 years ago, I was part of a team that was building a client-server workflow system in C++. We had sharded SQL databases and an object server that managed the ORM for each shard and a queue server that kept a prefetched list of objects for each queue. A central broker handled client applications and communicated with the queue server and the object server and also handled transaction management. Since this was a workflow, objects moved from queue to queue as defined in the buisness process and were acted upon by applications (could be an automated step or user-driven).<p>One of the main techniques we used was a memory manager (using overloaded new&#x2F;delete operators) and data serialization such that we could build the prefetched set of objects in a memory manager (at the object server) and persist it to disk on a central file server. The client could just load that file into memory and directly access the objects without any parsing. We had a whole object API to encapsulate this. When the client was done with processing, it would just flush the memory to disk (on the network file server) and send a message the broker and the broker&#x2F;objectserver&#x2F;queueserver handle the write lazily.<p>Also, if the system crashed, we had a tool to rebuild the object server state and queue server state from the SQL databases, so there was some recovery&#x2F;resiliency built in.<p>Granted, the operating environment of the client and server was controlled by us and this architectural choice made sense. But, the main thing that surprised me was the performance gained by the client apps not having to parse out the objects due to the use of the memory manager and the reduction of application latency (for users) due to the interleaving of prefetch and lazywrites. This was by no means a simple trick, but certainly very clever.
sebastianconcptalmost 3 years ago
That structure is <i>infinitely</i> more important than algorithms for the great majority of the cases you have to deal with when building a product.<p>Being jealous of keeping good Separation of Concerns comes to mind strongly regarding to this.
dirkcalmost 3 years ago
ZeroMQ [1] - it&#x27;s sockets on steroids.<p>I&#x27;ve used it to do distributed load testing using a small javascript program, a script written in python to cache aggregated results for a big database and as a transport for high performance messaging in a c++ framework.<p>Being able to do distributed computing without having to rely on a single framework or setting up lots of additional infrastructure is really useful!
chriswarboalmost 3 years ago
I use property-based testing a lot:<p>- We write our unit tests as <i>functions</i>, accepting some arguments<p>- Our assertions should hold <i>for all possible values</i> of those arguments (this works better with a rich type system!)<p>- The test framework generates a bunch of random values, to check if our test functions ever fail<p>This on its own is a great way to find edge-cases, and expose hidden assumptions.<p>One of the most hacky things I&#x27;ve done with it is to regression-test interactions between dynamic binding and futures. My test suite defined a small language, containing strings, concatenation, dynamic variables and futures (deferring and awaiting). I wrote a straightforward, single-threaded implementation which just computed deferred values immediately; and I wrote a concurrent implementation using actual dynamic binding and futures. My property-tests would generate random expressions in this language, and check that both interpreters give the same result.
dgb23almost 3 years ago
If you are interested in these kinds of things I can recommend the book &quot;Hacker&#x27;s Delight&quot;.
评论 #32224422 未加载
notacowardalmost 3 years ago
One of my favorite tricks (from CPU designers I worked with) was to &quot;poison&quot; requests or pieces of data and pass them on, instead of trying to return them immediately after an error. At first it seems like it&#x27;s just wasting cycles, but often &quot;turning around&quot; the control flow at a particular point can require all sorts of code contortions especially when locking is involved. Letting things flow to a point where it&#x27;s easier to turn around - like turning around in a parking lot instead of in the middle of the street - has drastically simplified error handling in several codebases I&#x27;ve worked on. It&#x27;s like soft deletes, but for data in flight instead of data at rest.
oxffalmost 3 years ago
Writing functions that return side effects as a message instead of running them within the function must be one of the most underrated things.
评论 #32224057 未加载
评论 #32226750 未加载
评论 #32224079 未加载
recursivedoubtsalmost 3 years ago
As far as &quot;tricks&quot; go, my favorites are:<p>* Recursive descent parsing, see <a href="https:&#x2F;&#x2F;craftinginterpreters.com&#x2F;" rel="nofollow">https:&#x2F;&#x2F;craftinginterpreters.com&#x2F;</a> for a great introduction<p>* ConcurrentHashMap#computeIfAbsent() for a thread safe caching mechanism: <a href="https:&#x2F;&#x2F;www.geeksforgeeks.org&#x2F;concurrenthashmap-computeifabsent-method-in-java-with-examples&#x2F;" rel="nofollow">https:&#x2F;&#x2F;www.geeksforgeeks.org&#x2F;concurrenthashmap-computeifabs...</a><p>* Using Hypermedia As The Engine of Application State (<a href="https:&#x2F;&#x2F;htmx.org&#x2F;essays&#x2F;hateoas&#x2F;" rel="nofollow">https:&#x2F;&#x2F;htmx.org&#x2F;essays&#x2F;hateoas&#x2F;</a> :)
zerralmost 3 years ago
In C++ you can access a private member of a class A by defining a class B as exactly the same but making that member public, and casting to B*: B* b = (B*)&amp;a; b-&gt;private_member... Shouldn&#x27;t be used more than once in every 20 years though :)
评论 #32224728 未加载
throwaway81523almost 3 years ago
HAKMEM <a href="http:&#x2F;&#x2F;w3.pppl.gov&#x2F;~hammett&#x2F;work&#x2F;2009&#x2F;AIM-239-ocr.pdf" rel="nofollow">http:&#x2F;&#x2F;w3.pppl.gov&#x2F;~hammett&#x2F;work&#x2F;2009&#x2F;AIM-239-ocr.pdf</a>
Etherytealmost 3 years ago
Being proficient and fluent in your language and tooling of choice is a superpower. What are the guarantees you get with different kinds of async behavior, how are null or maybe values handled and passed around, what are the default values of things and why. Not just knowing, but understanding questions like these will allow you to write code that is robust and has fewer unexpected side effects. In short, the trick is putting in the hours and hard work. Or, to quote MtG: &quot;There is no shortcut to work done true and well.&quot;
dahartalmost 3 years ago
For performance optimizing, learning first how to do less work &amp; delete code, second how to avoid memory accesses, and third how to use cache friendly accesses, are pretty broadly useful.<p>One bit-twiddling trick I used successfully on a GPU recently that was quite satisfying: I needed to gather some data to process, and it was a different amount of data for each thread. GPUs are SIMD, so process multiple threads with the same instruction and it’s bad if one thread does different work than it’s neighbor. I first tried sorting the data to make sure the work was coherent and to minimize the number of divergent threads - threads working on data while other threads are idle or doing something else. Then I learned how to use an FFS (find first set) instruction to avoid the sort but achieve exactly the same behavior. Setup a bitmask to mark active data, each thread then uses FFS to find the index of a datum to process, clears the bit and processes one item, repeat until the bitmask is zeroed. Much better than sorting, and uses fewer memory accesses, win!<p>Also you might be surprised to learn that the XOR trick for swapping variables is rarely if ever faster than plain old assignment on modern architectures. This is one bit-twiddling trick that you could probably unlearn and never need. It’s cute and fun to know, might be useful in an interview once in a while, but I’ve never seen it unused in production even though I have seen it discussed many times.
评论 #32224636 未加载
vcarricoalmost 3 years ago
If you&#x27;re not doing TDD, write the name of the tests before coding. Why?<p>* It helps you to understand the problem and the solution;<p>* I tend to write more test scenarios and cover more cases when I don&#x27;t need to write the tests right away. I write the names, the actual test it&#x27;s a problem for my future me;<p>* You don&#x27;t have to think and remember of all the scenarios after writing the code, just do what the name says.<p>* No one actually does TDD lol - jokes a part, TDD might be annoying in some complex cases IMO.
JohnDeHopealmost 3 years ago
The command design pattern never ceases to amaze me. Package up a complicated process in an &quot;input, process, output&quot; package. Turn it into a black box. The input should be as small as possible, just the details and data you need to &quot;do the needful&quot;. The output should be as little as possible to explain how things went. I usually let my code grow organically, but once it gets to a certain point, using this technique really helps clean things up.
评论 #32224133 未加载
lcordieralmost 3 years ago
A Python &quot;trick&quot; I like which is a compact one-liner if-statement.<p><pre><code> var = (False, True)[predicate] </code></pre> This is equivalent to:<p><pre><code> var = True if predicate else False </code></pre> Since we are doing item getting, we can do CASE statements.<p><pre><code> var = (case0, case1, case2)[item] </code></pre> Which is equivalent to:<p><pre><code> if item == 0: var = case0 elif item == 1: var = case1 elif item == 2: var = case2</code></pre>
ajbalmost 3 years ago
All-pairs testing.<p>Lets say you&#x27;ve got a complicated piece of code that has a bunch of options (either input or configuration, doesn&#x27;t matter). You can&#x27;t test it exhaustively because that&#x27;s exponential in the number of options. But you can test all combinations of each pair of options, in ~O(A x B) where A and B are two largest option cardinalities.<p>To be concrete about this, suppose there are 10 option variables each having at most 5 possible values, a,b,c,d,e,f,g,h,i,j. Suppose that d and e are have the largest cardinality (5). So you can test all pairs of assignments to d and e in 25 tests. But with the same 25 tests (or epsilon extra ones) you can test all pairs of assignments to <i>every pair of variables</i> - you need hardly any more tests.<p>Of course, coming up with the table of values is a bit tricky, especially if there are some constraints. But there are libraries to do it.<p>Takeaway: with a very small number of tests you can find corner cases that are very hard to locate with a standard approach.<p>This generalises to triples, etc.<p>(see <a href="https:&#x2F;&#x2F;burtleburtle.net&#x2F;bob&#x2F;math&#x2F;jenny.html" rel="nofollow">https:&#x2F;&#x2F;burtleburtle.net&#x2F;bob&#x2F;math&#x2F;jenny.html</a>)
oxffalmost 3 years ago
Not strictly a programming trick, but when something breaks I do this mentally:<p>1. Don&#x27;t change anything.<p>2. Ask myself what do I know.<p>3. Ask myself why do I think I know (2).<p>4. Ask myself what to do next.<p>The step 3 is really the big one.
XCSmealmost 3 years ago
I like code-golf challenges. To write shorter code, you have to first find an algorithm that&#x27;s short to write and also know all the ways you can re-write existing statements to make them shorter (which are often language-specific). This forces you to learn operator priorities (when you can avoid parentheses), what are default variable values, short-circuited statements, when you can re-use the same variable or ways to use built-in functions for things other than they were built for, etc.<p>Some code-golf tricks examples, for JavaScript: <a href="https:&#x2F;&#x2F;www.geeksforgeeks.org&#x2F;code-golfing-in-javascript&#x2F;" rel="nofollow">https:&#x2F;&#x2F;www.geeksforgeeks.org&#x2F;code-golfing-in-javascript&#x2F;</a><p>A few examples, if you skip the link:<p><pre><code> &#x2F;&#x2F; Check if variable is upper case &#x27;g&#x27; &lt; {} &#x2F;&#x2F; Returns false, lower case &#x27;G&#x27; &lt; {} &#x2F;&#x2F; Returns true, upper case</code></pre> If you were to use a &#x27;g&#x27; &lt; &#x27;a&#x27; you would need an extra character.<p><pre><code> &#x2F;&#x2F; Ceil a = Math.ceil(a); a = a%1 ? -~a : a;</code></pre>
OrangeMonkeyalmost 3 years ago
Best programming trick I know - when I don&#x27;t know something, I ask for help.
msluyteralmost 3 years ago
Not sure if this counts as a &quot;programming trick&quot;, but for maneuvering around the shell: learning readline.<p><a href="https:&#x2F;&#x2F;readline.kablamo.org&#x2F;emacs.html" rel="nofollow">https:&#x2F;&#x2F;readline.kablamo.org&#x2F;emacs.html</a><p>^This one cool trick will increase your productivity by 1000%!<p>I&#x27;ve had sr. engineers see me using ctrl-r and go &quot;woah, how did you do that?&quot;
评论 #32224140 未加载
评论 #32224122 未加载
评论 #32247457 未加载
BrainVirusalmost 3 years ago
Treating DOM as the state of my JavaScript code instead of storing state separately and then synchronizing.<p>Using HTML instead of parsing Markdown by applying white-space: pre-line with some additional styling for semantic tags.<p>Styling style and script tags as visible to embed examples into HTML pages without duplicating or entity-encoding them.<p>Using files as a key-value store. (File name = key. File content = value.)<p>Using folders&#x2F;files as a one-to-many messaging bus. E.g. one app creates empty do-something.txt file in a folder, couple other apps monitors the folder and do stuff. Very simple setup, but allows to create multiagent systems in different languages <i>with persistence</i> and easy way to debug&#x2F;interact with the whole thing manually.<p>Using inheritance instead of mocking frameworks. (Instead of mocking something out, extend the class, override &quot;mocked&quot; behavior and test that class.)
craniumalmost 3 years ago
I like to implement features from end-to-end and keep them as lean as possible so I can fit the execution flow in my head. Each time an edge case or a question pops up, I leave a TODO in the code explaining why it could be a problem but I don&#x27;t solve it yet. Then I proceed to implement the next call in the stack. Once the happy path is done and tested, I go back the TODOs.<p>I also like to implement the feature top-down: starting with the caller and implementing the chain of callee. It helps designing the abstraction layers by forcing you to answer &quot;does the caller care&#x2F;know about this argument or should it abstracted away elsewhere (config or service)?&quot; By starting from the top, you tend to add arguments only if they are needed.
asicspalmost 3 years ago
Here&#x27;s a trick I wrote with `GNU grep`:<p><pre><code> grep --group-separator= -A0 &#x27;.&#x27; </code></pre> The above command is equivalent to the below `awk` command (including removal of empty lines at start&#x2F;end of input):<p><pre><code> awk -v RS= &#x27;{print s $0; s=&quot;\n&quot;}&#x27; </code></pre> Both the above solutions can be changed to a different group separator instead of single empty.<p>You can also just use `cat -s` if you don&#x27;t need a custom group separator and don&#x27;t care about start&#x2F;end empty lines.<p><pre><code> $ printf &#x27;\n\n\ndragon\n\n\n\n\nunicorn\n\n\n&#x27; | cat -s dragon unicorn $ printf &#x27;\n\n\ndragon\n\n\n\n\nunicorn\n\n\n&#x27; | awk -v RS= &#x27;{print s $0; s=&quot;\n&quot;}&#x27; dragon unicorn</code></pre>
lynndotpyalmost 3 years ago
Test-driven development. You write the unit tests <i>before</i> the code, then you write code until tests stop failing.<p>It makes writing code so much faster it&#x27;s not even funny, and with much less mental strain. Debugging sucks but testing rocks. You basically always save time.
评论 #32247595 未加载
gonzo41almost 3 years ago
Try and talk to your users directly and if you&#x27;re attempting to improve their workflow, try and watch their existing workflow and ask them questions about why they do things as they are now. Also use lists and hash-maps first, be wary of exotic features.
kbranniganalmost 3 years ago
When building UIs, I fill the UI with TODO bullet points. This screen will have textbox, when I press enter it will store the input.<p>Next version: This textbox should display properly on mobile. Then I fix it.<p>So my UI is always telling me what to work on next
badrabbitalmost 3 years ago
For C, use seccomp and write simple and readable code and hope the compiler optimizes instead of complicated and hard to audit code, I don&#x27;t mean commenting and variable&#x2F;function names but the actual control flow, data structures and algorithms. Eliminate complexity unless you absolutley have no choice. And the power 10 rules from JPL which i think can apply to other languages as well.<p><a href="https:&#x2F;&#x2F;en.m.wikipedia.org&#x2F;wiki&#x2F;The_Power_of_10:_Rules_for_Developing_Safety-Critical_Code" rel="nofollow">https:&#x2F;&#x2F;en.m.wikipedia.org&#x2F;wiki&#x2F;The_Power_of_10:_Rules_for_D...</a>
nanumbatalmost 3 years ago
Track down a syntax-aware code search&#x2F;database tool (if your IDE doesn&#x27;t have one). For me it was&#x2F;is GNU ID Utils. At some point you&#x27;ll be handed thousands or millions of lines of someone else&#x27;s code, and you will need to find things quickly and completely.<p>Also, turn on all compiler warning flags all the time. Some compiler warnings aren&#x27;t triggered unless optimization is enabled, so turn that on every now and then during development and see if any warnings pop. If you&#x27;re handed thousands of lines of someone else&#x27;s code and it&#x27;s riddled with warnings, fix them first.
评论 #32226041 未加载
YeGoblynQueennealmost 3 years ago
The simplest trick that every programmer learns early: when parenthesising, write both parentheses first: (), {}, [], etc. Then fill them in.<p>Even with modern IDEs this one neat trick saves a ton of annoyned confusion and swearing.
评论 #32224332 未加载
brad0almost 3 years ago
Someone here said don’t name your variables x, or a, etc.<p>I argue that you do name them ambiguously to start.<p>Normally when you’re writing code you’re thinking about the right hand side of the statement. What is the next step in my code? But most of the time we write the left hand side first. If you’re focused on naming, you lose your flow. You’re switching contexts.<p>By choosing x or a as your variable name, it unblocks your flow to write the right hand side.<p>Once you’ve written the code, go through and rename your variables. Use your IDE refactoring features to make this easy and change it everywhere at once.
robalnialmost 3 years ago
This is a trick that makes the experience of writing C and C++ code much better: Skip the header files and include the .c or .cpp files into one translation unit instead.<p>* No more code duplication every time you change the type or name of a function.<p>* Fewer files and less code.<p>* Tab completion works better for the file names (you don&#x27;t have two files that start with the same name)<p>* Only one place to put the comment if you want to document the function (otherwise the comments are easy to miss if there is a description in the header file but I&#x27;m looking at the definition).<p>* The code usually compiles faster.
fallingmeatalmost 3 years ago
(1) Model checking first (using a tool most appropriate for the domain): UPPAAL, SPIN, NuSMV, Z3, TLA+<p>(2) Model based design (less time spent on less value-added concerns...plus, capturing even more benefit from (1))
azebazenestoralmost 3 years ago
- Use cs.github.com for code search when you need to find usage ( other than sample) for a library<p>- If you need to choose a tool to do something. After you find one, don&#x27;t just use it: search for alternatives using: * crowded based developer alternatives sites like like alternativeto.net, stackshare.io * crowded based buisness alternatives sites like like g2.com, producthunt * Github topics based alternatives sites like libhunt.com, openbase.com, quine.sh
brad0almost 3 years ago
Something I rarely see anyone do is use the Refactoring features in their IDE.<p>Most IDEs understand the AST of the code you’re working with. Knowing the AST allows it to restructure that tree, based on some simple commands.<p>One command is rename. You can rename variables, functions, classes, files, you name it. Your IDE should update all your code automatically.<p>Extract and Inline are two other useful commands.<p>Learn the keyboard shortcuts and you’ll feel like a wizard. It’s honestly close to magic.
评论 #32226244 未加载
waffles2021almost 3 years ago
Learn your development environment (IDE, or text editor). It may contain features that will make your life easier, both during development and during debugging.
chriswarboalmost 3 years ago
If some tricky manual process can&#x27;t be automated, we can still write a script for it: just have it show prompts, like &#x27;Toggle the widget, then press ENTER to continue&#x27;.<p>This way, we have a form of &#x27;interactive documentation&#x27; telling what to do. We can even put branching (e.g. &#x27;Did you get an 404 error? y&#x2F;N&#x27;), and automate some of the in-between steps to make things less tedious.
Chris_Newtonalmost 3 years ago
If you work with numerical algorithms, understanding the architecture you’re running on can make a huge difference to performance.<p>I once saw a colleague achieve something like a 30% speed-up just by swapping the inner and outer loops in an algorithm that worked on largish 2D arrays (matrices), just because the new nesting better matched the memory layout of the array and so made the hardware caches more effective.
eschneideralmost 3 years ago
Take notes of what you&#x27;ve tried&#x2F;what your results were when debugging. Simple, but massively effective for eliminating duplicate work.
评论 #32224200 未加载
ajosepsalmost 3 years ago
Not really clever, but having a tight iteration loop for whatever you&#x27;re working on. This can look like creating custom scripts to automate commands you would need to input each time you iterate on something, or setting up an environment or UI to help with the development process. It can be a pain to put in the upfront work but it tends to pay in dividends down the line.
TrianguloYalmost 3 years ago
I remember being very confused when I saw !!x on a C source code. It&#x27;s a shorthand for (x != 0 ? 1:0), to return error codes.<p>And then almost everything from JavaScript. Including<p><pre><code> function setPos(horizontal,value){ this.position.edit()[&quot;set&quot;+(horizontal?&quot;X&quot;:&quot;Y&quot;)](value).commit(); }</code></pre>
sidcoolalmost 3 years ago
Most of the programming tasks do not need optimization for time or memory. Instead optimize for readability of code.<p>Also, write tests.
mbaumanalmost 3 years ago
If you&#x27;re having trouble naming something, don&#x27;t just name it `x` or `a` if this is something you&#x27;re going to have to maintain. Instead, it&#x27;s a red flag that your abstractions are wrong. It&#x27;s often worth taking some time to figure out if there&#x27;s a better structure.
评论 #32227015 未加载
rovr138almost 3 years ago
Not exactly a programming trick, but adjacent enough.<p>Learn your tools. Learn the features of your IDE. Learn the flags and know and understand what your makefile or runner is doing.<p>So many times I&#x27;ve asked people that and they absolutely have no idea except, &#x27;I run make&#x27; or &#x27;I run grunt&#x2F;gulp&#x27;
Xophmeisteralmost 3 years ago
The XOR swap trick is just a trick; it shouldn&#x27;t be used in practice. Modern architectures can do a register swap almost for free, compared to three XORs. The biggest problem is when your two values are equal: they&#x27;ll get zeroed out and good luck tracking that down!
评论 #32224350 未加载
评论 #32226798 未加载
评论 #32225398 未加载
waffles2021almost 3 years ago
Don&#x27;t optimise until it works.
waffles2021almost 3 years ago
If working in a team, create a policy document that everyone signs off on. Don&#x27;t sacrifice quality for speed when it comes to policy. This ensures that code is transferable between team members without too much noise.
podgorniyalmost 3 years ago
Work out solution from the end result. Imageine how end result should be (library API, UI components and interaction) and figure out how reduce it to building blocks you have (framework entities, text, functions-data, etc)
akfaewalmost 3 years ago
Writers say that the secret to writing is rewriting.<p>The same is true for programming.
apricot13almost 3 years ago
Set an alias for `git push` for `git pish` not strictly programming though!<p>Along the same lines I still use a text expander shortcut for for loops!
vortalguantalmost 3 years ago
Have a variable named &#x27;toreturn&#x27;.
sambalbadjakalmost 3 years ago
if you use Jira&#x2F;bitbucket, you can prefix the branche names and git commit messages with the Jira ticket number. This way git blame can quickly give you the the context of the ticket.
mywacadayalmost 3 years ago
Get someone else to do it or do it yourself, pick as appropriate.
joshxyzalmost 3 years ago
generics in typescript<p>seriously, generics in typescript is godsent.<p>it&#x27;s great to be able to code in javascript while having a very supportive vscode intellisense
评论 #32224193 未加载
joshxyzalmost 3 years ago
use of linters is godsent too, eslint for javascript fixes a lot of compile time problems which avoids runtime problems
krembananalmost 3 years ago
console.log({ variable }) when debugging
latchkeyalmost 3 years ago
Write tests.
dublinalmost 3 years ago
One word: awk.
estevaoamalmost 3 years ago
Not a technical trick but this helps immensely when designing an application: always start with good problem decomposition and draft the technical components and their interfaces derived directly from that.<p>What I realized over my career is that almost always the software architecture quality just follows how well the problem was decomposed initially. If that decomposing processing is done well, getting to good technical and visual interfaces for the application is a straightforward process.<p>Let me give a practical example of good decomposition and translation to technical interface.<p>Let&#x27;s say you want to develop an application to manage a parking lot. Start by listing what happens in the parking lot, thinking in a story format (user stories are not a coincidence):<p>- A car enters, the machine generates a code and prints into a ticket, the driver picks the ticket up<p>- Then the driver searches a suitable spot and parks the car<p>- Afterwards, the driver inserts the ticket in a machine that reads the code, calculates the price and ask for payment<p>- The driver pays, the machine returns the ticket and the driver proceed to exit<p>- At the exit, the driver inserts the ticket on another machine which validates if it was paid before opening the boom pole<p>Now, let&#x27;s draft the components and their interface for that. Tip: the best names are already contained on that story. We need to: 1. Generate ticket code 2. Calculate price for ticket 3. Request ticket payment 4. Validate ticket<p>We can easily translate those to something similar to this:<p>TicketManager.generateTicket() =&gt; ticketCode<p>TicketManager.calculateTicketPrice(ticketCode) =&gt; float<p>TicketManager.requestTicketPayment(ticketCode) =&gt; (integration with the machine)<p>TicketManager.validateTicket(ticketCode) =&gt; boolean<p>Here is a good start point, you can decide to put those methods and their implementation into specific components depending on how complex those are. Yes, everything is included in that `TicketManager` but this is already a nice draft which can be improved upon.<p>My point here is that it is that simple. I use this approach both for boring simple and extremely complex use cases and it works wonderfully to keep things simple and connected with the domain. Just use the language that describes what is wanted from the automation, and use that in the final implementation directly.<p>There are multiple edge cases and scenarios to deal with within a problem domain, but the skeleton of your program is there and unless the concept of the problem changes, those won&#x27;t go away soon.<p>This might sound obvious and dumb for some people but I stopped counting how many meetings I participated where people spoke in natural language what the program must do and in the very next moment that is lost completely by someone trying to translate to code using other terms and structure.<p>Our language already gives us what we want: verbs and nouns describe actions, capabilities we want to automate with the help of a computer program. Those same verbs and nouns should become function names within the software.<p>It is that simple, people overcomplicate things too much.<p>P.S.: Can&#x27;t say for sure if this works nicely for other types of domains (scientific, research), but I would assume that it does. We humans create concepts using our natural language all the time. Writing software that represents those concepts is what programming is all about.