Tag Info

New answers tagged

2

Couple of points. Since you already know about ANTLR you will probably already realise that your internal representation is going to be an AST, or something very near. Using 'new' all the way is messy. Better to use factories, for clarity of code. Yes, you will need a parser but it's nicer to get things started by building the AST directly. Then you can do ...


0

Your question is about code organization (as specified in the title) and many here seem to be talking about VCSs, that might not solve your problem at all. You do not seem to need version control, your problem seems to be something else. Basically what's been happening is we end up working on the exact same thing, or we write code for components that ...


1

How is it going to be used? I think you need to look at it terms of the client code's usage patterns. The code for a calculator app probably doesn't actually include much if any complex formulas. So the problem you are trying to address doesn't really come up. Something that a calculator app would want to is to be able to build a map of names to function ...


4

Speaking at a high level, I would perhaps build the interface so that option 1 is the "native" way to build your expression tree. Additionally, option 4 could provide an optional interface that offers a much more succinct notation. The result would be exactly what would be manually generated using option 1.


0

There are a couple of things here that need to be addressed. First, there is the two code bases. You've got your code. Your friend has his code. Wen you do a merge (somehow) you're doing it without the ability to see the changes that did it before. You don't need github to do this. You could have a master git repo on a thumb drive, and then merge to ...


1

I have recently been deeply involved in the Java portal server scene. It was chosen as an inexpensive alternative to SharePoint, as we were able to find a portal provider carrying comparable features. We went with eXo Platform and though it is primarily advertised for social features, it is fully compliant as a JSR286 portal server. A Java portal can be ...


1

The composition approach (including another Tokenizer in DefaultTokenizer) will be easier to modify in the future. If possible, you shouldn't allow the Library*Tokenizers to be subclassable at all. That said, as long as the rest of the code can only reference a DefaultTokenizer through the Tokenizer interface you'll be able to change how it's implemented ...


-1

Yes, getters and setters is an anti-pattern in object-oriented programming and should never be used: http://www.yegor256.com/2014/09/16/getters-and-setters-are-evil.html. In a nutshell, they don't fit into object-oriented paradigm because they encourage you to treat an object like a data structure. Which is a major misconception.


6

You are missing option 3 (and more). Don't have a DefaultTokenizer. There is no value, and it leads people to make choices that reduce maintainability later. Additionally, the problem can be solved with sensible documentation. Reasons not to have the Default: you actually can't change it later, because people expect the default to be a specific ...


0

