New answers tagged

5

This violates the Liskov Substitution Principle because an OkayButton cannot be substituted in any place a Button is expected. For example, you can change the label of any button as you like. But doing that with an OkayButton violates its internal invariants. This is a classic misuse of inheritance for code reuse. Use a helper method instead. Another ...


0

Use which ever convention you prefer and live with the consequences. Most readers of your code will know how to interpret "is" and "has" prefixes. For this reason I recommend using the convention. It is helpful to others. In addition, consider what "makes sense grammatically" actually means in a coding context. Don't confuse the grammar of your spoken ...


3

I'd be willing to bet that your teacher doesn't actually believe that you should always extend a Swing component to use it. I bet they're just using this as an example to force you to practice extending classes. I wouldn't worry too much about real-world best practices just yet. That being said, in the real world we favor composition over inheritance. Your ...


1

Given: the application may be split up into different parts (business fields) most likely. and the application might be split apart into single services in the next few years I would be reluctant to do anything based on the above. Who knows what will happen in the near future, and I'd be wary of basing any design on what is predicted to ...


6

IMHO, Best Programming Practices in Java are defined by Joshua Bloch's book, "Effective Java." It's great that your teacher is giving you OOP exercises and it's important to learn to read and write other people's styles of programming. But outside of Josh Bloch's book, opinions vary pretty widely about best practices. If you are going to extend this ...


8

This is a very non-standard way of writing Swing code. Typically, you only rarely make subclasses of Swing UI components, most commonly JFrame (in order to set up child windows and event handlers), but even that subclassing is unnecessary and discouraged by many. Providing customization of text to buttons and so-on is usually performed by extending the ...


0

So you want to normalise your DB to cope with the subclasses - I'd say that makes sense. Its easy to do, you create views or stored procs to expose the new DB schema to the old application as if nothing had happened and work on modifying the DB tables as much as you like. When that's complete, you can modify the application to start reading from the new ...


36

It's completely terrible in every possible way. At most, use a factory function to produce JButtons. You should only inherit from them if you have some serious extension needs.


5

If your class is too big and unwieldy when it's all in one place and you can easily see it all, what makes you think scattering it across multiple files and making it harder to correlate will be an improvement? Partial classes are essentially a hack to make it easier for generated code, such as that produced by the form designer, to work together with ...


1

I am strongly against procedures, I don't believe any business logic (including logic that says in which format you should query a database) belongs to the database, but to the code itself. Even though in your case the simplest solution is to simply create a new function in your code, make a getUsersByEmail procedure in the database and call this newly ...


1

It seems like in your app, having two separate functions (Option 1) is a simple enough solution because you have these distinct ways of getting user details at different places in your application. If you wanted to have a single function that has to determine whether you're giving it an ID or an email, that type of logic isn't too difficult. You can even ...


3

This is not a good idea because you can introduce a race condition. In one thread you change the value to one you want but before you manage to create an instance of the class another thread changes the value, and you get an instance created with the wrong default value. Your hair will grow whiter than mine, trying to figure out why things aren't working ...


4

I'm sure there are situations where this would make sense to do, particularly if you're writing a small application, but in general I think it would be a bad idea. You could apply any argument that you could make about global variables to static variables - they're still changeable anywhere in the application. If your application (and dev team) is ...


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


0

I would propose a more objective basis. Go to your existing HTTP logs. Assuming this is an update to an already in the field app, simply pull the logs and examine the HTTP requests which are included. This provides an absolute objective basis fore your load modeling instead of a wetted finger in the air to test the wind. Also, keep in mind from a QA ...


4

As long as you want only a PDF version of your report, it's enough to simply apply good factoring practices. Write utility functions, extract common code into subroutines, choose good method names, and after a while you'll have a pretty decent maintainable report generator. However, the second it looks as if you'll have to support any other output format ...


7

Your parsedDate method doesn't need the throws Exception clause because the exception is already being caught. The compiler looks at the method signature when a method is called and sees throws Exception, so it expects you to handle it.


-2

I'm a big fan of meaningful names. Is this function insert(array, rightIndex, value) { for(var j = rightIndex; j >= 0 && array[j] > value; j--) { array[j + 1] = array[j]; } array[j + 1] = value; }; as clear as this? function insert(array, value) { old = array.length - 1; new = array.length; while ...


