New answers tagged

5

Use an identifier that has an explicit name. Validators with explicit names make your code so much more readable: instead of BusinessGroupA having validators 'v1', 'v2', 'v3' and 'v4' the CustomerOrderGroup is validated by the NoOutstandingPaymentsValidator, SufficientCreditValidator...


0

Perhaps the class you're looking for is the Runtime class. The Runtime class allows you to run other programs from within the Java VM. For example, you might want to write a program which lists all the files in the current directory; rather than implement your own solution, you can just run the dir command on Windows or ls on Linux-based systems.: Process ...


1

Summing up pros and cons of the proposed answers: The problem with the global helper file is the lack of flexibility, for example, in an application I have various enums with a specific enum constant that I would like to have a very specific key, not following the common format. The problem with locating the logic in the enums is the replication of code, ...


9

Recursion limit hits are indicated by corresponding messages and a recursion can easily be rewritten as iterations. This makes detection and fix easy. Recursions are typically used in situations where the recursion depth is low. As Ordous pointed out -Xss parameter can be tuned to address borderline cases. Deep recursive calls should be avoided. Tight ...


-2

There is no controversy on that page. It's Oracle telling people to use checked exceptions. The fake 'controversy' that they have invented here is between the language designers and the language users. The designers allowed people to throw and catch things that (in their mind) should not be thrown or caught. So they created a web page complaining about lazy ...


2

I'm a Linux user and what I do is as follows. I have a folder named cheatsheets, and under that I have folders for topics like bash, java, css, html, sql, etc. I save each code snippet or cheatsheet in it's own text file with a pertinent name. Then I made a script based on the locate comand that helps me find the cheatsheet I need. Besides that I just do ...


0

Your doing what is called 'downcasting'. You can do this in C++, however, it's not recommended (imho) because of the various baggage that C++ has that Java doesn't. Direct downcasting (like the example above) will 'slice' off derived data when cast to the base class. To avoid this, you need to use pointers. RTTI. This is a feature where you can determine ...


1

People have different ideas of RAD - in fact, it's a rarely used phrase these days. Technologies like Spring Roo are great for prototyping, but not usually used for commercial apps. Once your app has a certain degree of customisation, Roo is more trouble than help. Technologies like Hibernate or Vaadin - which some would call RAD - are widely used in ...


1

Within the Android environment, the answer is the SparseArray that is an optimized structure for the <Integer, Object> type structure. The primary advantages of are the lack of boxing (all keys for a Map must be Objects rather than primitive) and the lack of the additional Object that is the key. A key reason for the creation of this is its lower ...


0

You'd use a map if you want to choose the index. Something along the lines of Map exampleMap = new HashMap<String, HidDevice>; This would allow you to use a string as a key to obtain the value.


2

In addition to @Jules very good answer: Perhaps you are thinking about the decision making at too low a level. Remember, you are trying to provide a useful and complete abstraction to clients/users/callers. So, one way to frame the question is, do you want clients/callers to have an API that is about: recipes that have some relationship with a ...


0

I figured this out eventually. Hopefully this will help others in the future. What was needed was a way to interrupt the deserialization process and run some custom code to extract the data. SimpleXML allows you to use many different strategies for serialization / deserialization. I chose one called the Annotation Strategy where by I annotate my POJO model ...


10

Your option 2 is usually preferred. Option 1 violates the common guideline known as the "Law of Demeter" -- it means that your main program now knows in detail how your Recipe voting works, which makes it harder to change that if you decide to do it another way later. This is an example of unnecessary coupling, which we usually try to minimise.


0

Replace every occurence of "_" by "-" in the locale string when you receive the parameter and let the logic expect only "-".


3

There are two legitimate reasons to DIY that I can think of: It simplifies your life. A custom solution can fit your needs exactly whereas trying to incorporate a 3rd party approach can sometimes be more work than it's worth. Eliminating/Avoiding dependencies. I really think developers in general don't put enough weight into this. There are costs to ...


0

I think the Builder pattern may help you. public class ConfigBuilder { public void SetPropertyA(string a) public void SetPropertyB(int b) public GeneralConfiguration Build() } The UI may interact with the methods exposed by the ConfigBuilder object. Once the user is OK, the Build method will be invoked to determine if ConfigA or ConfigB will ...


0

