New answers tagged

-2

The constructor would run when you call "new Chapter3(); " in your main method. The constructor was never executed in the above code, so value of A remained unchanged. Refer : http://topjavatutorial.com/java/constructor-in-java/


-2

In a class you want some default code run every time in program that time you can use constructor.like this code public class HelloWorld{ public static void main(String []args){ demo d=new demo(); d.display(); } } class demo { demo(){ System.out.print("Hi"); } void display(){ System.out.println("HEllo"); ...


0

I may say that the issue isn't fixed but is closed as non-reproducible. Yes but I still couldnt understand this line: " In the case of a non-static method becoming static this will cause the interpreter to read a value of the stack which isn't guaranteed to be valid." Most likely the point is that in the case of static method top cell of the stack is ...


-2

Constructors are for creating objects and they execute with object initializing. Here in the code you are initializing 'A' inside constructor but never created. public class Chapter3 { private static String A; public Chapter3(){ A = new String("hello!"); } public static void main(String[] args){ Chapter3 obj = new ...


-1

You have two implement two interfaces: Iterable and Iterator. Let's say you have a class named MyOwnIterableThing which is a wrapper around some source of objects of type Stuff. That source could be a file, a database table or even a data stream. public class MyOwnIterableThing implements Iterable<Stuff>, Iterator<Stuff>{ @Override ...


0

In Objective-C, all object references are optional. Because of this, code like you posted is silly. if (variable != nil) { [variable doThing]; } Code like the above is unheard of in Objective-C. Instead, the programmer would just: [variable doThing]; If variable contains a value, then doThing will be called on it. If not, no harm. The program will ...


0

In addition to the other answers, the other major advantage of Optionals when it comes to writing clean code is that you can use a Lambda expression in the event that the value is present, as shown below: opTr.ifPresent(tr -> transactions.put(tr.getTxid(), tr));


1

"New Items" simply show up as Product@######## It's normal. The default toString() method is being invoked. Invoking the toString() method on an object returns a string that describes this object. By default, it returns a string consisting of the classname of which the object is an instance of, an at sign (@), and the object's memory address in ...


-3

Constructor is a special member that is used to create an instance of class. It is required whenever you want to pass parameters or or to access required values inside a program.These kind of Constructors are termed as "Parameterized Constructor". Constructor is used in almost every Object Oriented Concepts.For example, Constructor Chaining is done in ...


3

A constructor is for creating Objects. But main and the field A are both part of the Class Chapter3, not of any Object of type Chapter3 (that's what static means). You never called a constructor, so the code initializing A never ran, and A remains uninitialized. There are more problems with this code (e.g., a constructor normally should set Object ...


-1

The "factory" class with lots of static CreateXXX() methods is misguided. There are cases where some (OTHER) form of factory is useful. For instance I use factories to enable mocking object instantiation for unit testing.


0

As the question is tagged with Java I will focus on it in the answer: The main reason for these classes were that Java did not have any simple method of passing a function as a parameter (e.g. C(++) has pointers to functions). One good example for when this is really annoying is a generic sorting method. The only way to pass a custom comparison method to ...


5

Objects are models. They don't have to correspond to real-world objects. Sometimes actions need to be modelled. Take, for example, the typical Bank Account Scenario, that is used in many introductory OO courses. The design that is taught looks a bit like this: class BankAccount { Money balance; void deposit(Money amount) { balance += amount; } ...


4

An Optional brings stronger typing into operations that may fail, as the other answers have covered, but that is far from the most interesting or valuable thing Optionals bring to the table. Much more useful is the ability to delay or avoid checking for failure, and to easily compose many operations that may fail. Consider if you had your optional variable ...


1

Consider the following method: void dance(Person partner) Now let's look at some calling code: dance(null); This causes a potentially difficult to track crash somewhere else, because dance was not expecting a null. dance(optionalPerson) This causes a compile error, because dance was expecting a Person not an Optional<Person> ...


0

An Optional<T> allows you to have "failure" or "no result" as a valid response/return value for your methods (think, e.g., of a database lookup). Using an Optional instead of using null to indicate failure/no result has some advantages: It clearly communicates that "failure" is an option. The user of your method does not have to guess whether ...


2

There are a couple options that present themselves in this case. The first, is the properties file. Its location is somewhere and typically in the class path. Typically, you will see it coupled with the getResource family of calls. Properties prop = new Properties(); prop.load(this.getClass().getResourceAsStream("stuff.properties"); Now, if you don't ...


-3

if(optional.isPresent()) { The obvious problem here is that if "optional" really is missing (i.e. is null) then your code is going to blow up with a NullReferenceException (or similar) trying to call any method on a null object reference! You might want to write a static, Helper-class method that determines the null-ness of any given object type, ...


3

You will normally keep your tests in a separate folder hierarchy as they usually aren't part of the binary you ship, and it's just simpler to not mix them up, but you keep them in the same repo and branch because they belong together in source. As for where you work, TDD means Test Driven Development, which means you first write a (small) test for the ...


6

The basic workflow for TDD is commonly known as "Red; Green; Refactor": Red: Write a failing test Green: Modify the code to make that test pass (without any existing tests failing) Refactor: Tidy up the code to better incorporate the change. There are numerous resources that explain this process in details, eg The Cycles of TDD It's unclear to me as to ...


1

I assume these are really constants, not configuration values - i.e. they don't change between invocations or deployments. In that case I'd store it in Java files - no complicated parsing from the config file, you can leverage type safety etc. Your approach with enums is fine for a lot of cases, but the problem here is the number of attributes - enum ...


2

The tests aren't there to ensure you write the code you want to write. They are there to ensure that three years from now, you don't accidentally change the way the code works through a seemingly unrelated change, causing unintelligible defects. Tests are insurance against the future. Never remove the tests.


3

Let me give you an example: class UserRepository { User findById(long id); } It's quite clear what is this method intended for. But what happens if the repository doesn't contain user with given id? It could throw an exception or maybe it returns null? Second example: class UserRepository { Optional<User> findById(long id); } Now, what ...


9

Optional harnesses the type system for doing work that you'd otherwise have to do all in your head: remembering whether or not a given reference may be null. This is good. It's always smart to let the compiler handle boring drugework, and reserve human thought for creative, interesting work. Without Optional, every reference in your code is like an ...


8

It highlights the possibility of null as a valid response, which people often assume (rightly or wrongly) is not going to be returned. Highlighting the few times when null is valid allows omitting littering your code with huge numbers of pointless null checks. Ideally setting a variable to null would be a compile time error anywhere but in an optional; ...


0

So if I understand correctly the difference between the 2 solutions is really just in serving the 1st page if the external API is down: solution 1 is serving a generic (thus potentially useless) page solution 2 is serving a customized page (but with potentially stale cached info) Both solutions will fail subsequent requests if the external API remains ...


2

Component packages As for the component packages - this approach is usually called vertical folder (directory/package) structure and is common for larger projects. Structure of component Naming conventions are a little bit untraditional: Interfaces prefixed with capital I - this is C# convention, not Java one. In Java, interface is named without I - in ...


19

You're confusing immutability of reference to object and immutability of the object itself. They are separate things. laptop.memory is just a reference (pointer) to the object. This can be modified, i.e. you can change the reference to point to a different object - which is exactly what you did - you created a second String object containing "2GB" and ...


0

Both controller layer and service layer expose certain interfaces. Interfaces define contracts on how the interface should be used. Contract usually means which arguments (and its types and values) are expected, which exceptions can be thrown, which side effects are created etc. Now, your validation is essentially enforcement of the contract of controller ...


1

This is a difficult problem. Maybe we can simplify it? Problem with standard paging is that you typically need to know how many are there results in total - so that you can display links to page 1, page 2 ... page X. Maybe you can simplify the UI so that you only have "next" link to the next page - customer doesn't see the total number of results (because ...


0

Input should be checked in service layer. And "Can't find id" is logical error condition. So should be thrown from controller layer. This again depends on your layering / design. What a service layer is supposed to do and what is expected from controller layer.


0

It could be easily misinterpreted, so I would avoid using it like this. Probably the best option is to use a lambda function to merge the two actions you need into the forEach call. You may also want to consider returning a new object rather than mutating the existing one - it may be slightly less efficient, but it is likely to result in more readable code, ...


4

You are correct, "peek" in the English sense of the word means "look, but do not touch." However the JavaDoc states: peek Stream peek(Consumer action) Returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream. Key words: ...


1

You're going to need an overflow area, perhaps a stack, or some chunk of memory. You'll also want to get the generated code correct before optimizing it, because optimizing broken code is basically impossible. So , given a stack, you should have something like: PUT b,2; Push b; Put b,7; Put c,3; ADD; Pop b; MUL and if using memory, PUT b,2; Store b @1; ...


4

I was wondering what is the state of the Java standard regarding heap allocation. It only takes a couple of seconds to actually grep the text of the Java Language Specification for all occurrences of the words "stack" or "heap" and inspect those, so the answer is not really hard: it doesn't say anything about stack or heap allocation. And why would it? ...


22

A software is real time not when it is as fast as possible, but when it is guaranteed that a process completes within some determined time slot. In a soft real time system, it is good but not absolutely necessary that this is guaranteed. E.g. in a game, the calculations necessary for a frame should complete within the period of a frame, or the framerate will ...


2

From wikipedia: A key characteristic of an RTOS is the level of its consistency concerning the amount of time it takes to accept and complete an application's task; the variability is jitter. The important thing is that jitter is quantified for the system to be considered real time. The article goes on to say that if the jitter is usually bounded, the ...


1

As I understand your question, this is the Bridge Pattern. See https://en.m.wikipedia.org/wiki/Bridge_pattern "The bridge pattern is a design pattern used in software engineering which is meant to "decouple an abstraction from its implementation so that the two can vary independently".[1] The bridge uses encapsulation, aggregation, and can use inheritance ...


1

That's the Strategy Pattern. If you're looking for names, I'd suggest CrawlerStrategy JsoupCrawlerStrategy JauntCrawlerStrategy Actually, I'd go with ICrawlerStrategy, but that's just because I'm a .Net dev. :)


0

I would argue IntentService is not a framework implementation of the command-executor design pattern, because it does not meet the requirement of the separation of application logic and application context. The command-executor pattern is like providing a button on a remote control to replay some action(s) on-demand (dim the lights, close curtains, turn on ...


0

data provided by an user is somehow incorrect and could cause my domain object to get into invalid state. So a subclass of DomainException extends RuntimeException is thrown. Perfect. Now: how should I handle this? Suppose my endpoint is used by a frontend and I want to display a proper message to user. Catch the runtime exception at the fault ...


4

I'm going to respectfully disagree with Michael here, and some rather smart programmers, like Rich Hickey, tend to think along the same lines as me. The key here is that you take care not to pass this data structure all over the place, but you use it as a base layer from which you build the sort of abstractions that Michael talks about in his answer. These ...


0

@Groostav, answering rather than commenting so I can say a bit more. Interesting post. Since I asked my question, I made a bit more progress, so have a bit more perspective. I think Id try to initially use something standard like YAML or JSON. Then if you feel you are stretching the boundary of what the config management system can do, only then would I ...


1

I'm actually in the process of debating exactly this. My issue is that I want to give our users really pretty YAML documents to edit by-hand and then load back into our software --something akin to what CircleCI does with their circle.yml file. We're on the JVM and SnakeYAML is a very nice YAML serializer/deserializer, so I can simply add it to my project ...


2

There are already some good points, but I think I can add some further thoughts on the matter. If Java doesn't provide a feature that C++ has, it means that the feature is not good, so we should prevent using it. This has been pretty well answered: Java isn't "the good parts" of C++, nor is there any reason to think so. In particular, though the ...


13

This is a dumb, stringly typed data structure. It is a: List of Maps keyed by String of Maps keyed by String of Local date array This makes it difficult to create, traverse, and could very well get you into code that looks like: foo.get(1).get("bar").get("qux")[42] And guess what... you've got a null pointer exception that was thrown on that ...


1

Whether or not you use generic parameters as @DavidArno suggests, your interface should probably be written in terms of other interaces, not in terms of classes. It is perfectly reasonable for an abstraction of concepts to require several interfaces. But an interface that consumes and returns classes is probably not fully abstracted. So, keep going until ...


2

In certificate chaining, you are essentially allowing the issuer of certificates to validate your certificates on your behalf. The GoDaddy certificate in this instance is your Root Certificate Authority and validates the identity of the Root CA. They also will issue you an intermediary certificate to represent your organization as well and this is just ...


4

The type system can do many things for you, but even the best type system cannot do everything. There is no problem with having several methods with the same type signature but different contracts. Look at it this way: if everything could be expressed machine-verifiable via the signature, we wouldn't need programmers - just spec writers and compilers. The ...


2

What all these methods have in common is that the update to multiple properties is only atomic if everybody updating the properties uses the same method, but also everybody reading the properties and wanting them updated atomically reads the properties using one of these locking methods. Your chances improve mightily if instead of having multiple ...



Top 50 recent answers are included