Tag Info

New answers tagged

0

I often prefer standard and good enough over best. There could be a "less is more" argument for using the included Java Logging: http://docs.oracle.com/javase/6/docs/technotes/guides/logging/overview.html


3

When the compiler enters a "new scope", new variables within that scope are stored for that scope, and when the scope "disappears", those variables disappears. This is, normally, done in the form of some sort of stack/list type, which in turn holds the variable names and their type. So, if we have: int x; void func() { float x, y; int a; } the ...


1

Why can we use the same name for local variable in different scopes? Each method has its own set of local variables. The compiler converts these local variable names, in essence, to per-method unique numbers (stack frame offsets). After compilation the names of local variables are lost (disregarding some of the newer reflection APIs). Local variables ...


0

If you use the Maven Assembly Plugin, you can include the slf4j jar (along with whichever implementation you prefer) inside your deployed jar. There are more complicated options if you want to allow users to choose the logging library, but it will run perfectly well if you make a fat jar with or without the slf4j implementation. Users are much more likely ...


2

Coding to the SLF4J API doesn't force the dependency on users of your library. From the user's guide: As of SLF4J version 1.6.0, if no binding is found on the class path, then slf4j-api will default to a no-operation implementation discarding all log requests. ... Embedded components such as libraries or frameworks should not declare a ...


2

It's usually a good idea to separate the serialization method (JSON) from your business logic so that if in the future you decide to use some other type of serialization, you can do so without affecting the business logic. Jackson is probably the most popular open-source library for JSON serialization/deserialization in Java. In the situation where some ...


0

Using a single Timer and an unbounded ExecutorService (thread pooling) for this type of general-purpose scheduling can be very powerful. However, it does not stop concurrent execution of the task, should the previous invocation not yet be completed. We've combined Timer and ExecutorService just for this purpose, along with the ability to restrict the ...


-1

// IMPORTANT: NOTE THAT THIS IS A PACKAGE PRIVATE CONSTRUCTOR OurData(/* I don't know what they do */) { // some stuff } If the package private constructor is a major obstacle, you can still create an instance of their class by making a class of your own in their package. I know it feels dirty but it works. This class could be a subclass of ...


-1

More than three arguments (polyadic) requires very special justification--and then shouldn't be used anyway. Wow! We do not work on the same code bases. Inversion of Control frameworks - like Guice or Spring - essentially strive to make this half of your problem, a pillar of design. Many arguments in constructors is totally fine. Seriously, a typical ...


8

You really have two separate concerns here: wrapping an API and keeping the argument count low. When wrapping an API, the idea is to design the interface as if from scratch, knowing nothing other than the requirements. You say there is nothing wrong with their API, then in the same breath list a number of things wrong with their API: testability, ...


1

I think you might be interpreting Uncle Bob's recommendation too strictly. For normal classes, with logic and methods and constructors and such, a polyadic constructor does indeed feel a lot like code smell. But for something that is strictly a data container that exposes fields, and is generated by what is essentially a Factory object already, I don't think ...


9

The strategy I've used when there are several initialization parameters is to create a type which just contains the parameters for initialization public class DataTypeTwoParameters { public String foo; // use getters/setters instead if it's appropriate public int bar; public double baz; public String quuz; } Then the constructor for ...


1

It all comes down to risk management and gut feeling. Try to estimate the following: How big are the costs of the mistake as it is in the code right now. Does it cause recurrent costs? Or costs in form of a risk that it might turn into a bug in the future? What is the cost and the probability of that bug? How big are the costs of fixing it right now: Risk ...


3