Yes, it's possible, but why do you feel the need to? Reflection has its uses, to be sure, but with Great Power comes Great ... Opportunities to Shoot Yourself in the Foot in New and Exciting Ways (and just when you least expected it, too). That aren't that many things that actually need Reflection, so I would suggest that if you find yourself reaching ...


1

While there are lot of reasons to use Spring (I've never worked with guice so can't comment on it) they aren't always important for any given project, and it's therefore a good idea IMO to at least consider DIY DI for each new project. That said, I end up with more Spring projects than those without. My most common reasons for using Spring are: declarative ...


3

Yes, this is not k only possible but actually quite common. You can create your own byte code and feed it to a ClassLoader instance to turn it into a Class object and then use reflection to create and manipulate it. There's a library called cglib that's commonly used to make it easier, and many frameworks and libraries (eg Spring and Hibernate) use this ...


5

When Java encounters this + operator, it compiles the addition to byte code, specifically an iadd instruction. What the computer does when executing this instruction depends on how the virtual machine on which this program is executed was programmed. It might delegate to an ADD opcode from some processor's instruction set. It might consult an internal ...


1

Just a hunch, but are you writing unit tests? Many small classes over a few large ones become more valuable as you test your code more thoroughly and from more levels of mocked out, unit environments or production-like environments. I don't think having a large number of classes in Java is a problem or is unusual, but I am concerned that you feel so ...


3

Is 20 Java classes for just making... This is entirely the wrong question. Something is wrong or you wouldn't be asking. It sounds like you're looking for something to blame. Anguishing over the number of classes isn't going to fix it. I've felt this same pain before. You step back and look at everything. It works. You can kinda follow it. But you ...


5

I would use a JSP every time. Why? Low-level programming HTML is a slow and error-prone operation. I've done this in C++ on an Arduino board, and I'm glad it was a hobby project.There is no way I could charge commercial rates for the small amount of functionality I produced. A JSP is very close to the HTML it emits, and so is easy to maintain. There are ...


0

You should take a look at the JAX-RS spec and do a tutorial. I like running Jersey but there are many implementations. Do not reinvent the wheel and try to build a RESTful interface using hand-rolled servlets. This will make building your REST interface a snap. Integrating to Hibernate is just writing the code to do your queries. The JAX-RS spec allows ...


2

I'll give you an example first (but at the very end is the answer why the controversy). Let's suposse you are editing a document in a Java-based document editor and after you are done you choose File->Save as... and you chose to save the document into a volume you don't have write permission on. The Editor wouldn't crash on you with an ugly stacktrace, it ...


0

However, it also seems that everyone does it and it seems to be good practice. Yes, everyone does it indeed, so it's a practice, but is it still good? Several people are questioning that: http://mnapoli.fr/approaching-coding-style-rationally/ (The Exception suffix § context: php) the linked video, https://vimeo.com/album/2661665/video/74316116 (skip to ...


3

An old sage once said: You usually don't create an interface for every class, that would be an afterthought. You create interfaces as a design exercise, then you create classes that implement those interfaces. You have to think that what you are creating is always a foundation upon which someone else can built some bigger. Don't create little programs, ...


3

Interfaces exist (speaking of the interface keyword), so you can define an API for classes, where the implementation does not matter, only the arguments, return types and maybe thrown exceptions. You should treat classes and their public methods exactly the same, whether they implement an interface or not. Once you realize that, you will see even a class ...


-1

You don't need need an interface for every class. What I do is create interfaces for injectables and implement newables without interfaces http://misko.hevery.com/2008/09/30/to-new-or-not-to-new/.


0

There are multiple ways to handle code reuse in Perl. A lot of examples do not make clear the distinction between the approaches and many classes use at least two. I advise using OO style as much as possible and only use the EXPORTER when you have at least three or more classes that need a relatively small cluster of utility functions. So: package Foo; ...


1

I think you should export your project as a regular jar file and not as a runnable jar. That way your plugin client just need to know what method to call just like when you use an API. The only difference is that that method will open a Window etc.


3

Why do you want to "mention" anything in the manifest file? What does the documentation of the software you're writing the plugin for say about what it expects in the manifest? Most likely, you can just leave out the Main-Class header or even omit the manifest entirely.


3

