Tag Info

Hot answers tagged

68

Yes, your colleague is right: that is bad code. If an error can be handled locally, then it should be handled immediately. An exception should not be thrown and then handled immediately. This is much cleaner then your version (the getValueByKey() method is removed) : public String getByKey(String key) { if (valuesFromDatabase.containsKey(key)) { ...


46

Practice. No, really. You will never fully appreciate a technique in a book or blog post until you've written your first plate of spaghetti or big ball of mud, and realize that many of these techniques are just effective ways to tame that complexity. Then you will understand them at a deeper level, much deeper than the cargo cultist who is just ...


21

My one surefire way is: Not being afraid to refactor the plan at the first hint that the code is turning complex. (Which, of course, does not negate at all what you have already mentioned about being more thorough and dedicated in the planning stage.)


19

There are indeed techniques for gradually simplifying code and improving design by doing so. The general technique is known as "refactoring". Note that this term is used both informally (to mean "anything that changes how code is designed without changing what it does") and formally (to mean "following a specific refactoring discipline"). I am referring to ...


11

I wouldn't call this use of Exceptions an anti-pattern, just not the best solution to the problem of communicating a complex result. The best solution (assuming you're still on Java 7) would be to use Guava's Optional; I disagree that it's use in this case would be hackish. It seems to me, based on Guava's extended explanation of Optional, that this is a ...


11

It's called a cache, the technique is called caching. A cache is something that stores data in order to speed up further requests for that same data. That data may be the result of some expensive computation and thus be cached to avoid repeating that costly computation. It might also be a copy of some data that is already pre-computed elsewhere but is ...


10

A "raw" pointer is unmanaged. That is, the following line: SomeKindOfObject *someKindOfObject = new SomeKindOfObject(); ... will leak memory if an accompanying delete is not executed at the proper time. auto_ptr In order to minimize these cases, std::auto_ptr<> was introduced. Due to the limitations of C++ prior to the 2011 standard, however, it's ...


9

Daisy chain when it is clear to the next developer why you did it that way. "Code is read more often than it is written." -Guido von Rossum, PEP 008 There is no one answer to this, but I can give you a good rule of thumb: If the name of the function implies that its job is to do one function and call another, then it is safe to chain them. There are ...


8

The easiest way is to get yourself a mentor who writes clean code, show him or her your messy code, and ask what's wrong with it. The thing to realize is clean code doesn't happen at the planning stage, and you can't continually "adhere" to clean coding principles. You can only periodically reset to them. You will write messy code. As soon as you ...


7

Post your code to Code Review, and let someone else simplify it for you. ☺ In seriousness, if you study the simplifications recommended among the thousands of Code Review answers, you'll find that the range of techniques is far too broad to summarize in an answer. Just off the top of my head, I can think of: Don't reinvent the wheel. Don't write code ...


7

Since there's no performance considerations and it's an implementation detail, it ultimately doesn't matter which solution you choose. But I have to agree it's bad style; the key being absent is something that you know will happen, and you don't even handle it more than one call up the stack, which is where exceptions are most useful. The tuple approach is ...


7

One should never allow work to affect your personal life or relationship. If you start feeling like this is the case, something drastic needs to change with either where you work or how you do your work. You need to focus on managing your time & estimating deadlines more accurately. Next time, consider requesting to do a code review prior to estimating ...


5

There's this Preferences class, which is a bucket for key-value pairs. Null values are legal (that's important). We expect that certain values may not be saved yet, and we want to handle these cases automatically by initializing them with predefined default value when requested. The problem is exactly this. But you already posted the solution yourself: ...


5

....no. There is not. I never really thought before of the idea of such a thing existing because it's relatively obvious there's no perfect solution, but now that you mention it....that would be awesome! However no, there is not nor will there ever be a perfect solution to ensuring your code isn't terrible, quickly, slowly, or inbetween (sluickly?).


5

If you do it to improve code readability, this is a good idea. If you do it to type less, you probably do it wrong. In your example, your methods don't improve readability; I would even assert that they add complexity and decrease readability: What is Write? Is it writing something to a file? A log? Right, you should read how the method is implemented ...


5

