Tag Info

New answers tagged

1

It depends on the complexity of the binding operation. If it's just one line to populate the dropdown, encapsulating that in a method is unnecessary. If it's a dozen lines of database queries and looping over the result and whatever else, having a populateDropdownA method makes sense.


0

I think that is not good technique. Method should adhere single responsibility principle. Which means each method should have single responsibility. So it's better if you go with different method to bind each drop down. That's really help lot in future.


0

Microsoft has written and published a very good set of Cmdlet Development Guidelines Excerpt: The topics in this section provide development guidelines that you can use to produce well-formed cmdlets. By leveraging the common functionality provided by the Windows PowerShell runtime and by following these guidelines, you can develop robust cmdlets with ...


3

One common guideline is that for any fact known by your system, there should be only one place where it is stored. In a database, this is known as normalisation; in object design the principle is sometimes referred to as "Single Point of Truth", or the acronym SPOT. This is closely related to the principle "don't repeat yourself" (DRY), and in fact in one ...


6

If you set the one value (maximum) and then update the next (used) (and even more often - think of a progress bar) you are doing the calculation twice and even worse, nobody asked for the values between the setXY-operations. Why spend time for things nobody actually requests. Thus it is perfectly fine to use the getter to calculate the real value whenever it ...


3

I think you should have a reason to create a procedure. There are a number of reasons to create a procedure. The ones that I think are most important are: abstraction modularity code navigation update consistency recursion testing Abstraction A procedure can be used to abstract a general algorithm from the details of particular steps in the algorithm. ...


0

