New answers tagged

2

With absolutely no prior knowledge of the specific case, I would guess: performance. Given a function with a fixed set of parameters, a compiler can optimise how those parameters are laid out in memory, and even optimise the entire function to a fixed set of processor instructions. A generalised implementation instead needs machinery for detecting the number ...


2

I can't see anything wrong with this. There's even precedent: for example, the String class has equalsIgnoreCase and contentEquals. So if you have a class such that two instances could be "equal" in more than one way, just create the methods that you need.


1

Short answer: It is too easy to just "try catch swallow" everything in java*. Where in Rust and Go, it's much easier to just write good error control code 'correctly', and make it hard to do poorly. i.e., "Falling into the pit of success" programming paradigm. I strongly suggest you read Joe Duffy's blog on error handling strategies, ...


0

Philip Kendall's response to the above post refers to an extremely important(!) element of this picture – which really should have been presented as an "answer." Namely: "because I haven't written the code yet." In lots of practical software-engineering situations, "the source-code is perfunctory, as long as it fulfills the ...


1

The idea is to compare the spectrogram of the voices. I'm not sure if there are proper libraries that you can use directly, but the basic steps would be Filtering the audios Applying a band-pass filter (e.g., Butterworth) to remove the unnecessary frequencies (ref on voice frequency range) while keeping the main waveform. Determine the background This is ...


5

Black/White -box testing refers to whether or not the internals of the code under test is known to the tester. Black-box testing tends to be more high-level, possibly based on a high-level requirements document. User-acceptance testing is one form of black-box testing. White-box testing is more low-level. It might be based on a detailed design document, and ...


-1

I fixed this "feature" and created this project https://github.com/leonardofel/JSON-java-put-null-fix making the following code bellow possible: String v = null; JSONObject j = new JSONObject().put("myPreciousNull", v); System.out.println(j.toString()); prints: {"myPreciousNull":null} just works !!!


-1

For VScode, need to: Enable java.debug.settings.hotCodeReplace Make sure java.autobuild.enabled is not disabled for VSCode Java


1

One way to design this in a scalable way is to implement a publisher/subscriber mechanics ( for example, utilizing java.util.Observer, or by utilizing a stored lambda expression) in the UserRepository. This will allow to send a notification to an observer object (or just call the injected lambda function) whenever the UserRepository.update method is called. ...


0

The main point I would raise is that the above is not OO at all. Having data structures and procedures (services) is arguably exactly the opposite of OO. Second, please ignore SRP and SOLID. Because those (with the possible exception of L) are not well enough defined, they can't help you. Third, coming to the problem at hand, you are using a type marker (...


0