It may be a good idea to encapsulate behavior into a Java enum (or C++ enum class) when you find yourself writing switch statements like the following, especially when the switch is repeated in different parts of the code. MyEnum x = ...; switch (x) { case A: // Do something break; case B: // Do something break; case C: // Do ...


4

A simple fix would be to replace the internals of your wrapper to use Threadlocal. So the format() changes from: private DecimalFormat format = new ...; private final Object lock = new Object(); public String format(double value){ synchronized(lock) { return format.format(value); } } to private ThreadLocal<DecimalFormat> format = ...


4

I use enums this way all the time. Enums are a great way to write immutable helper objects that you only need exactly one copy of; they help reduce the chance of memory leaks and easily group many related classes together in a clear way. What I would not do is expose the control of which particular BusinessLogic you're using to external classes using a ...


0

An abstract class mean that some parts of its implementation may be missing. IMHO, the fact that a Gauge may be useless on its own is your opinion, not the opinion of all the users of your API. I would only declare such a class abstract if it lacked important methods, but never as a mean to prevent the user from instantiating such an object. First, I would ...


0

From my point of view, yes it is. The only question is, do you want a class, or an interface is enough? So the question will be: do you have common behaviour (method implementation) between child classes, so you need a common abstract class, or just method declaration (in this case, better use an interface)? D.


1

Usually Abstract classes are used when one has a class which has some methods which needs to be implemented by one of its child classes, thus, when one sees an abstract class one also expects to see a series of abstract methods which must be implemented. So although you can use abstract classes to denote non instantiable classes, I do not think that if you ...


4

NaN has a very specific meaning as the result of an undefined numerical operation such as division by zero or taking the square root of a negative number (within the realm of real numbers). It's not an appropriate return value from code that parses a floating point number. Code like that should signal an error when it comes across text that can't be ...


1

In addition to the good answer by @Doval, throwing a NumberFormatException is more general: it works for similar methods like Integer.parseInt(). There is no NaN equivalent for ints, shorts, etc. So, throwing a NumberFormatException is both more specific/informative than returning NaN, it is also more generalizable. That's truly a win-win!


1

This lets you easily detect the cases where the input is completely nonsensical. You can parse the string "NaN" and get NaN, so if the user wanted to give you NaN, he could type that. The fact that you received "ABC" means they weren't even trying to enter a double at all.


-1

All the seemingly random numbers floating around the code should have some name associated with them so they make sense. It should also be reorganized. Things like stats for different objects should be grouped together instead of being defined globally in the main. I would make a base class that contains all the different stats, separate from any individual ...


2

Yes, too many or too complicated mock objects are a bad thing. Yes, there is a better design, and I have been toying with the idea in my mind for years. Unfortunately, I cannot fully explain it here because the paper that I am writing about it is not complete yet. But, in coarse terms, here is what is happening: You are mixing business logic with GUI ...


0

The Final products which you want to create are 1) Remote control Unit 2) Front Panel 3) Buttons on Setup box So, I think the situation is not highly dynamic. (May be in future you may have to add one more type of new device.) so, with Factory Method / Abstract factory we end up with parallel creator class hierarchy. This approach of creating objects ...


0

It is possible that your mistake is taking a too fine-grained approach to access. Are you certain that each user of your class will have different access? Perhaps your actual problem is that you should be implementing a Role mechanism where only a user with a specific role can have access to certain methods. A Role mechanism can be implemented using ...


2

You cannot do exactly what you want - see the other answers, but there are a couple of things you could do. You could have a package private interface that exposes the setters, and a public interface that exposes the getters. You mention that you want to use the setters in multiple packages in your own code. Why is this? This is a code smell for me - if ...


0