As I see it there are two aspects of using implicit typing. The first is, as Andrew Shepherd and the other answerers pointed out, to use the var keyword in a way that increases readability. However, in my opinion there is also another neglected aspect, and that is to increase refactorability. Lets say you see this code: foreach(var gear in ...


1

I have come to believe something about refactoring that I haven't seen mentioned here, I know there are a lot of answers here already, but I think this is new. I've been a ruthless refactorer and a strong believer in DRY since before the terms arose. Mostly it's because I have trouble keeping a large codebase in my head and partly because I enjoy DRY coding ...


0

As a corollary to @DocBrown's comment to @RobertHarvey about using functions to create abstractions: if you can't come up with an adequately informative function name that isn't significantly more concise or clearer than the code behind it, you are not abstracting much. Absent any other other good reason for making it a function, there is no need to do so. ...


66

Only if the duplication is intentional rather than accidental. Or, put another way: Only if you would expect them to co-evolve in the future. Here's why: Sometimes, two pieces of code just happen to become the same even though they have nothing to do with each other. In that case you must resist the urge to combine them, because the next time someone ...


4

Neither of the cases you give seem worth refactoring. In both cases, you are performing an operation which is expressed clearly and succinctly, and there is no danger of an inconsistent change being made. I recommend you always look for ways to isolate code where: There is an identifiable, meaningful task which you could separate out, and Either a. the ...


3

The most important aspect of named constants and functions isn't so much that they reduce the amount of typing, but rather that they "attach" the different places where they are used. With regard to your example, consider four scenarios: It's necessary to change both greetings in the same way, [e.g. to Bonjour, Tom and Bonjour, Mary]. It's necessary to ...


7

All best-practices have a particular reason, which you can refer to in order to answer such a question. You should always avoid ripples, when one potential future change implies changes to other components as well. So in your example: If you assume that you have a standard greeting and you want to ensure it's the same for all people, then write def ...


22

In your particular example making a function may seem overkill; instead I would ask the question: is it possible that this particular greeting will change in the future? How so? Functions are not simply used to wrap up functionality and ease reuse, but also to ease modification. If requirements change, copy-pasted code will need to be hunted down and ...


20

Personally I have adopted the rule of three - which I'll justify by calling YAGNI. If I need to do something once I'll write that code, twice I may just copy / paste (yes I just admitted to copy/paste!) because I ain't gonna need it again, but if I need to do the same thing again then I'll refactor and extract that chunk into it's own method, I've ...


2

In general I agree with Robert Harvey, but wanted to add a case to split up a functionality into functions. To improve readability. Consider a case: def doIt(smth,smthElse) for x in getDataFromSomething(smth,smthElse): if not check(x,smth): continue process(x,smthElse) store(x) Even though those function calls are ...


11

It's seldom clear-cut, so you need to weigh options: Deadline (fix burning server room ASAP) Code readability (may influence choice either way) Shared logic's level of abstraction (related to above) Re-use requirement (i.e. is having exact same logic important, or just convenient right now) Difficulty of sharing (here is wher python shines, see below) In ...


165

Although it's one factor in deciding to split off a function, the number of times something is repeated shouldn't be the only factor. It often makes sense to create a function for something that's only executed once. Generally, you want to split a function when: It simplifies each individual abstraction layer. You have good, meaningful names for the ...


1

There is no hard and fast rule that must be applied, it will depend on the actual function that would be used. For simple name printing I would not use a function but if it is a maths sum that would be a different story. You then would create a function even if it only gets called twice, this is to ensure that the maths sum is always the same if ever ...


50

No, it's not always a best practice. All other things being equal, linear, line-by-line code is easier to read than jumping around function calls. A non-trivial function call always takes parameters, so you have to sort all that out and make mental contextual jumps from function call to function call. Always favor better code clarity, unless you have a ...


1

The first declaration also allows you write the function differently: int accumulate(int n, int *array) { int sum = 0; while (n-- > 0) sum += *array++; return sum; } so you don't need the variable i. Whatever's idiomatic to the code base should be preferred, followed by whatever's the easiest to understand, followed at some distance by ...


1

You say that there are 3 ways in C and C++, but C++ actually makes a fourth available: template<std::size_t n> void arrayFunction(std::array<int,n> &array) { ...} This has several advantages over the solutions you suggest: The parameter for the size of the array will be automatically determined on use by the compiler, meaning you don't ...


5

In practice, you'll see int accumulate( int n, int *array) most often. It's the most flexible (it can handle arrays of different sizes) and most closely reflects what's happening under the hood. You won't see int accumulate( int (*array)[N] ) as often, since it assumes a specific array size (the size must be specified). If your compiler supports ...


1

Typically, you would use the variables directly. You expect to change all members when changing a class's implementation. Not using the variables directly simply makes it more difficult to correctly isolate the code that depends on them and makes it harder to read the member. This is of course different if the getters implement real logic, in that case it ...


0

For a class this small, simplicity wins. I would just use a * b. For something far more complicated, I would strongly consider using getA() * getB() if I wanted to clearly separate the "minimal" interface from all the other functions in the full public API. An excellent example would be std::string in C++. It has 103 member functions, but only 32 of them ...


1

I would say that using the public methods would be preferable, if not for any other reason but to conform to DRY. I know in your case, you have simple backing fields for your accessors, but you could have certain logic, e.g. lazy loading code, which you need to run before the first time you use that variable. Thus, you would want to call your accessors ...


7

It depends of the actual meaning of a, b and getProduct. The purpose of getters is to be able to change the actual implementation while keeping the interface of the object the same. For example, if one day, getA becomes return a + 1;, the change is localized to a getter. Real scenario cases are sometimes more complicated than a constant backing field ...


0

I don't think it's really a versus. Pythoneers often criticize braces programmers as if they would readily violate indentation because they can. In fact I always used 100% consistent indentation even before knowing about Python and its indentation scoping. The fact is that braces languages could also impose correct indentation in the compiler and we would ...


1

Specifically in the case of Swift, I believe there are a few benefits to leaving out self unless explicitly required by the compiler: Using self only where required (i.e. in closures where self is captured) makes it much easier to spot situations where references to self may be improperly retained. I ran into an interesting issue where the use of self ...


2

In C, when the array notation is used for a function parameter, it is automatically transformed into a pointer declaration, so declaring parameter as int* array and int array[] are equivalent. I tend to use second one because it is more clear that function expects an array as an argument. Declaring function parameter as int (*array)[] is not equivalent to ...


0

Compare your situation to the empty string / null string: An empty string (in C: '\0') means the string is known to have no value, whereas the null string means it is not known to have a value. As the result value is not known until the job finishes, the null value seems correct. Of course you can use an enum value to indicate "not known to be known". It ...


-1

to me, the most straight forward C translation of the pseudocode is do { success = something(); if (success == FALSE) { handle_the_error(); } } while (success == FALSE) \\ moving on ... i don't get why this obvious translation is a problem. perhaps this: while (!something()) { handle_the_error(); } ...


13

What you have to strive for is avoiding raw loops. Move the complex logic into a helper function and suddenly things are a lot clearer: bool getValidUserInput(string & input) { cout << ": "; cin >> input; if (cin.fail()) { cin.clear(); cin.ignore(512, '\n'); return false; } return true; } int ...


9

It's not so much that for(;;) is bad. It's just not as clear as patterns like: while (cin.fail()) { ... } Or as Sjoerd put it: while (!(cin >> input)) { ... } Let's consider the primary audience for this stuff as being your fellow programmers, including the future version of yourself who no longer remembers why you stuck the break at the ...


14

I would write the if-statement slightly different, so it is taken when the input is successful. for (;;) { cout << ": "; if (cin >> input) break; cin.clear(); cin.ignore(512, '\n'); } It's shorter as well. Which suggests a shorter way that might be liked by your teacher: cout << ": "; while (!(cin >> ...


3

My logic instructor at school always said, and pounded it into my brain, that there should only be one entrance and one exit to loops. If not you start getting spaghetti code and not knowing where the code is going during debugging. In real life I feel that code readability is really important so that if someone else needs to fix or debug an issue with ...


1

There are plenty of methodologies given for making your code more adaptable and maintainable, but most of them have the following points at their core: Keep methods small: Your methods should only do one thing well. If they try to do more than one thing they will almost certainly fail at doing at least one of those things under certain circumstances, and ...


2

I'm not advocating this as the answer, but this is a list of techniques that has helped me greatly over the past 20 or so years. Self documenting code You might be tempted to add comments everywhere to make the code easier to understand. But the simple fact is that a lot of the time, if extensive comments are required within a method, the code isn't simple ...


-1

As MainMa already said: The changes that actual happen are unpredictable. (in almost all cases) Keep the implementation as simple as possible from the technically POV and as close as possible to the actual requirements (i.e. use speaking identifiers), or, in other words The best you can do for future changes is help understanding how your solution works.


9

Two very essential things to understand are that: You can never anticipate every change a customer may ask. I had a customer who decided to switch a two months project from PHP to ASP.NET one week before release and was convinced that this would be an easy change. Any change will have a cost. It doesn't matter if you are using Agile or if you have clean ...


1

I completely agree with Bart on this, considering that you will rarely if ever see your footer.php as text included in the referencing file you only need to make sure footer.php is human reader friendly. The only time footer.php is seen as text and not a reference is the complete page output in the browser page source which will not be seen by humans. So ...


3

In both (X)HTML and PHP, whitespace is largely irrelevant and and indentation is only useful for human readers. The browser reading the HTML and the interpreter processing the PHP will just ignore the indentation. This makes that the best practice is that you try to makes the codes look nice to a human reader in those files and/or outputs that will read by ...


1

Looking at this as a state machine problem, where each state was represented by an enum, it would be reasonable to provide an enum for all states, including the "not yet" state. I'd be tempted to name it something meaningful, though, like "PROCESSING" rather than a synonym for "NULL". Setting aside the programmatic problems with NULL, representing the state ...


4

If a field value is one of a list of predefined values, your domain will have a real-world value that you can correspond to NULL. All you have to do is look for it. If the Status is not completed its result could be 'NotFinished', 'Unavailable', 'DoesNotExist' or 'Unknown'. Think about this in a non-code way. If you print something and ask a colleague to ...


0

If OptionalAttrType is part of the public API defined by those headers, then I would use some other name for your typedef. If OptionalAttrType is an implementation detail that you aren't supposed to know about, then those headers should have put it inside a namespace to prevent collisions like this. Since they didn't, you have to work around this somehow. ...


3

Ask yourself, what is the expected behavior of your method when the variable is outside the range? Should it: Silently discard it and do nothing? Then your second approach is fine. Inform the caller that the variable is wrong? My answer focuses on this case. Although I would prefer the first approach, it can be improved. The second approach, on the other ...


8

Ask yourself honestly why you want to refactor. That's really important. then think what you're doing at your company - are you hired to write nice code, or to create good product. I think too many developers get so caught up in the minutiae of the codebase that they forget what they're supposed to be doing - which is making something useful out of it. Its ...


4

I admit, I love refactoring code - but chose wisely what to refactor and why. Will the user of your code clearly benefit from the rewritten code? Will the user demand this new functional style code, or is it just a developer thing, to try coding with a different style? If there is no benefit for the user at all, except the code is now looking "nice", who is ...



Top 50 recent answers are included