Tag Info

New answers tagged

1

To ensure safety both threads must go and acquire the lock before messing with the data of student. If one thread doesn't do that then it's like neither thread acquired the lock. Part of acquiring the lock is waiting until no other thread has the lock.


3

What happens when a thread acquires a lock? No other thread can acquire that lock until it's released. Note that this is all that happens. Only methods called via other threads are affected. Only other threads that compete for the same lock are affected at all. This means that the holding thread can do whatever it likes, just as before the lock. ...


0

Do all the classes really need access to the entire object? Otherwise, this looks like a correctness problem (but not in a bad way), rather than a design problem. One approach is to consider a code contract enforced by a caller: f(g, exchange-object) { /* pre-condition/invariant */ assert(exchange-object.open() == true); g(exchange-object); /* ...


5

Don't use null, use Optional As you've pointed out, one of the biggest problems with null in Java is that it can be used everywhere, or at least for all reference types. It's impossible to tell that could be null and what couldn't be. Java 8 introduces a much better pattern: Optional. And example from Oracle: String version = "UNKNOWN"; if(computer != ...


1

Try running the following: public static void diceRolls(int dice) { List<Integer> chosen = new ArrayList<Integer>(); diceRolls(dice, chosen); } // private recursive helper to implement diceRolls logic private static void diceRolls(int dice,List<Integer> chosen) { System.out.println("Entering diceRolls with dice="+dice); ...


3

You may imageine backtrack as if you were walking through a dungeon and you must explore all the paths in the dungeon (the dungeon is acyclic - you will never come back to the same place regardless the path you choose). When you come to a place which forks to multiple paths, you choose only one and follow it. Only after you come to an end, you go back to the ...


-1

Just follow it line by line, and when you hit a function call imagine copying and pasting the entirety of that function code in its place. Therefore chosen.remove() will be called after the previous function calls have ended and therefore the other chosen.removes shall be called prior to it. Google how to use a debugger put breaks in your work and then ...


9

Your code actually sports not one, but three antipatterns: log and rethrow; rethrow without wrapping the original cause; log only the message and not the stacktrace (this is the worst one). If you followed the best practice to: not catch at all (let the exception propagate on its own); if forced to catch a checked exception, wrap into unchecked and ...


0

Short answer to "when to use Java serialization" and "when to avoid Java serialization" Use Java serialization if few coding should be necessary it doesnt matter that binary data is not human readable searching in serialized data is not neccessary (database-like query is not possible) either serialized data structure does not change or it doesn-t ...


0

I'd say it depends mainly on this question: If someone needs to extend the functionality of Item and ItemStackFactory, will they just overwrite methods and so instances of their subclases will be used just like the base classes, just behave differently? or will they add members and use the subclasses differently? In the first case, there is no need for ...


0

I think that using generics in your situation is too complex. If you choice generics version of interfaces, the design indicates that ItemStackContainer< A > contains a single type of stack, A. (i.e. ItemStackContainer can't contain multiple types of stack.) ItemStack is dedicated to a specific type of item. So there is no abstraction type of all kind ...


3

Your code has a bug: assuming mShowsAdapter is a List or similar collection, when mShowsAdapter.size() == 0 there is no element at index zero, because there are no elements at all. If you change the condition of your test to the following (note the comparison operator), does it solve your problem ? if (!mShowsAdapter.isEmpty()) { item = ...


0

I like this builder. Do you really need a Builder in your case ? Liking a pattern is not enough to justify its use. Upto 4-5 arguments, creating instances of your class directly by the constructor greatly simplify your code, plus allows you to make your class immutable. public final class Example { private final String first; private final ...


0

There are other options. You could use a Singleton where you only initialize the static instance if you call getInstance(). MathUtils.java public class MathUtils { private static MathUtils mathUtils; private MathUtils() { //initialization logic here } public static MathUtils getInstance() { if (mathUtils == null ) { ...


1

Do it both ways. Make one new Java class to match as closely to the original C as you can, using static variables in the same way the C code does. In most cases do a direct one-to-one translate of each line of code. Even use the same loop types, parameter names, method names and variable names and even keep the gotos. Test that code to the maximum ...


2

Now, Item and ItemStackFactory I can absolutely foresee some third-party needing to extend it in the future. There's your decision made for you. If you do not provide generics they will need to up-cast to their implementation of Item every time they use: class MyItem implements Item { } MyItem item = new MyItem(); ItemStack is = createItemStack(item, ...


6

Your plan of how to introduce generality to your interface appears to be correct to me. However, your question of whether that would be a good idea or not requires a somewhat more complicated answer. Over the years I have interviewed a number of candidates for Software Engineering positions on behalf of companies that I have worked for, and I have come to ...


5

You use generics in your interface when your implementation is likely to be generic as well. For example, any data structure that can accept arbitrary objects is a good candidate for a generic interface. Examples: List<T> and Dictionary<K,V>. Any situation where you want to improve type safety in a generalized way is a good candidate for ...


4

Like Basile said, 4K lines is a small program. It should be relatively straightforward for you to puzzle out what it does and how it does it.1 You said this was a simulator of some sort; I'm guessing it acts as a server or client to some other process for testing purposes. We have similar tools for testing our software - the simulator stands in for a ...


2

According to Java Docs: About nextInt() Scans the next token of the input as an int. If the translation is successful, the scanner advances past the input that matched. This method consumes the integer, but not the new-line character or other character after that integer. So after consumption of integer by nextInt(), there only remain newline ...


6

short answer: you don't. You can get user input without using a Scanner instance. For example: https://docs.oracle.com/javase/tutorial/essential/io/cl.html or http://alvinalexander.com/blog/post/java/java-source-code-read-command-line-input


34

The answer is "because a scanner has state." Looking at the code for java.util.Scanner, you will see a number of private fields such as a buffer and its associated information, a Matcher, a Pattern, an input source, information about if the source is closed or not, the type of the last thing matched, information about if the last thing was a valid match or ...


1

Naturally, the correct procedure would be to do it the right way, Java is an OO language after all, but whether you should mimic the current coding style or do it the right way an OO programmer would is not up to you, but up to your lead. Therefore discuss with your manager first, if they want to keep the structure as is, or make the code more agile ...


1

I see no reason to port the code from a procedural language to an object oriented language without making the code object oriented. Do you just wish to be able to write procedural code in an object oriented language? Object oriented code is a step forward. Procedural code in an object oriented language is for the least not forward if not exclusively ...


1

It seems you want to achieve two things: Create a Java program instead of a C program, and have an improved structure. Both represent work. However, it is less work to convert a C program with a good structure to Java than a badly structured C program. And improving the structure is easier with a known working application, so you can make one improvement, ...


12

A 4Kline long C program is a small C program. It generally needs a few weeks or months to be written by a single person. If you are familiar with the domain of the program, you should be able to understand it entirely quite quickly, and write a tiny documentation describing the design and purpose of the original program (in particular, the communication ...


1

One solution to this problem I've used in the past (where a large number of decorators add facilities to a relatively simple base, with many possible interfaces) is to have a base class for both the decorators and the classes they wrap, regardless of interface they implement, that has a method declared (using Java's syntax): public <T> T ...


2

For a good definition of Test Driven Development, I suggest you read Doc Brown's post. Here is how I would answer a similar question: All three practices are not mutually exclusive and can be combined into the larger software development process. Developing based on User Stories in iterative development cycles (Agile) does not exclude the engineering ...


0

TDD means writing unit tests, before writing the code. Your unit tests are the documentation, and they dictate the design. Integration tests is testing how group of modules integrate together. It comes after unit testing. Agile methodology is the way you organize your process, in order to faster respond to requirements changes. That usually means ...


0

The other developers do not want them as Enums because they don't want to have to add a .value to the enum every time they want to use the constants, feeling it's too verbose and thus cumbersome. This is easy. The other developers' objections aren't simply differences of opinion; they're factually wrong. You can statically import the enum constants to ...


2

Ask yourself this, if you separate out the members into separate classes, are the classes doing any meaningful independent work? If the classes are co-dependent, and can do nothing without access to the other members then its probably a bad idea to separate them out. On the other hand, if one class can meaningfully lessen the workload of the other class or ...


2

Creating interfaces for single values may make sense if you want to create a very robust API, which should endure even if requirements change, or if you are not sure how the values will be implemented (will id be a String or int? Will description be simple String, or an object with more structured data, such as group, textual note, comments). Generally, it ...


0

There are many considerations around class design, intelectual control, cohesion, future extensibility of the application, etc. My reccomendation on class size is focus on good functional cohesion and let the class size be what is natural. But, consider this variation on option B( or A?): you have broken down your business logic in to discreet functions ...


1

The type of cohesion your describing is not really the best example of where you would use package access. Package is handy for creating components, modules that are interchangable on an interface. Here is a rough example of a scenario. Suppose your code was reorganized to be more around functional cohesion and componentization. Perhaps 3 jars like: ...


0

I'm against having large classes, even if all the methods are related, it makes more difficult to understand the code. So I vote for the [B] approach, where you pass the parameters to the constructor and the class implements an interface. This way, you can treat all classes as if they were of one type (interface type). You can handle the business logic ...


0

As always, it depends. I don't see why would it be wrong. I had classes with as many fields, maybe even more, in a project which scrapped data from a website, so one page was one object (lots of data + some calculated values to speed up things across multiple runs). They were perfectly related to each other. If fields contained in one class have little to ...


1

It's not all that useful, especially as a default, in a world where people tend to use the dotted names of packages as if they were sub-packages. Because Java has no such thing as a sub-package, so x.y.internals has no more access to x.y than it does to a.b. Package names are either the same or different, a partial match is no different from having nothing ...


15

I guess it comes down to which is the greater evil, too many Objects or too many fields in an Object. It depends. The greater evil is having classes do too many things or too many classes for one thing. In your example, it looks like you have three distinct groupings that have nothing to do with each other. So those shouldn't be the same class. But if ...


5

The important figure is complexity, not pure object/member count. You can have a simple class with roughly up to 20 members (that's already really smelly, though), and you can have a much too complex class with only five. Anyway, just grouping members by type won't help. The questions are: Which members have to work together? And, which sub-services can ...


0

Easy. Pass the table name from Book (and all other concrete classes) into a constructor of the abstract class. Store the table name in the abstract class and use it directly where needed. Remove the getTableName method Sorry my answer is so brief, I'm editing in the mobile app.


2

Sometime i escalate the visibility of private or protected methods to package to allow a junit-test to access some implementation detail that should no be accessed from outside. since the junit-test has the same package as item-under-test it can access these implementation details example public class MyClass { public MyClass() { this(new ...


1

It really depends on the context in which you want to invoke those functions. [A] assumes that the arguments of your method are always well known in the section of code you wish to invoke it. You should use a static method for these types of stateless calculations. [B] assumes that the arguments/state of the code is different depending on some other ...


2

Throughout the java.util.* package there are instances where code is written with package level protection. For example, this bit of java.util.String - a constructor in Java 6: // Package private constructor which shares value array for speed. String(int offset, int count, char value[]) { this.value = value; this.offset = offset; this.count = ...


1

I think you can adapt the visitor pattern for your requirement. Your Book class should implement an interface, typically named Visitable. public interface Visitable{ public void accept(Visitor visitor); } Now, to your book class you pass in a visitor which performs the necessary operations. Implement this method in book class. public class Book ...


0

This would work if you dropped all the statics from the base class, and the abstract from the method with an implementation. Think of how the methods would be called by clients: either aBook.dropTable() or Book.dropTable() makes sense, but DatabaseObject.dropTable() doesn't; which table did you want dropped? Doubtless there are better ways to do things, ...


3

I want to be able to iterate over these strings as if they were an enum in one location, but everywhere else they are used just as constant strings. So define a list (or vector or array), load the necessary items into it and iterate over that. If you really only need it in one location, define and load it there. If there's a chance that you might want ...


1

Yes. Whether or not you need to use enums is a different story, but: If you use both enums and String constants you will need a way to keep these values in synch in your code. The enums you are iterating over need to match the constants used by your peers. Maintaining this code is going to be difficult. Someone at some point is going to come along and ...


1

Even with modern persistence frameworks, queries are very often composed of lots of String concatenation (JPQL) and different kinds of query building templates (JPA Criteria). There is also need for native queries in some circumstances. Grouping all of this in a separate layer may still make the code more readable than scattering it through the service ...


1

If memory serves, the reasons for developing the technique of encapsulating members with accessor/mutator pairs are due to some historical problems associated with maintenance and quality control. As a programs grows, is maintained, and new features added, some of the particular problems are: A bug emerges where the value of the member is incorrect, but ...


3

If you need to pass only the URL, then pass only the URL. No need to over think it. There are several disadvantages of passing the whole object: the performance cost of json serialization and deserialization weaker encapsulation and weaker information hiding: the source fragment reveals more information to the other than necessary If you only need to ...



Top 50 recent answers are included