1

I am going to give a more detailed example of how to use pre/post conditions and invariants to develop a correct loop. Together such assertions are called a specification or contract. I am not suggesting that you try to do this for every loop. But I hope that you will find it useful to see the thought process involved. In order to do so, I will translate ...


0

In theory declaring functions for your nested loops may sound good. In practice you have to be very careful with hiding complexity. Maybe I can explain better with an example. Consider you have a list. Now you make an add function, but you don't want duplicates, so the add function checks all items and only adds an item if there's no duplicates. Easy ...


0

Eventually you will learn about refactoring. Refactoring is about changing a program so that its structure is different, while it does exactly the same thing as before. Two refactoring methods that are often used are splitting a function into two functions, and combining two functions into one. The art is twofold: First, being able to work focused and ...


2

as I get deeper and deeper into my developent career, I find myself losing interest in the academicians who spout truisms about levels of nesting, anti-patterns and etc. I'll share what seems to work well for me in a pragmatic, enterprise-focused development environment: "...solve for the specific case in front of you, THEN refactor for the general ...


1

I think the problem is the same one as with any unintendend infinite recursion: You are not perfectly sure what the callee does when you call it, and if that callee happens to call the caller with unchanged arguments, you are doomed. I really don't think that your case is any different, only the involved mechanics differ. So, I would apply the same to your ...


0

I'll try to stay clear of the topics mentioned galore already. What are tools/mental models to avoid such mistakes? Tools For me, the biggest tool to write better for and while loops is not to write any for or while loops at all. Most modern languages try to target this problem in some fashion or other. For example, Java, while having Iterator right ...


0

Since you've specified that you're using C# a viable solution to your situation is to leverage the Roslyn Code Analyzers. This will allow you to catch violations immediately and even allow you to suggest code fixes. One way to implement it would be to decorate the temporally coupled methods with an attribute that specifies the order that the methods need to ...


0

If I understood the problem correctly, your question is how to think to get loops right from the first try, not how to make sure your loop is right (for which the answer would be testing as explained in other answers). What I consider a good approach is to write the first iteration without any loop. After you've done this, you should notice what it should ...


0

Are you simply confused about what a for loop actually does and the mechanics of how it works? for(initialization; condition; increment*) { body } First, the initialization is executed Then the condition is checked If the condition is true, the body is run once. If not goto #6 The increment code is executed Goto #2 End of loop It might be useful ...


3

Off-by-one errors are one of the most common programming mistakes. Even experienced developers get this wrong sometimes. Higher level languages usually have iteration constructs like foreach or map which avoids explicit indexing altogether. But sometimes you do need explicit indexing, as in your example. The challenge is how to think of ranges of array ...


0

I'm not 100% sure of the problem you had but it seems like you had issues with callbacks calling callbacks, or at least callbacks being called out of sequence. Why that was occurring seems to be that you are combining a callback-based architecture with an event based one, so you don't have full control over your program flow. A simple answer would be to ...


-3

In your example, the body of the loop is quite obvious. And it is quite obvious that some element has to be changed at the very end. So you write the code, but without the start of the loop, the end condition, and the final assignment. Then you go away from the code and find out which is the first move that needs to be performed. You change the start of ...


1

Getting this right easily and fluently is a matter of experience. Even though the language doesn't let you express it directly, or you're using a more complex case than the simple built-in thing can handle, what you think is a higher level like "visit each element once in revere order" and the more experienced coder translates that into the right details ...


-1

There are several approaches: Make the class easy to use right and hard to use wrong. Some of the other answers focus exclusively on this point, so I'll simply mention RAII and the builder pattern. Be mindful of how to use comments. If the class is self explaining, don't write comments.* That way people are more likely to read your comments when the class ...


3

Looking at this problem more generally than the current answers do, which have mostly focussed on initialization. Consider an object that will have two methods, a() and b(). The requirement is that a() is always called before b(). You can create a compile-time check that this happens by returning a new object from a() and moving b() to the new object ...


2

Perhaps I should put some flesh on my comment: There is only one way: understand your problem better. But that is as general as your question is Your point is Although I got my assumptions correct after some trial and error but I got too frustrated because of the lack of correct computing model in my head. When I read trial and error, my alarm ...


60

