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)) { ...


11

Congratulations! You've just reinvented Ada's looping structure. Jean Ichbiah probably reinvented someone else's prior art. This is de facto possible in a lot of languages, where you can create endless loops with programmed exits. For example, in Python: while True: do_stuff() if not loop_continues: break do_more_stuff() The reason so ...


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 ...


7

Use whichever one you think is more readable and maintainable. Depending on the language, variables and function calls involved, either one might be preferable. If I had to evaluate your two examples in isolation, I would have a slight preference for the second version because it makes it a little more obvious that do_something() only gets called once. But ...


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 ...


5

Yes, a function that just raises an exception is OK. You can easily have functions like ensureWellFormed(email_address) or http_request.ensureUserLoggedIn() that raise well-documented exceptions. This de-clutters code, and many high-profile projects, e.g. Django, do use this style here and there. If you use this approach, make sure your exception objects ...


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: ...


4

Imagine a concrete example of a code which, given a price of an item, should call a method while specifying if the item is a rebate (price inferior to zero), a paid product (price superior to zero) or a free product (price equal to zero). Your two pieces of code become: Solution 1: if (price < 0) { this.DoSomething(PriceType.Rebate); } else if ...


4

The methods I've seen most are 2 and 3. The user supplied buffer is actually quite simple to use: char[128] buffer; mytype_to_string(mt, buffer, 128); Though most implementations will return the amount of buffer used. Option 2 will be slower and is dangerous when using dynamically linked libraries where they may use different runtimes (and different ...


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

I usually do the following unless there is a good reason not to. The member check acts as a "Guardian Clause" and the need for temp variables disappears if you are returning a constant in the case of an exception. private String getMyString() { if (!mStrigMember.isEmpty()) return mStrigMember; try { return ...


3

In your second example, the Map should be a private static member to avoid redundant initialization overhead. For large amounts of values, the map will perform better. Using a hashtable, one can look up the answer in constant time. The multiple-if construct has to compare the input to each of the possibilities until it finds the right answer. In other ...


3

The point is to move the creation of the hashmap outside the function and do it once (or just less times than otherwise). private static final Map<String, Integer> map; static{ Map<String, Integer> temp = new HashMap<String, Integer>(); temp.put("A", 12); temp.put("B", 21); temp.put("C", 45); map = ...


2

Optional is the correct solution. However, if you prefer, there is an alternative which has less of a "two nulls" feel, consider a sentinel. Define a private static string keyNotFoundSentinel, with a value new String("").* Now the private method can return keyNotFoundSentinel rather than throw new KeyNotFoundException(). The public method can check for ...


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. ...


2

ID's are needed to be unique while classes tend to group several elements' style together. I read somewhere it as this analogy : <student id="JonathanSampson" class="Biology Calculus" /> <student id="MarySmith" class="Biology Networking" /> Student ID cards are distinct. No two students on campus will have the same student ID card. ...


2

I think the gist of the argument, for those that agree with it, is to use class for css selectors instead of id. This avoids unintended css precedence rules from kicking in. If you know what you're doing (re class vs id selectors), and it works for you, I wouldn't change just for the sake of changing, though. From http://csslint.net/about.html: IDs ...


1

Maybe It can work to externalize validation logic as long as it is not externally visible and is used to enforce preconditions. Say you have an object that operates on a database connection, and most of its functions require that the connection be set up and initialized. Rather than checking the connection and conditionally throwing an exception in each ...


1

I recommend separating the concerns of the do_something and the conditions. There is some business logic that should be well named and encapsulated to determine what the do_something will operate on (ConditionType in my example below). Use the resulting ConditionType as a parameter to do_something. I read a lot of code (more than I write) and I'm not a ...


1

There are many reasons to select by an id. I think the spirit of that message from lint is that you should primarily apply styling by classes. Selecting by id can be the exception where your styling is shared across similar elements, except this one, or only this one. You can use classes to act as an id, but I think thats probably evangelism. That'd be ...



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