To avoid that, it's necessary to retrieve the user's existing entity just to fill in the password digest, so that updateUser(newUser) won't affect the user's passwordDigest There is an alternative that maybe you want to consider. An existing entity can be updated in a more controlled way: void updateUserGeneralInfo (User newUser) { User oldUser = ...


2

While Christophe's answer addresses the actual question about the random reading of the text files, I think there is a XY problem here. You have a set of chess puzzles structures in a form of a text file. And so you're asking how to read a random line from this file. Your actual question should instead be how to load a random chess puzzle, given that ...


5

CSV files and many other text based formats encode information in a potentially variable size. Due to the variable record size, there is no way to directly jump to a random record if you don’t know its precise position in the file. To get some randomness in your app, you could imagine to go to a random offset in the file and move forward or backward to the ...


4

Sometimes such classes would be named as Base- or Core- to indicate that they are to be extended in other implementations, so you'd have CoreBoard and CorePiece. Depending on the language you're using, you could also use namespaces to distinguish between the two sets of classes. You could have a namespace for the Engine, and other namespaces for specific ...


4

There are some good points made in other answers, but I feel each picks out a different aspect, so I'm going to try to bring them together. Checked vs unchecked errors The idea of statically checking code is to make "bad" programs impossible to write. In other words, it places constraints on what the programmer can do. Those constraints have a ...


-1

The problem with using always the return value approach is that often the developers end up mixing business logic and error handling. Beyond return values, error handling could be about: Resource handling, closing access to files or database connections, even though this point was later addressed with the construct try/with resource Transaction handling. ...


1

Yes, it does. Some of the other answers are down too deep in the details of what abstract does in Java to get at the underlying concept that the term comes from and its essential purpose. Ironically, that's an example of not seeing the forest for the trees, i.e. lack of abstraction. Here's a more relevant definition of abstraction from Oxford Languages: the ...


3

checked exceptions can be seen as syntactic sugar for alternative return values This is the modern perspective on this language feature, but the feature was initially intended and used for a different purpose, at which it failed. Checked exceptions were added to the Java language before its initial release back in 1996. Back then, Java aspired to be a more ...


-2

Of course they are related. Abstract methods, together with abstract classes and interfaces, hide the implementation from the client. At this level you no longer care about how something was implemented, but only what it does and what's its result. Now, how this is used in OOP and what you gain from it is a different story. Abstraction is never an end in ...


3

It is somewhat related, but not as you think: An abstract class is a class that cannot be instantiated, and an abstract method is a method that has no implementation. The principle is that an abstract class needs to be specialized by a class that implements its abstract methods, before it can be used to really create objects. So it's not hiding unnecessary ...


2

No, it does not. Those are two different things. In Java, the abstract is a language keyword, which can only be placed on methods in classes also marked abstract. If you do this, then such class cannot be instantiated directly (you cannot create a new instance of it using new) and the abstract method must not have implementation. If you wish to provide the ...


0

Abstract classes and members are one way of achieving polymorphism in Java and other similar object oriented languages. Polymorphism is at the root of creating abstractions. Polymorphism allows many kinds of objects to be treated the same way, while the implementations remain hidden from those using the objects. This certainly "reduces complexity by ...


22

Disclaimer: This will, to a degree, be my own personal take on the problem. I love programming language design, I've thought, read, and discussed a lot of about PL design in general, and the hard topic of errors in particular. This gives me some experience, and also an appreciation that beyond objective factors, there is a lot of subjectivity at play. I will ...


-2

Awkward typing The type winds up being T with a type union of A, B, C. This is an odd type that doesn't work best with other things, for example Generics There isn't a good way to do a generic with variadic check exception. Classes In Java, every exception must extend Throwable with a stack trace. You could invent solutions to these, and you'd likely wind ...


12

Checked exceptions can't be treated as just another part of the expression. They must be handled out of line. With an error return value, you can write a function that converts error values to a default value, for example. Something like this (even if the variant type has no getOrDefault method): setNumber(getOrDefault(parseInt(stringValue), 0)); With ...


1

There are of general ways a client can use a timestamp in the response: It can help identify issues with incorrectly configured system clocks It can help with identifying latency issues The other thing I would consider here is what you will do when supporting a client when they get an error like this: [client] I got a 500 error. [you] when? [client] In ...


0

Note that composition as a software design term is used almost exclusively in an OOP context, to set it apart from inheritance. The word just means "collect things to make a bigger something". In an OOP context however it stresses a particular approach to class design: combine several objects in a container object opposed to adding functionality ...


8

There are three parts to error code: Code that generates the errors. Code that handles the errors. Code that just propagates the errors from part 1 to part 2. Most programmers don't give part 3 much thought, because most "enterprise" languages use unchecked exceptions where the part 3 code is essentially invisible. In error propagating code, you ...


1

The first scenario seems a good approach. By default, the method getCar should just return the Car object without the Engine (as it is set to be fetched lazily). If the controller needs the Car and the Engine, an option is to provide an additional method CarService#getCarWithEngine. Such a method, will explicitly load and return the Car with the Engine (see ...


0

The only reason why Java even has primitives is performance. If objects would be equally fast during processing and require equally little memory, everything would have been an object, even int. Ruby and Smalltalk, for example, only know objects. In these languages really everything is an object, even a simple integer value. This means they will never be as ...


39

From a scientific point of view, checked exceptions can be seen as alternative return values, e.g. Exactly. They can be seen that way, and they should be but they aren't. Using an Error type like is common in Rust, Elm, Haskell, and in some sub-communities in Scala or a special error value as in Go is just an alternative return value indicated in the type ...


3

Yes. More precisely, this is called object composition: you compose a more complex object which access its components using their known interfaces (i.e. the operations defined for primitive data types). In a Java context, there's a difference between primitive data types, which have value semantic, and class types, which have reference semantic, but in both ...


1

If mixing the event publishing code with your other code is an issue for you, it might be an option to apply the decorator pattern. Instead of directly calling your implementation of the UserService, call another one which has the same signature but which is solely there to first forward the call to UserService and secondly publish the event(s). By doing so ...


2

Pass the board to the piece you want a move list from. You’re correct that the board data needs to be where the moves are. But the board is mutable so it’s a poor choice to make into an objects state. So just pass it as a parameter to a method. Speaking of immutable, pieces don’t need to know where they are. Let the board keep track of that. All the pieces ...


1

Logically, a valid move is not something determined by an individual piece, but by the application of the rules to an overall board (consisting of the current placement of many pieces), and also (in the case of castling) by an analysis of previous moves. You could dispense with the history, by keeping a separate account of castling rights, but this absence ...


0

You could refactor some repeated code like this: String[] latitudesArray = latitudes.split(","); String[] longitudesArray = longitudes.split(","); Double startLat = getStart(latitudes); Double endLat = getEnd(latitudes); Double startLong = getStart(longitudes); Double endLong = getEnd(longitudes); ...


3

It all depend on the purpose of your model: If it is a design model that aims to communicate the big picture, it would be advisable not to show any annotations: these would on’y make the big picture more difficult to grasp by adding unnecessary implementation details. if it is an implementation model that aims to be ultra-accurate, for example because it’s ...


0

There have been some good answers, but I would like to add to them. Transaction is a terrible choice of base class name as it already has meaning, especially in financial and database-centric applications. Model the real world. When I front up to an ATM I know that I want to deposit, withdraw or transfer between accounts. I don't think along the lines "...


5

You don't want BankService to know what the true type of the transaction parameter is.  It can find out by doing instanceof, but that is a red flag indicating OOP problems. However, the transaction parameter variable knows what kind of object was passed in. So, the idea is to tell the transaction object to do something for you, instead of inspecting it to ...


3

If you have execute() method overridden in each child class, you can just call transaction.execute() inside executeTransaction(), so BankService does not have to know the transaction type. However, I don't see the necessity of using inheritance here --- you can just have fundsTransfer, pinChange,... methods inside BankService class and implement them ...


0

This is an interesting question that goes deeper than it looks. Here's my view on the topic. First of all, just by looking at the two method signatures, I can tell that the semantics and behaviour are different, so picking one or the other is not just a stylistic choice. In particular, the second form has a built-in side-effect of writing the result of the ...


0

Who cares about memory usage for a single variable of type int? Nobody. But there is one huge difference if your code is a bit more complicated: If there are situations where the code inside the loop misses initialising temp then it will without any warning use the value of the previous iteration. If this happens only rarely then you have a very hard to find ...


-1

If you do a 1000-2000 loop using the two methods, you will find out that declaring it outside is more economical and better optimized. Reason being, re-initialization of the variable in the loop leads to creation of memory location (different ones) for the variable. The extra workload and time lag that is given to the code for the reallocation of memory for ...


1

The challenges with shared code between services is merely the good old question about dependencies. There is no right or wrong here, but a balance and tradeoffs for the path you choose. And this path I would argue is quiet significant in software development. A shared libary is a dependency. Dependencies can have a bad rep' because they have a tendency to ...


1

Neither. Your services aren't microservices. You have unfortunately created a "distributed monolith" or "hidden monolith". Your services aren't loosely coupled. A change in one service will probably result in a change in another service. Often this will require simultaneous deployment of multiple services. Your services aren't loosely ...


-1

Have a look at FlexiCore, an open-source framework that brings modularity to spring boot utilizing plugins(jars) loaded at runtime See wizzdi and FlexiCore. for example FlexiCore allows you to create a project ( compiled into a seperate jar from your main application) that contains a spring bean as follows: @Component @Extension public class ...


Top 50 recent answers are included