Tag Info

New answers tagged

1

You are adding a ridiculous amount of complexity for no apparent benefit: implements means what is implementing that interface is a relationship, that is pretty tightly coupled and introducing Adapter pattern type indirection is going to bloat the codebase with more complexity and code to maintain and test, which is a good enough reason to not do that. If ...


0

Meet BoxPong, a very simple game I made to get acquainted with object-oriented game development. Making BoxPong helped me formulate, among other things, a fundamental question: how can I have objects that interact with each other without having to "belong" to each other? I have quite a bit of experience writing code for the SNES, where you have ...


3

In general, it turns out very badly if objects of the same level know about each other. Once objects know about each other they are tied, or coupled to each other. This makes them hard to change, hard to test, hard to maintain. It works out much better if there is some object "above" that knows about the two and can set the interactions between them. The ...


0

It's about communicating your intent of how the object should be used. For example, if your method expects a Map object with a predictable iteration order: private Map<String, String> processOrderedMap(LinkedHashMap<String, String> input) { // ... } Then, if you absolutely need to tell callers of the above method that it too returns a Map ...


-1

Quick Short Answer Yes, Programmers can apply the Object Oriented Programming without "Classes". Long Boring Extensive Descriptive Answer There are several variations of "Object Orientation", altought, the first concept that comes to the mind of many programmers is "Classes". Yes, Programmers can apply the Object Oriented Programming without "Classes", ...


0

Not always: it depends on the language. You've demonstrated the ability to do this in Python but (if your question is meant to be language agnostic despite the Python tag) not all languages can do this. Java, for example, mostly can't. Ignoring the class that contains main, there is no way to define arbitrary methods/fields on an object defined within main ...


5

Of course you can! The Self programming language is a dynamic prototype-based object oriented language in which everything is an object and there is no sense of classes or whatsoever. It's focused in the idea of prototypical objects and the idea of cloning them instead of having classes as templates of how to create objects. You should check ...


2

How does one express this notion in natural everyday language? To make it short: class inheritance describes a family of objects. In language terms, think of nouns. Think of: vehicle, cars and bikes. interface inheritance describes a set of unrelated objects, sharing common behaviour. In language terms think of adjectives. Think of: able to ...


2

Extending a class is not necessarily "code inheritance". If A is an abstract base class or an interface, then making B a subclass of it means it only inherits the interface of A. If A is concrete, then B would inherit the interface and maybe some code, depending on what B chooses to override. So I believe the correct answer to your question is that ...


1

First 3 options break Liskov's substitution principle. Fourth one complicates the interface for the client. Personally I think the easiest solution would be to declare the getAmount() method that it returns always string - then it works with both integer-based and GMP-based implementations. Alternatively this might be a case of premature optimization - ...


37

Congratulations! You rediscovered the well known fact that object orientation can be done without specific programming language support. It is basically the same way objects are introduced in Scheme in this classic text book. Note that Scheme does not have a class keyword or some kind of equivalent, and objects can be created without having even classes. ...


7

I would agree that the first definition satisfies the three points your teacher made. I do not think we need the class keyword for anything. Under the covers, what else is an object but a data structure with with different types of data and functions to work with the data? Of course, the functions are data as well.. I would go even further and say that ...


1

It really depends on the structure of your neural network. For example this: Fig 1 can be modeled easily with 4 array lists since there is no interesting information in the connections. However, this: Fig 2 would require construction of an object graph. A key decision to make is which end of the arrow is knowledge of the other layer going to ...


0

The best way is to start with a linear algebra library that allows computation of: matrix multiplications and basic arithmetic (scaling, addition, subtraction), and matrix pseudo-inverse. (If you use a non-linear function, you might also need the partial derivative of that non-linear function - if I remember correct.) Then, you write a loop doing those ...


1

Neither is inherently better than the other. Use whichever one is more readable. In your example, where you can get all the values immediately and construct the object in a single object literal expression, I see absolutely no reason not to do just that. If getting each property was a non-trivial exercise, or there are many properties the final object may ...


1

There is no "correct" way of doing this as either will work just fine. It depends entirely upon what makes your code the easiest to write, understand and maintain. If I already know the values of object properties at the time of declaration of the object, I find it generally makes the code a bit more self describing if I just put the known properties ...


0

It's more than just whether you can mock a Brand object or not. First, I'll assume your Product is really a Data Access Object, and not a simple Java Bean/DTO/POJO. The real question to ask is, how long will this assertion hold? Assume 234 is the brand id of the brand in database. Will simple int values become long in the future, necessitating all ...


1