There have been languages that, as you suggest, provide only a single datatype and then have operations where the expected encoding of the data is provided as part of the operation, rather than being determined by the type of the variable as it is in most modern languages. The best known of these was probably B, the predecessor of C (in fact, C can be ...


8

Let's forget for the moment that processors have specific hardware for manipulating byte sequences of a particular size. Let's forget for the moment that processors have specific hardware for operating on specific interpretations of byte sequences (floating-point registers, SEE registers, etc). What good does this abstraction do from a user perspective? ...


1

You are correct that numeric types are just patterns of bits. But processors are optimized for certain operations on certain patterns of bits. For example x86 processors have registers of sizes 8, 16 and 32 bit, arithmetic operators corresponding to these sizes, and memory is addressed in chunks of 8 bits, known as bytes. There is no support for 19-bit ...


8

So why did all those programming languages decided to provide multiple built-in data types Because the built-in types like int, float, byte and char are used in almost all use cases – and it turns out that standards are a convenience for everyone. If everyone used their own variant, writing code that uses libraries with different types, exchanging data ...


11

Because processors have operations specifically for ints, and specifically for floats. The compiler has to know what operation to target. And I mean, even if you had adding for a series of bits, adding 0110 and 0001 have very different meanings if 0001 is treated as a float rather than an int - not to mention actual operations required to calculate it. And ...


0

Based on your option 2, why not simply do this? If you want to prevent use of the raw base you can make it abstract: class Vector2 extends Vector { public Vector2(double x, double y) { super(new double[]{x,y}); } public double getX() { return getComponent(0); } public double getY() { return getComponent(1); } }


1

The best way to do it is to do it in two distinct steps. Pseudocode: function IterateMap(myMap as MapType): var myList = new ListType() for key, value in myMap: if IsBadKey(key): myList.Add(key) else: Process(key, value) for badKey in myList: myMap.Remove(badKey)


2

On android you can use AsyncTask (the equivalent of SwingWorker). It has 3 methods you can override, doInBackground for the work you want to do in the background thread, onPostExecute called on the UI thread with the return value of doInBackground after it returns, and onProgressUpdate also called on the UI thread in responce to calls to ...


0

There's a simple way to do this: You set up an object with the synchronized data and share it between the threads. You can then write the data or check for it from each thread. So, you'd have an instance of a class that looks like this: public class Shared { private boolean signalSent = false; public synchronized boolean isSignalSent(){ ...


-2

i think you can do this using common method in both the thread , for example 1 thread can get the input from the user and process on that and successfully processed than it update the common method and 2 thread continuously check the common method if it is updated or not if it is updated than it start process on that.


0

I would do the following: Remove the second function with the String as second parameter. Call device.setName(deviceName) before calling attachDevice(device). It is not the responsibility of the attachDevice method to set the name of the device. Change the attachDevice method to add the device to the genericDeviceMap if it has a name, as shown in the code ...


0

The problem with static singletons is not the global state per se, it is that they are usually used for shady things. One of the most common examples is is a database connection. Static singletons are wrong for one main reason: you can get an instance of an instance the singleton wraps anywhere in the application, in any class, without ever letting a user ...


0

"One of the problem of using the singleton pattern is global state" If you use it for global state then you can do so. But that does not affect the "singleton pattern" itself as it is answering the question how many instances of an object there may be: One. "global" and "state" do not adress the question "How many instances may be there?". They adress the ...


0

You have two options: 1. Polling - Your application calls the database You should have modified_date column in the database. In your java application a scheduled thread should query the database depending on that modified_date; if there are results then update the cache. Something like this should do it: while ([...]) {//or better scheduled executor ...


0

Usually you should not update the cache instead, you should invalidate it whenever there is an update to the content. The get operation should always check content in the cache, if there is a miss it should contact the database to get the content and update the cache.


0

It's actually pretty simple, a Synchronized version will do just fine, it will make all access to the list safe EXCEPT in the case where you need to iterate over it. If you need to iterate over it, there are a couple ways. Create a copy of the list then iterate over the copy (Note this will only copy the list's pointer array, not the objects in it--pretty ...


1

If it is a little confusing to you, it's a problem. Someone unfamiliar to the code (which will probably be you in 2 months) will be utterly baffled. From the look of your code, you are letting yourself in for a lot of boilerplate. You might be best served looking at a single problem and saying "What's the simplest thing that could possibly work" and ...


4

To answer your questions directly: 1) No, it will not affect performance much. Generics are mostly erased by the time the program gets executed anyway, so the additional cost is really only multiple (up to 3) map lookups instead of 1. I would not expect this to ever be a bottleneck in a scenario where usage of a standard HashMap is acceptable. 2) Not ...



Top 50 recent answers are included