Simply. Don't mix code built with debug with code built without. If that class is exported by library you link against, you either need to: Have debug and release version of the library. That's what one always does on Windows where even the standard runtime has such two versions and they are incompatible, so there is no other way in most cases. This is ...


4

Not daisy-chaining is almost always preferred. Look at your example, and imagine a future maintainer reading this code to fix a bug, without the benefit of the flow chart. It's tough to tell from dummy example function names, but in a real program, he can read the main function to reconstruct the overall flow and tell where to look next by the names of the ...


4

Use enums. Good ORM framework can easily handle mapping of enums to IDs. Then you benefit two ways: Simple use in code and clear business logic - you operate (compare, etc.) on descriptive names, so business logic is clear. Performance efficiency: No joins for descriptive names in db queries (ORM will operate on Ids only) If you can't - you can fallback ...


3

Though I think @BЈовић's answer is fine in case getValueByKey is needed nowhere else, I don't think your solution is bad in case your program contains both use cases: retrieval by key with automatic creation in case the key does not exist beforehand, and retrieval without that automatism, without changing anything in the database, repository, or key map ...


3

I know I am late to the party, but anyways your use case resembles how Java's Properties lets one define a set of default properties too, which will be checked if there is no corresponding key loaded by the instance. Looking at how the implementation is done for Properties.getProperty(String) (from Java 7): Object oval = super.get(key); String sval = (oval ...


3

Your methods should do one and one only thing. For example, is saying good bye a part of doBar? If yes, your second approach should be used. If saying good bye should be done after doBar but is not part of doBar, then your first approach is better. Practical example. A part of an application should read and process data. This is done through five ...


3

Of the things you should be worried about as a programmer, initialization overhead is way, way down on the list. Your suggested grouping is a minimal first step. The next step is to reconsider if you actually need to keep all that data together in one case class. You almost never do, and it usually hurts you to create that large of a coupling. One thing ...


3

Let's assume you have an application that looks at the last 100 payments performed with a creditcard and displays a graph for these with the payments grouped into different categories (food, car, sports,...). Instead of the server performing all the grouping and calculating you decide to take advantage of the processing power on the clients (which is what ...


3

Let me cite from your own question: "… more JavaScript, but I can't find the time or passion …" "I would definitely happily learn fay-lang or purescript …" It seems obvious to me what is the more likely course of action. You obviously don't enjoy JavaScript as much as the other languages you mention. Having fun while learning and feeling ...


3

There are two entirely different things at play here: variable reuse and variable name reuse (redeclaration.) Your sample pseudocode does not make it clear which one of the two cases you are referring to, so I will mention both. This is variable reuse: int i = 5; for( ;; ) { i = 3; ... } This is variable name reuse: int i = 5; for( ;; ) { ...


3

Let's invert the logic here, to keep in the spirit of Demorgan's law: Would you want "programmers" to contribute to your project even though they have problems with elementary logic? Is that a net benefit to you? Or will they be time wastes? Does your project have enough volunteers to review their code?


3

Is there any way I can get them to accept help so I have something to work on? If you're near the end of the sprint, then the rest of your peers should be doing testing. Very few developers like doing testing, and testing doesn't require a ton of information exchange. By offering to do that stuff, you should get some help. If you're in one of the many ...


2

After much debate, we found a method that we like, but it involved other substantial changes to the project. We turned on pre-compiled headers. Within the pre-compiled header, we first include any and all system headers (and other third-party library headers) that are not compliant with banned.h, and then we include banned.h. This has a lot of properties ...


2

One thing that neither thread brings up is this: char whopping_great[8192] = "foo"; vs. char whopping_great[8192]; memcpy(whopping_great, "foo", sizeof("foo")); The former will do something like: memcpy(whopping_great, "foo", sizeof("foo")); memset(&whopping_great[sizeof("foo")], 0, sizeof(whopping_great)-sizeof("foo")); The latter only does the ...


2

Learn from the framework that learned from all Java's pain points: .NET provides two far more elegant solutions to this problem, exemplified by: Dictionary<TKey, TValue>.TryGetValue(TKey, out TValue) Nullable<T>.GetValueOrDefault(T default) The latter is very easy to write in Java, the former just requires a "strong reference" helper class. ...



Only top voted, non community-wiki answers of a minimum length are eligible