That is a great question and an interesting problem. I propose that you use a combination of Chain of Responsibility and Double Dispatch patterns (pattern examples here). First lets define the task hierarchy. Notice that there are now multiple run methods to implement the Double Dispatch. public abstract class RecurringTask { public abstract boolean ...


3

I would say Option 1 is the best route to take. The reason you should not dismiss it is that the SendEmailTask is not an entity. An entity is an object concerned with holding data and state. Your class has very little of that. In fact, it is not an entity, but it holds an entity: the Email object you are storing. That means that Email should not take a ...


0

I think the serialization to JSON is a web concern (infrastructure), not necessarily a model concern. So invoking a helper from the controller to do the serialization is fine, I would regard it as desirable. It handles a pretty clear concern, I think it's a valid component. The tabulation you mention however sounds like it is a model thing, I would avoid ...


4

For unit-testing the findByBrand method, there is no real difference between passing in a Brand object or just an ID. The difference is more relevant for the code calling findByBrand. In the large majority of cases, that code should already be dealing with Brand objects, so passing that as an argument to findByBrand makes the most sense. The only reason ...


0

I completely disagree with that article. Services (concretely their "API") are important party of the Business Domain and as such will exist within Domain Model. And there is no problem with entities in business domain referencing something else in same business domain. When X send mail to Y. Is a business rule. And to do that, service that sends mail ...


3

Have you had a look at existing libraries e.g. spring quartz or spring batch (I'm not sure what fits your needs most)? To your question: I assume the problem is, that you want to persist some metadata to the task in a polymorphic way, so an e-mail task has e-mail addresses assigned, a log-task a log-level, and so on. You can store a list of those in memory ...


0

In the end I decided on option 4. Have the interface specify that getAmount() can throw an exception, and have the BigAmount implementation throw one should it not be possible to express its value as an integer. Then I'll have another method that can return the amount in another format. It would require the programmer using the class to jump through some ...


0

I think in the very most cases (not all?) you can replace a case condition with a hash; at least in OOP. Because what else is the case condition than choosing the right value based on the input parameter? This is exactly what a map does: Based on a key it returns a value. But what if some logic is necessary instead of a value? Well in this case the ...


1

Replacing conditional with polymorphism (see Refactoring, Martin Fowler, page 255) is indeed the refactoring which comes into mind. You've already did it partially, by: Creating classes, one for normal price, another for the promotional one. Moving the business logic to the newly created classes. The remaining part is to: Create the hierarchy. It ...


3

There's no direct way to do what you're describing. However, you have a few options which will hopefully achieve what you want: Have an interface which contains only the accessors, and not the mutators, and make sure your return type is of the interface rather than the concrete class. Have a way of cloning a class- this might be an external method, or a ...


3

You can make the objects immutable: public class Developer { private final String name; public Developer(String name){ this.name = name; } public String getName(){ return this.name; } } Then there will be no issue with returning the reference. Otherwise you can map each developer to a unmodifiable view of itself: ...


2

This is issue of following the Law of Demeter. In first case, the Main class knows about all the other classes. If it has dependency on all of those classes, then you have to check if Main works properly if you change any of those classes + the one that is using it. If you needed to mock dependencies of Main class, then you would have to mock all of those ...


3

"Red arrows mean it create pointed class as a object and call the method of it." So you did not separate creation from usage? This is pretty much opinionated, but one "recommended" way of creating OO programs, especially when multiple classes are involved, is to make use of dependency injection. One central aspect of DI is: if one object needs another ...


-2

I know it's an oldish question, but check out ReactiveX if you haven't already. I discovered it recently, and it's really changed how I see designs like these. It's basically a combination of type-safe observables, event-based push (sync or async), and classic pipes-and-filters. http://reactivex.io/ You just write little components and snap them together ...


0

So for example, given a Customer class that keeps alot if information about the customer, e.g. Name, DOB, Tel, Address etc., how would one avoid getter/setters for getting and setting all those attributes? What 'Behavior' type method can one write to populate all that data? I think this question is prickly because you are worried about behavior ...


1

OOP is about encapsulating and hidding behavior inside objects. Objects are black boxes. This is a way to design thing. The asset is in many case one doesn't need to know the internal state of another component and is better to not have to know it. You can enforce that idea with mainly interfaces or inside an object with visibility and taking care only ...


5

Trying to expand on Kasper's answer, it's easiest to rant against and eliminate setters. In a rather vague, handwaving (and hopefully humorous) argument: When would Customer.Name ever change? Seldom. Maybe they got married. Or went into witness protection. But in that case you'd also want to check on and possibly change their residence, next of kin, ...


6

TL;DR Modeling for behavior is good. Modeling for good(!) abstractions is better. Sometimes data objects are required. Behavior and Abstraction There are several reasons to avoid getters and setters. One is, as you noted, to avoid modeling data. This is actually the minor reason. The bigger reason is to provide abstraction. In your example with the ...


8

To transform the Customer-class from a data object we can ask ourselves the following questions about the data fields: How do we want to use {data field}? Where is {data field} used? Can and should the use of {data field} be moved to the class? E.g.: What is the purpose of Customer.Name? Possible answers, display the name in a login web page, use the ...


65

The simplest way to avoid setters is to hand the values to the constructor method when you new up the object. This is also the usual pattern when you want to make an object immutable. That said, things are not always that clear in the real world. It is true that methods should be about behavior. However, some objects, like Customer, exist primarily to ...


52

It is perfectly fine to have an object which exposes data rather than behavior. We just call it a "data object". The pattern exists under names like Data Transfer Object or Value Object. If the purpose of the object is to hold data, then getters and setters are valid to access the data. So why would someone say "getter and setter methods are evil"? You will ...


0

SOLID principles are good, but KISS and YAGNI takes priority in case of conflicts. The purpose of SOLID is managing complexity, but if applying SOLID itself makes the code more complex it defeats the purpose. To take an example, if you have small program with only few classes, applying DI, interface segregation etc. might very well increase the overall ...


21

The Principle of least knowledge or the Law of Demeter is a warning against entangling your class with details of other classes that traverse layer after layer. It tells you that it is better to talk only with your "friends" and not with "friends of friends". When trying to apply principles like this it's important to understand that they are never ...


8

The principle you are talking of (better known as Law of Demeter) for functions can be applied by adding another helper method to your streamer class like { frame = encoder->WaitEncoderFrame() DoOrGetSomethingForFrame(frame); ... } void DoOrGetSomethingForFrame(Frame *frame) { frame->DoOrGetSomething(); } Now, each ...


11

Is functional design better than object-oriented design? It depends. Is MVVM better than MVC? It depends. Amos & Andy or Martin and Lewis? It depends. What does it depend on? The choices you make depend on how well each technique or technology meets your software's functional and non-functional requirements, while adequately satisfying your ...


2

Based on your update from 2015-05-18. TruckTire should be a private subclass of Tire. Tire should contain the interface other client classes (Truck, Car) use, and TruckTire encapsulates the behavior. The Truck's interface to TruckTire is the same as Car's interface is to CarTire. They all know them as Tires. Use the Strategy pattern for Tire.


1

Student, Subject and Degree are not directly related. A StudentDegree would have the knowledge and reach to know about students, subjects and their degree. A subject should not track what each student scored. A StudentSubject should. A student should have one StudentDegree. A StudentDegree has a Student, and many StudentSubjects and Degree. Now you've got ...


1

First: What is the program supposed to do? You cannot make decision about architecture without knowing the purpose of the program. Also, ignore advice from people whom you haven't told the purpose of the program :) Second: Unless you are writing an actual simulation of a college, you probably don't want objects like Student, Subject etc. to have behavior ...


2

Not all features of a class are relevant to the type of its instances: Private methods, the constructor, the destructor (in C++), and the methods' implementations. This is not usually true. In a nominative type system, nothing about the type matters but the name (and where it exists in the hierarchy if you have subtyping). As the compiler goes through ...


1

Any field/method that a user of the class can access is part of the type, because all code using that type has to know it exists, whether it's static, how many arguments it takes and so on in order for code using it to compile properly. For instance, you'd have no way of knowing if Foo::field was valid code unless static int field (or something similar) was ...


3

TruckTire is a Tire all right so inheritance is appropriate here. Truck however cannot use Tires, only TruckTires. This we can achieve by introducing some elementary generics. If the program would need additional types, say Tractor and TractorTire, the solution could easily be extended to this. public class Vehicle<T extends Tire> { private T[] ...


1

If you want to associate a Student with a Degree, but keep them separate from each other, you can express that relationship with a data structure like a HashMap. something like (untested, treat this as pseudo code): HashMap<Student, Degree> enrolment = new HashMap<Student, Degree>(); Student dave = new Student(); Degree masterOfScience = new ...


2

Modular design is about separation of concerns, NOT about splitting something up into smaller sections (though it tends to have that effect). It's perfectly acceptable (and even very good practice) to have a separate EJB module, web module, etc.. Each is its own deliverable after all within the JEE landscape, with the EJB module creating an EJB jar, the web ...



Top 50 recent answers are included