New answers tagged

-1

Since you asked out of curiosity, and your question is not tagged with a specific language (even though it's clear you had imperative languages in mind), it may be worth adding that languages supporting lazy evaluation allow for a complete different approach. In those languages, expressions are only evaluated when needed, so you can define "variables" and ...


1

If you're writing code that needs a library, the import for the library is necessarily less code than the code which uses said library. When you put the two together in the same file, it is more likely that changes in one will result in remembering to do the other. Particularly if your editor uses pyflakes to enforce PEP compliance and therefore notices ...


1

The correct answer is: C. None of the above. Option A: void fill_array(Array<Type>* array_to_fill); This is more idiomatic for pre-C++11 code where smart pointers were troublesome due to a lack of move semantics, and still continues to be the safer of the two options. The key here is the function does not "own" the memory: it performs one ...


0

Well, obviously you can seperate them into two solutions, add another project in solution, or have them in same project. I will tell what I would. IMHO, if you want to take advantage of Sessions in IIS and/or hide authentication process within API, write angular in Visual Studio as well. VS2015 has a pretty good integration(intellisense) with angular if you ...


10

I would name them based on what the facade does for consumers, or what it needs to "look like" to the outside world. The fact that it is a facade is an implementation-detail. So instead of, say, BillingSystemFacade, I'd present it as a BillingService. Heck, perhaps someday I can get rid of whatever clunky API is behind it, and rewrite it from scratch, but ...


2

You have already an accepted answer, but I am adding a new one (because I disagree with what @ixrec said). I imagine there is a subtle difference, but I don't know what it is. Could someone explain when I might prefer one form over the other? Ideally (in a perfect world), you should use the second form, for three reasons: it composes it naturally ...


0

I guess, annotation processing could be the solution, even without annotations. It's the thing which can generate all the boring code for you. The downside is that you'll get N generated classes for N model classes. You also can't add anything to an existing class, but writing something like public Object getNode(String name) { return ...


1

Returning the Optional seems OK but if there is no value the logic should not proceed. Each guest has a real room assigned to it or it is not a guest. So once the receptionist decided to return an empty Optional, the order should be put back in the queue and nothing more. It is fine to first take the order from the queue, then perform the ...


1

I think you could model it in two ways: Option 1: Using an wrapper + enum for the receptionist response: enum ReceptionistDecision { BOOK_ROOM, NO_ROOM, RETURN_TO_QUEUE, } class ReceptionistResponse { ReceptionistDecision Decision; Optional<Room> Room; ReceptionistResponse(Room room) { ... } ...


5

There are couple of approaches one could apply to modelling this. First, we might have the passive receptionist. The passive receptionist decides what to do, but doesn't do anything. Instead, we have class something like public class ReceptionistResponse { public static ReceptionistResponse bookRoom(Room room); public static ReceptionistResponse ...


8

The first kind of signature is usually preferable. The difference is that the second signature requires the array to be created inside the function. In particular, the second signature effectively requires the array to outlive the scope in which it was created. So what we're really comparing are these two snippets: function foo1() { Array<Type>* ...


2

It seems most likely that the second one returns Array<Type> and not Array<Type>*. In the first case, there is an Array<Type> somewhere and you pass a pointer to it, so the function can fill it. In the second case, the function creates an object and returns it (unless the type is Array<Type>* and I don't know what's going on). If you ...


5

What Style is Better (Instance Variable vs. Return Value) in Java There's another style - use a context/state. public static class MyClass { // Hold my state from one call to the next. public static final class State { int var1; } MyClass() { State state = new State(); doSomething(state); ...


0

There already are answers talking about object state and when the second method is preferred. I just want to add one common use case for the first pattern. The first pattern is perfectly valid when all what your class does is that it encapsulates an algorithm. One use case for this is that if you wrote the algorithm to a single method it would be too large. ...


-1

Let's try an example that does something. Forgive me since this is javascript not java. The point should be the same. Visit https://blockly-games.appspot.com/pond-duck?lang=en, click the javascript tab, and paste this: hunt = lock(-90,1), heading = -135; while(true) { hunt() heading += 2 swim(heading,30) } function lock(direction, width) { ...


1

It's about side effects. Asking whether var1 is part of state misses the point of this question. Sure if var1 must persist, it has to be an instance. Either approach can be made to work whether persistence is needed or not. The side effect approach Some instance variables are only used to communicate between private methods from call to call. This kind ...


7

You should reduce the scope of your variables as much as possible (and reasonable). Not only in methods, but generally. For your question that means it depends whether the variable is part of the object's state. If yes, it's OK to use it in that scope, i.e. the whole object. In this case go with the first option. If no, go with the second option as it ...


94

I'm surprised this hasn't mentioned yet... It depends if var1 is actually part of your object's state. You assume that both of these approaches are correct and that it's just a matter of style. You are wrong. This is entirely about how to properly model. Similarly, private instance methods exist to mutate your object's state. If that's not what your ...


1

The first variant looks non-intuitive and potentially dangerous to me (imagine for whatever reason someone makes your private method public). I would much rather instantiate your variables upon class construction, or pass them in as arguments. The latter gives you the option of using functional idioms and not relying on the state of the containing object.


16

I don't know which is more prevalent, but I would always do the latter. It more clearly communicates the data flow and lifetime, and it doesn't bloat every instance of your class with a field whose only relevant lifetime is during initialization. I would say the former is just confusing, and makes code review significantly more difficult, because I have to ...


0

It is indeed good practice to declare variables as const (or readonly or final, depending on the language) if possible. The author of the linked answer also admits that is is right to mark variables as final, but the author is simply too lazy to do it. Even if the authors opinion about "clutter" was right, then it wouldn't apply to JavaScript or ...


4

*sigh*... This is why immutable needs to be the default. Even the referenced Java answer suggests this. Note that that answer does not recommend removing final modifiers, just that the author of that answer wouldn't add them in new code (for local variables) because they "clutter up" the code. However, there is a difference between JavaScript and Java ...


0

I would frame your company policy around readability, and consequently judge everything based around that, rather than a specific policy of having one exit point (or not). Code has many more readers that writers, and you want the code to be easily comprehensible.


4

it misuses java streaming api to handle something that usually would be covered by simple for and if statements This is a vacuous argument. Everything the streaming API does except for parallelization can be handled by for and if statements. Whether they're simple is a matter of taste; IMO your first example is already not simple. (You also managed to ...


-1

The last option is definitively more difficult to upgrade or edit and since it hides what's behind those linq-like function it could be difficult to debug. To solve the " If one tried to have one return at the end of the method, one would see all this hidden complexity definitely forcing one to refactor" problem i would do something like this: protected ...


1

I agree with Erik Eidt's answer, but there is a third option: stub out the constant in the test, so the test passes even if you change the value of the constant in the production code. (see stubbing a constant in python unittest) foo = FooSaver("/tmp/special_name") foo.save_type_a() foo.save_type_b() with mock.patch.object(FooSaver, 'A_FILENAME', ...


1

The concept underlying your question is so important I feel it needs another answer rather than just a comment (as I had started to do). The other 3 answers thus far provide some useful points of consideration on whether a given situation merits using what you call "nested function calls". But perhaps a more important point is hidden in the comments under ...


8

This really depends on how much nesting you use. After all, you are allowed to use function results directly in expressions to improve readability. Both, code that does not use nested expressions (like assembler code), and code that uses too much nested expressions is hard to read. Good code tries to strike a balance in between the extremes. So lets look at ...


1

It is absolutely not a bad practice in general. Functions call accept values and one way of producing a value is by calling another function. When I see a variable being defined, like: parsed_value = cashParser(input) ... I have to consider that parsed_value might be used more than once and I'll probably have to check if this is true or not (what if my ...


4

I think whether it's good or bad depends a lot on context. The main reason it might be considered bad is that it (arguably) makes the code harder to read and debug. This is especially true when you are first learning to program. As your coding skills (and code) gets more advanced, there are times when this is acceptable. For example, consider an error ...


0

I usually try to keep code as readable (= simple) as possible, so I try to eliminate such cases where possible. So the question is: when is it possible? You definitely need those checks if they are part of the business logic (eg a balance check before reducing a bank account). You don't if you can make assumptions (+ document those) on preconditions, eg ...


2

The simplest correct code is almost always best. Document the expected behavior both in comments and in unit tests. Your first example doesn't even have any special cases, and the simple "return a*y < b*x" is vastly preferable to the alternative. Then write a few unit tests, one with x and y zero, one with x zero, one with y zero, and three cases where ...


2

What @Erik suggested--in terms of making sure you are clear on what it is you are testing--should certainly be your first point of consideration. But should your decision lead you to the direction of factoring out the constants, that leaves the interesting part of your question (paraphrasing) "Why should I trade off duplicating constants for duplicating ...


13

I think it depends on what you're trying to test, which goes to what the contract of the class is. If the contract of the class is exactly that FooSaver generates a.foo_file and b.foo_file in a particular location, then you should test that directly, i.e. duplicate the constants in the tests. If, however, the contract of the class is that it generates ...


0

In the namedtuple documentation, it says: Any valid Python identifier may be used for a fieldname except for names starting with an underscore. Valid identifiers consist of letters, digits, and underscores but do not start with a digit or underscore and cannot be a keyword such as class, for, return, global, pass, print, or raise. Because namedtuples ...


1

namedtuple is a bit unusual thing in python. It is not a base class, it is a class generator. Invoking it creates a new class that uses a tuple for its storage and can be manipulated as either tuple or normal class with named fields. The generated class is intended to be used as a base for your own types that will add methods, and constraints. Including ...


2

Why is it [a bunch of seemingly random hard-coded values] OK for CSS/SVG? It isn't OK. It's possible to write and maintain plain ".css" files, but eventually random hard-coded values will become a prevalent burden. For anything other than extremely simple webpages, you will either have to develop a disciplined "find and replace" strategy, or use a CSS ...


11

Because CSS is not a programming language, instead, it is the configuration file that contains the variable data for your program. Currently CSS is so powerful that you can actually program in it, but that is besides the point. In essence it's still a stylesheet language. Let's take a step back. Imagine we have a programming language that can draw on a ...


25

The prohibition on magic numbers is the primordial version of this design principle: Make decisions in one place. But these are not magic numbers. At least, not as far as any coding style guide I know of is concerned. width: 200px; height: 200px; They are clearly labeled. Sure, the numbers happen to be the same. But the width is the width and ...


116

Firstly, magic values are avoided in programming by using variables or constants. CSS does not support variables, so even if magic values were frowned on, you don't have much of a choice (except using a preprocessor as SASS, but you wouldn't do that for a single snippet). Secondly, values might not be as magic in a domain specific language like CSS. In ...


79

It's acceptable because these formats are not code, but data. If you were to remove all the "magic numbers," you would essentially duplicate every label, and end up with ridiculous looking files like: mainkite_width = 200px ... .mainkite { width: mainkite_width; ... Every time you needed to change some data, you would need to look in two places. ...


3

No one is doing that because it does not make sense from a syntactical perspective. While it conceptually makes sense to indent items that have a child relationship with a parent item, it does not work well in practice for CSS. Keep in mind that there is a distinction between DOM nodes and CSS selectors. Although elements may be nested within each other in ...


1

Create a Repository Layer contains and manage all your repositories and business logic, create unit of work class to act as single point to manage your repositories. Create Data Access Layer that will contains your database Layer (EF code first). Create contracts Layer will contains all interfaces of your repositories which you can easily inject it using ...



Top 50 recent answers are included