There are many ways to do that in Java depending on your specific scenario. By one hand, we could start analyzing if access modifiers could help in this scenario. For instance, in Java the package can be used to modularize your code. package a; public class A { private String foo; public String getFoo(){ return this.foo; } void setFoo(String ...


7

That cannot be done. Your problems arise from violating ISP. That said, the only idea I can think of is to force client classes to register with your classes in orden to be able to call their methods or they get a NotRegisteredException. Once they register you can check their type and rise a YouAreNotAllowedToCallThisMethodException if the registered class ...


5

Hiding inherited methods is a terrible idea and almost guaranteed to cause you grief. I would say that this is what Interfaces are for; a "disclosure agreement" between two or more classes that accurately describes what each is allowed to know about the other[s]. Of course, this will get just a mite fiddly if its mixed with inheritance as you describe - ...


1

You can use JPA with inheritance. There are several variations ("patterns"): all objects share the same table and there is a "discriminant" column/attribute (this is the closest to the one you explain). It is quick for queries, but you will have a column for each attribute of a subclass (if you have 20.000 instances, and only two instances of a subclass ...


0

For me, the main difference in using one or more than one repository are the answers to the following questions: Are the multiple parts developed by the same team, have the same release cycle, the same customer? Then there are less reasons to split the one repository. Are the multiple parts highly dependent on each other? So splitting model, controller and ...


-1

I did a quick microbenchmark regarding this and I have provided full sources in github. My conclusion is that whether creating objects is expensive or not is not the issue, but continuously creating objects with the notion that the GC will take care of things for you will make your application trigger the GC process sooner. GC is a very expensive process ...


1

If you want a drop-in replacement of HashMap/TreeMap, then MapDB is what you're looking for. It has features such as transparent serialization to disk and multiple caching strategies (intelligent algorithm you've mentioned). Also you may consider doing all the work inside the DB, using stored procedures and temporary tables. It might be faster, because of ...


-2

You can use recursion to remove index-1 elements from the beginning of the queue, store the the first element and then, as you are unwinding the recursion, put removed elements back on the queue: public static int get(Deque queue, int index) throws Exception { int tmp = queue.removeFirst(); try { if (index == 0) { return tmp; ...


0

After more research I concurred with our group that for this particular application, some form of JSP technology was the correct answer. These were some of the main points: ASP to JSP is not a huge paradigm shift and are someone similar in my opinion. I read that JSP's came from the ASP concept originally. JSF has a steep learning curve and it's hard to ...


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


2

This is why: This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely ...


0

Further to class level unit tests, what's in my opinion perhaps a more grounded test and pragmatic approach is to execute all the critical/high value execution paths.. identify and create a metrics (of criticality) for your end user's minimum required critical functionality set - invoke these functions/operations at (increasingly) much higher level than at ...


0

I have always found if you put tests into the running code, even in production (ones that do not degrade performance), gives you more results for your testing money, than the heavily isolated unit tests that are currently in fashion. The tests I speak of are based on the design of each method and class. In each important, externally accessed method: Test ...


5

I'm assuming that the input that your code receives is the string representation of the function anyway, so there's no avoiding a string checking. There is, however, ways to avoid some of the other problems you've noted. I would go with your option #2, with the following caveats: Shared code should be shared Rather then extending Function, create an ...


0

I would like to give a more clear picture on understanding the concept of Mutable and immutable class. Mutable means whose value can be changed reverse is true for Immutable as already told. Actually whenever you are calling constructor of any class we are actually allocating a memory space of that type of variable in heap. for e.g String str1 = new ...


2

Since the Safari browser for Windows is horribly outdated (the latest download is from May 9, 2012), it is not a reliable browser to use as test and compare with the Mac version. On a project I am working on, we found there where to many differences between the Mac / iPad version of safari and the Windows version, so we decided it was worth to buy a Mac ...


0

Keyloggers require tight OS integration to work as the typical user would expect them to work. While you can technically write a Java keylogger, all of the real work would be done in JNI at the C layer. For example, in Windows you need a keyboard hook which is all done in C. This allows the program to grab keystrokes regardless of the current focus or what ...


-3

It is possible but you probably have to use JNI to intercept keystrokes.


2

Anything that is worth printing at all is worth printing to the logs, since the whole point of logs is to record as much detail as possible about what happened during execution. As with any other program, by default the user should see only a small subset of the output that's likely to be useful and relevant to him. Due to the nature of your program, you ...


2

The fact that you are writing a console application doesn't change good UI practices. Your business logic should be distinct from your UI. The business logic performs the operations and indicates what might have gone wrong. The UI decided how that should be displayed. If there is information that is useful for tracking the execution of the application ...


2

Your architecture should look something like this: Data source <--> Data source driver <--> CRUD interface <--> Application You'll need one data source driver implementation for each type of data source. The CRUD interface will be the same regardless of data source. Note that you can have more than just CRUD methods. You might want to ...


3

If you've already used JSP in part of your application, don't rewrite it into a different framework. Chances are, the team you're working with already has some knowledge of JSP, and you'll be able to build on the existing core of pages that utilize it, limiting the amount of work to be done and the subsequent number of bugs needing squashed. Remember your ...



Top 50 recent answers are included