There are three general ways of signaling error condions to the caller of methods -- exceptions, error codes, mutating error object that is passed in as a parameter. The problem with error codes is that if the method is a function, they only work well if you can fit them within the natural return values (ie negative indexes) or the language (such as ...


4

Yes, throwing exceptions is a good idea. Throw them early, throw them often, throw them eagerly. I know there's an "exceptions vs. assertions" debate, with some kinds of exceptional behavior (specifically, the ones thought to reflect programming errors) handled by assertions that can be "compiled out" for runtime rather than debugging/testing builds. But ...


1

In general, yes, it is a good idea to "fail early". However, in your specific example, the explicit IllegalArgumentException does not provide a significant improvement over a NullReferenceException - because both objects operated upon are delivered as arguments to the function already. But lets look at a slightly different example. class PersonCalculator ...


1

It's a valid usage, I tend to use the static block when the initialization may throw checked exceptions: private static final Cipher cipher; static{ try{ cipher = Cipher.getInstance("AES"); //initialization which may throw }catch(Exception e){ throw new RuntimeException(e);//rethrow as unchecked if it fails -> will stop the ...


0

Failing as soon as possible is great when debugging an application. I remember a particular segmentation fault in a legacy C++ program : the place where the bug was detected had nothing to do with the place where it was introduced (the null pointer was happily moved from one place to another in memory before it finally caused a problem). Stack traces cannot ...


0

In your example function, I would prefer you did no checks and just allow the NullReferenceException to happen. For one, it makes no sense to be passing a null there anyway, so I'll figure out the problem immediately based on the throwing of a NullReferenceException. Two, is that if every function is throwing slightly different exceptions based on what ...


1

As far as I know different programmers prefer one solution or the other. The first solution is usually preferred because it is more concise, in particular, you do not have to check the same condition again and again in different functions. I find the second solution, e.g. public void registerPerson(Person person){ if(person == null) throw new ...


0

Not in the examples you give. As you say, throwing explicitly isn't gaining you much when you're going to get an exception shortly thereafter. Many will argue that having the explicit exception with a good message is better, though I don't agree. In pre-released scenarios, the stack trace is good enough. In post-release scenarios, the call site often can ...


16

Yes, "fail early" is a very good principle, and this is simply one possible way of implementing it. And in methods that have to return a specific value, there isn't really very much else you can do to fail deliberately - it's either throwing exceptions, or triggering assertions. Exceptions are supposed to signal 'exceptional' conditions, and detecting a ...


0

To summarize: It looks like the only complexity comes from using improper configuration methods (yes, XML is not type-safe) and possibly also from frameworks doing much more work (Spring manages the object lifecycle, which goes far beyond DI). For a simple project, DI doing right is extremely useful: it allows to write services as tiny immutable classes ...


4

The most common way to handle updating messages without a redeploy/restart is via database or similar system like the file you proposed. Another option is to add functionality to the app itself to change messages, this would make use of the properties file. Using a database is probably the best approach, especially if you already have one set up for your ...


0

Obviously the message needs to be defined outside the application, so the simplest solution is to put it in a file. But you don't want to read a file every single time you want to display the alert; that's a lot of unnecessary IO. You can use Java's Watch Service API to check if the file containing the message has changed, otherwise you can continue ...


3

If just allocating objects for your smaller test cases are using several GB of RAM, and many small objects, you are right to worry about your larger cases. I would sit down and think carefully about your data needs for a larger test case. If it is pushing what you are comfortable with, I would radically restructure your program. For inspiration, read ...


-3

For very deeply nested loops or complex code flow, I often declare anonymous Runnables. While not directly related to the question, it is still relevant. I'm sure there is a better example than this, but it's a start. public int ComplexFunction() { final Integer value = new Integer(); final Boolean quit = new Boolean(false); final Runnable ...


2

As others said, in Java its generally better to use lot of short methods, because they are JITed and inlined better. But it's plausible that in EE enviroment situation can be different. At least for method that are not simply called, but there is aditional overhead because of 1) Transaction handling, 2) Interceptors 3) EJB remote calls (stay away from ...


0

If you have a file that is prepared for double-sided booklet printing, it will always contain a multiple of 4 pages (as there go 4 pages to a sheet of paper). These pages are also ordered in the same way. The very first page goes to the very back of the book The second page goes to the very front of the book The third page goes to the front, just after the ...


1

Dynamic Language Python is probably a better choice than Java for such an application, given its relative simplicity and less need for boilerplate code and operational middleware. I don't know about the IDLE console for Python 2, but IDLE for Python 3.4 handles Unicode characters well (I just tested it), as does Python 3 overall. Nicer IDEs such as Komodo ...


3

The JVM have this thing called JIT, which would optimize the application's code with various techniques. One of those is called "inline optimization". In this particular optimization, the JIT will automatically inline methods when needed, so, you might lost some processor cycles in this particular instant, even if it does, it's not sufficient to justify ...


5

It's probabbly an wrong assumption, first as common sense nested calls shouldn't have any (measurable) performance hit at all. After doing some research you'll find that the JVM can do some optimizations in your code "automagically": Adaptive Optimization And more importantly: Inline Expansion As you can see: In computing, inline expansion, or ...


6

Your example is specifically dealing with checking that the calling code is conforming to the contract. If that's the case then the hurdle style is typically cleaner and easier to read, usually because you will throw an exception so there's no expectation that there's some other piece of code lower down in the method that will miss being executed. There is ...


15

Your first “hurdle” style is superior in any respect. It saves you many levels of indentation. This alone makes it much more straightforward to understand. It's diff friendly: Adding another constraint doesn't require you to re-indent all your code. Validation is located at one place – at the top of the function. With the other style, it is before and ...


1

If you're looking to write an elegant plugin class that gets called by the formatter to handle special cases, I think you're out of luck. However, the next best thing is to handle special cases for a specific class. The Formattable interface allows you to output text given all the information made available in the format string. The example they provide ...


0

1 is a library that generates JavaScript code for you that performs AJAX gets/posts to your server and invokes methods. You will still have to write this code if you're building Ajax Enabled Web Site, even if you don't go with DWR. 2 is an architecture. I am not familiar with this DWR and cannot comment further. Maybe it can be implemented with RESTful ...


1

If you want to modell your classes by the single responsibility principle (SRP), you have to make up your mind what these responsibilities are. When you want to use your Employee class in a salary payment application, then the CalculatePayment method is perfectly right in that place. The Employee represents an employed person which for sure has a name. ...


1

When are getters and setters justified? When the behavior "get" and "set" actually match up to behavior in your model, which is practically never. Every other use is just a cheat because the behavior of the business domain is not clear. Edit That answer might have come across as flippant, so let me expand. The answers above are mostly correct but ...


1

Firstly, I believe following OOP SOLID Principles, calculatePay() method should not be an employee objects responsibility... Am I right in thinking this way? Yes and no. That behavior should not be the responsibly of the employee, but not because of any programming or design principle. It is because no company in the world lets their employees ...


1

For your first question, Strategy Pattern might be best solution. Each concrete strategy would be related to concrete employee type. But you should have separate employee types if different employees have different behaviors. For your second question, it is similar situation as I answered here : Is this a violation of the Liskov Substitution Principle? If ...


2

I would use composition to model this problem. There are more classes this way, but the classes are better segregated. A person has a role. A role has a salary. If the company changes the way that pays are calculated it requires changes in the PayCalculator. If the definition of a person is changed, it only requires change in the Person class. If a ...


4

As long as calculatePay() is as simple as in your example, and as long as it does not need any parameters more than members from Employee, I would leave the method where it is. But when calculatePay() becomes more complex, and it needs information from outside the Employee class (like information from the employer, about taxes, actual date, etc.) I would ...


1

Advantage of A: You make clear, under what condition you want to do something: house != null && house.getLounge() != null && house.getLounge().getLetter() != null That is the condition. And you want to get a value and set another value. String myValue = house.getLounge().getLetter(); textView.setText(myValue); So in terms of ...


0

"Write once, debug everywhere" is a fatalistic reality of all cross-platform languages, tools, and applications. Be it Java, JavaScript, Python, HTML, or whatever. Even for environments like Java, Unix, Linux, and HTML that are designed to be "used everywhere," there are enough variations from implementation to implementation to require testing, and often ...


0

Version A is self-describing. It aims to do exactly what it says. Looking at version B taken out of context, I have no idea if the defense is supposed to be against house being null or textField being null (because, maybe, it's available on some layouts and unavailable on some other layouts - this would not be strange when dealing with android resources). ...


2

Given the scenario you've given, I would go with implementation A. In both implementations, the case where house is null or house.getLounge() or house.getLounge().getLetter() return null is handled. One problem with implementation B is that it treats a NullPointerException that could happen in any of the methods called, which is an abnormal occurrence, as ...


1

Adding the file deletion to the Java program has the drawback of making debugging hard, assumed the Java program does not behave as expected and you want to reproduce the behaviour with the original input data. If the Java program is called from the shell script, it will make sense to add the deletion part to the script, since in this case the script knows ...


2

I am big fan of stupid tools. I want my hammer to hammer and my screwdrivers to screw. If I use grep, I want to find something, but I don't want it to be able to e-mail me with the results. If I wanted that, I could pipe it to some other tool that would do that. Likewise, you have a Java program that can do anything imaginable. Why exactly wouldn't it ...


8

One of the most popular design pattern here on PO is the strategy pattern. And yes, if you build some example code around this pattern, you can demonstrate all the SOLID principles: S = is fulfilled when each strategy subclass is only responsible for exactly one task, and the "context" class does not take responsibilities which belong into the strategy ...


0

The question is: where should I log the exception? I want to log the exception only once Log the exception only once, namely at place where it gets handled (not rethrown). This is the place where you have the most information. so I was thinking about do the logging stuff inside the constructor of EngineRuntimeException class itself. Is that a bad ...


1

If you don't mind having another library dependence, you could use AspectJ to log any exceptions that derive from EngineRuntimeException with the following declaration: public before() throws EngineRuntimeException: mypointcut() {...} The reason why this method is preferable is to decouple the logging from the actual exception itself. You could of ...


0

In my opinion solution depends how complex your testing environment is. Solution no1 looks simpler and you are able to use import static to simplify it even more this way you follow kiss principle Also solution no1 performs better as you do not need to create another stack call on thread that takes place in solution no 2. However solution no2 seems to ...


2

There are two arguments for using accessor methods instead of public variables: Access Control: A method allows us to publish only a getter method, or to add value-based (in contrast to type-based) constraints on a setter. With public final identifiers, this point is irrelevant, as that value can't be changed, and invariants therefore can't be broken by ...


4

Since N can be as large as 10^12 it should have been clear that iterating from 1 to N is not the desired solution. The key insight is that the recursion can be rewritten as V(i) = M * V(i-1), where V(i) = [RR(i), MM(i), PP(i)] (a column vector) so V(0) = [ 3 1 0 ] and M = | 1 0 3 | | 1 0 2 | | 0 5 0 | Now V(N) = M^N * V(0) We can ...



Top 50 recent answers are included