Tag Info

New answers tagged

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


1

Maybe it's force of habit from C coding 20+ years ago, but, no matter what teh language, I usually let my small helper functions float to the top. At the very least, I like to have every function declared before it is called, in order to obviate the need for forward declaration/function prototypes. I guess that makes me the exact opposite of @IAE (+1 to ...


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


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


1

It actually depends. I would only create a Class which contains instance attributes if more than one of its methods uses it. On the other hand, if an attribute (or variable) is only used inside the method, then it should be defined local to the method it uses. In the example you describe, I think that you are using functions instead of methods, which to me ...


0

If field and field2 need to persist outside of a particular method call, then they need to be defined at class level, outside of the methods. Where they happen to get instantiated thereafter doesn't really matter (as long as all of your code accepts that they might not be initialised). If field and field2 are only ever used inside a particular method, then ...


1

Put the function in the same namespace as the classes it operates on. This way, it does not clutter the global namespace and is properly grouped for easy understanding, but will easily be found by ADL (argument-dependent-lookup). As an aside, that's the way swap should be implemented and used: The standard provides the generic std::swap and various ...


1

boost uses a lot of free functions (free functions are a good thing). The free functions are maintained close to the namespace that involves the objects or other related classes associated with the free function. Then the free function definitions are hoisted to upper namespaces as required. This technique gives control over the scope of free functions. ...


0

Your problem is that you're not doing Agile. What is this "my work" you speak of, as if its been allocated to you? In an agile environment, you should have a backlog of tasks that the team works on, individual members of the team, pick up a task, work them and then go back for more until either you run out of time or you run out of tasks (what you do then ...


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


1

I don't think either of those two is really more complex or more difficult than he other. I'd choose the one without the unnecessary pass branch, because that's an unnecessary branch. If you consider all the things that keep people from contributing to Open Source (it needs time, some programming ability, motivation, getting a Github account, making sense ...


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?


1

I terms of readability and maintainability you will be better of with a dictionary if there are anything more than five or six actions. In terms of performance (depending on language, version, hardware etc. etc.) the trade off is:- Switch: one comparison per test value plus one branch per action if you assume the values are evenly distributed then you will ...


2

What if you have hundreds of values to choose from? How would your switch statement look like? Would it be maintainable? I think not. What you lose by using a map is very minimal hit in performance because of more misdirection - what you gain is huge, huge boost in maintainability. As mentioned by greyfade in the comments, you can also change the map ...


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


0

Specificity - don't use a variable named variable unless it refers to something specific, like variable timing on an engine. Just don't do it. In a given context: Do not re-use variable names in a given context for different purposes. In a function, don't make variable = 'foo' for use as a string then later in the function make variable a numerical index ...


0

Reusing a variable is bad, because a compiler that would normally warn you about uninitialised variables etc. can't warn you, because at the time of the second use, the variable will be initialised. Reusing a variable name is usually not a problem. You may get compiler warnings if you create a variable with the same name as another variable in an outer ...


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


1

If the variable is something simple and clear, like i, count, sum, go ahead and reuse it. If the variable is central to the method, like calculatedResult, or you are in a series of if/else blocks (or blocks all ending in return calculatedResult), reuse it. But if the blocks are not mutually exclusive, and control flows from one to the other, it might be ...


2

If the variable in question represents the same thing for both functions, I can't see why it would be a problem. If you're arbitrarily using variable to mean "any variable within a function that can do anything" then yes, it is a problem. Name your variables in the context to which they are used.


-1

First and foremost, calling Singleton2's getMyObject() method will crash the program because it does not create a new instance when it is null, and will just return null. Second, there is no getMyObject in a singleton class. There is just getInstance().


0

There's certainly a case to be made for it. All high-level languages that aren't purely interpreted "compile to another language", and most developers manage to be successful without ever learning (or learning very much of) ASM/CIL/JVM bytecode/whatever else. However, it's important to keep in mind the law of leaky abstractions. When you work on something ...


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


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


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


2

It's not you. It is something that a lot of developers struggle with and it is something you learn to live with as a developer. As soon as your code is typed it will probably be outdated. Here's a few tips on how to deal with that... Building something in a new framework/library/language is the best way to learn A lot of developers have projects 'on the ...


1

Yes, and its a hindrance to the industry. This continual churn of technologies only serves to help people who create them and those who sell training courses. So Microsoft is happy as it gets to sell new tools every few years and we all have to buy them because we've been indoctrinated to "stay current". Whilst some change is necessary, IT seems to be the ...


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


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


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


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


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


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


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


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


0

So here, you're writing the handler that throws the exception and the grid manages that exception itself. I see this as fair enough - after all, you're writing the library code that throws on error states, and the caller (ie the grid) catches and manages the exception how it likes, in this case showing a message to the user in a dialog (which is perfectly ...


2

Since the .NET framework standard UI controls do not catch unhandled exceptions by themselves, and offer you some mechanisms to catch those exceptions in a central place, I agree that it is questionable why a 3rd party control should behave differently. Lets assume, from the nature of your application, in case of a severe failure, you are 100% sure you can ...


1

I am very fond of hard error & fail fast, I believe they are the one true and right way to go, but I try not to be dogmatic about them. There are cases where the best thing to do with an unexpected exception is to log it and swallow it. I will give you an example which is more simple than your situation: suppose you have an observable collection which, ...


1

I recently solved a similar problem with a third-party library. Allow me to restate to make sure I'm not misinterpreting your situation. You know how to work around it, but you don't like the repetition of the workaround, and you feel it obscures your actual code? I solved my problem using a python decorator that catches an exception and handles it ...


2

What is there to do. In my view, the decision to turn an exception during validation into a failed validation is a correct way of handling such exceptions. Letting the exception pass through and crash the application has a significant risk that you lose the work the user had been doing, even if the situation was caused by bad user-input and entirely ...


0

In my experience, if a software developer doesn't properly understand the system/domain he is writing the code for then the code is quite likely to become over-complicated. The reason for this is fairly obvious. Simple code has a structure that mirrors the problem being solved or the domain being modelled. That way the code's behaviour tends to emerge from ...


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


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


1

If at all possible, use an IDE supplied with (at least) these two components: some kind of static code checker with metrics and, if you can, a report tool. a quick way to refactor code (hunt symbols and so on). Books are great to understand the why and the how - you need a tool that will pitilessly ferret out the what and the how much. You can then ...


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


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


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


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


0

You could, instead of using banned.h, write a Clang analysis program that analyzes your source code. You can use it to enforce whatever coding rules or guidelines you like, not just the banning of a specific set of C functions, and it can also query the source location of any given code and implement location-specific rules.



Top 50 recent answers are included