When programming it is useful to think of: pre-conditions post-conditions variants and invariants (of loops or types) and when exploring uncharted territory (such as juggling with indices) it can be very, very, useful to not just think about those but actually make them explicit in the code with assertions. Let's take your original code: /** * Inserts ...


11

I agree with other people who say test your code. However, it's also nice to get it right in the first place. I have a tendency to get boundary conditions wrong in many cases, so I've developed mental tricks to prevent such problems. With a 0-indexed array, your normal conditions are going to be: for (int i = 0; i < length; i++) or for (int i = ...


9

I got too frustrated because of the lack of correct computing model in my head. Is a very interesting point to this question and it generated this comment:- There is only one way: understand your problem better. But that is as general as your question is. – Thomas Junk ...and Thomas is right. Not having a clear intent for a function should be a ...


4

The introduction to your question makes me think you haven't learned to code properly. Anyone who is programming in an imperative language for more than a few weeks should really be getting their loop bounds right first-time in more than 90% of cases. Perhaps you are rushing to start coding before you've thought through the problem sufficiently. I suggest ...


159

Test No, seriously, test. I've been coding for over 20 years and I still don't trust myself to write a loop correctly the first time. I write and run tests that prove it works before I suspect it works. Test each side of every boundary condition. For example a rightIndex of 0 should do what? How about -1? Keep it simple If you can't see what it does at ...


22

Use unit testing/TDD If you really need to access sequences through a for loop, you can avoid the mistakes through unit testing, and especially test driven development. Imagine you need to implement a method which takes the values which are superior to zero, in reverse order. What test cases could you think of? A sequence contains one value which is ...


2

The answer is: Yes, no, and sometimes. :-) Some of the problems you describe are easily solved, at least in many cases. Compile-time checking is certainly preferable to run-time checking, which is preferable to no checking at all. RE run-time: It is at least conceptually simple to force functions to be called in a certain order, etc, with run-time ...


0

The principle of Information Hiding (Encapsulation) is that entities outside the class should not know more than what's required to use this class properly. Your case seems like you are trying to get an object of a class to run properly without telling the outside users enough about the class. You have hidden more information than you should have. Either ...


2

Comments are for communicating any information to future developers who are either using or maintaining the code, which is not obvious from reading the code. When writing comments, consider the situations facing a new developer who is unfamiliar with your code, and your present mindset. While you're writing code, you're usually juggling a lot of balls in ...


2

Yes, your instincts are spot-on. Many years ago I wrote articles in magazines (kind of like this place, but on dead-tree and put out once per month) discussing Debugging, Abugging, and Antibugging. If you can get the compiler to catch the misuse, that is the best way. What language features are available depend on the language, and you did not specify. ...


1

I think the root of your problem is that you are not using compositional patterns correctly. Instead of changing the model of these items, create a NEW model, which contains these items. That way the original identity and composition of these items are preserved. This article gives a fairly balanced look at the problem (even though it is targeting ...


4

As you seem to not want to ship the code check to the customer (but seem fine to do it for the programmer) you could use assert functions, if they are available in your programming language. That way you have the checks in the development environment (and any tests a fellow dev would call WILL fail predictably), but you will not ship the code to the ...


1

I think the answer for your specific example is neither. Comments shouldn't explain what the code does. The CODE should explain what the code does. Comments shouldn't even really explain WHY it does it, that should be either obvious with even slight domain knowledge or with technical knowledge. This second part is hard sometimes though. Sometimes you find ...


7

Overview what the code is about. It may be obvious when you write it, but not two years later, so write down when this code is used in the application, why it is used and so on. Like "this code handles the situation where a user fills out a form complaining about returned packages lost in the post". Answers the question "what the hell is this code for". If ...


28

The comments you write are fine for demonstration code when teaching a new language for beginners. They're the equivalent of "See Jane run. Run, Jane, run!" But in every other settings they're not appropriate. Every habitual programmer would just be puzzled, thinking "Huh? Why are you telling me this when it's already utterly obvious what's going on? Is ...


36

Neither. Comments should not describe what code does (at the same level of abstraction as the code itself), but only why it does something Don't take this too literally, this is a guideline, if you write a short summary what a longer piece of code will do, that may be acceptable. However, comments describing obvious things like "this is an iteration" should ...



Top 50 recent answers are included