New answers tagged

0

You can mimic the structure of the AuthorizeAttribute. In one of my past projects, I segregated "authorizable" functionality into different methods and appended a customized authorization attribute to those methods. So if you need to authorize a sub-function of your controller methods, put that functionality into it's own method. You can pass static data to ...


0

In your case you are not overriding any of JButton methods you are trying to set some properties to JButton usnig your custom method so there is no need for using inheritance. You can use Builder Design Patter. For example public class CustomButtonBuilder { private JButton button; public CustomButtonBuilder(JButton button) { this....


0

You could implement delegate methods that you will use most often, for all the others just ensure there is a way for a client to obtain JButton: public class CustomButton { protected JButton button; public void customMethod() { } public void add(PopupMenu popup) { button.add(popup); } public void addActionListener(...


8

If you honestly, truly need a component as general as a JButton, then you should just use inheritance. "Favor composition over inheritance" doesn't mean "never use inheritance." However, people made that buzzword phrase because 95% of the time when beginners think they need inheritance, they don't. 95% of the time, you don't actually need a component as ...


1

What composition over inheritance really has to say here is that it would have been nice if JButton has been designed with composition polymorphism so your CutomButton method could have been passed into it. It wasn't. If the client needs access to everything JButton provides (dubious) you now have to create a bunch of boilerplate delegation methods if you ...


0

It looks a bit like global variables (bad, bad). Or a bunch of singletons, utility objects (bad, bad). But then modules are again considered fine. Normally one would have a hierarchical structure: application - dialogs x documents. "As you need them" is the most efficient way in general, so I would keep with that. However there might be modular ...


1

It's fine if it doesn't hog to many resources. Best way to know if it does is to do it and see what happens. This is a performance issue. Don't fix it until you see it. The number one reason not to allocate space upfront, objects in this case, is when you don't already know how much to allocate. This is why heap collections are prefered over arrays. ...


1

Optional parameters can work nicely here. public class Vector { public static readonly double DefaultTolerance = 0.0001; // or whatever. public bool Equals(Vector other, double? tolerance = null) { tolerance = tolerance ?? DefaultTolerance; // go about your business } } // later w.Equals(v); w.Equals(v, 0.001); And since the tolerance ...


2

One approach that might fit is a finite state machine. There are tools that help you build and visualize them but you can also model it with standard OOP practices.


4

But I know that throughout my application, the tolerance will be constant. This is a bit suspect because such tolerance is usually very algorithm specific. I've had to deal with much pain because someone thought that it they could get away with using a constant tolerance everywhere. But assuming, that you really do want this, I might do: public class ...


0

There are multiple ways to handle code reuse in Perl. A lot of examples do not make clear the distinction between the approaches and many classes use at least two. I advise using OO style as much as possible and only use the EXPORTER when you have at least three or more classes that need a relatively small cluster of utility functions. So: package Foo; ...


0

Well, you could do it like this, if you really wanted to: for (int i = 0; i < myObjects.size() - 1; i++) { MyObject currentMyObject = myObjects.get(i); amount = amount.add(currentMyObject.getBillQuantity()); MyObject nextMyObject = myObjects.get(i + 1); if (currentMyObject.getCompletedDate() .compareTo(nextMyObject....


0

You could do something like this, where instead of starting at index 0 and allays comparing one forward, you can start at index 1 and compare one backwards. This method shouldn't go out of bounds, but it's certainty not the end of the world to leave the if statement there. Especially if it helps readability for others working on the project. for (int i = 1; ...


0

There is nothing wrong with empty methods. The right way to say that a method does nothing is an empty body. I believe your feeling that empty method are ugly is just a bad point of view. An interface method which depending the case is implemented as doing something or nothing (by an empty body) is typical of hooks, which depending on the use case might do ...


3

You are trying to create a layered design. In the top layer are inputs & outputs that interact with the elevator riders: the inputs are the button panel in the elevator and the displays of what floor it's on along with the up/down indicator and button pressed indicators. Further there are up/down call buttons on each floor (and a duplication of the ...


0

The question whether the relation between ClassA and ClassB is composite does not depend on whether there also instances of ClassB that are not part of any ClassA. In your example, as long as no reference to the inner ClassB-instance (the one held in your instance variable bInstance) can ever escape the containing instance of ClassA (which could happen if ...


8

The first approach is much, much better than the second approach. The most important quality of software is readability, since the number of times we may write and re-write a line of code is much smaller than the number of times we may read a line of code. (Do you ever write code and then never read it again? I hope not. And before you re-write a line ...


2

Consider separating use from construction. Foo foo = new FooInjector(f1).build(); Now making Foo immutable is trivial. Now I can look at Foo's behavior without being distracted by f# construction. Sure Foo has a long constructor to handle but that's hidden in FooInjector, not spread throughout the code base. If you find many classes (besides just Foo) ...


1

I don't see that it matters. All the processing is internal / private to the foo class. It's one massive side-effect anyway; the constructor is setting Foo object state. If Foo cannot trust itself then what's to do? Don't hold state and re-calculate all the fx objects every time? Nonetheless I like the 1st option not because of side-effect management but ...


6

Stop worrying about efficiency and start concerning yourself with creating a good abstraction that is applicable to the domain and complete to the client/user/caller's needs. To do this, we first identify what capabilities client/user/caller needs. Generally speaking, for a good abstraction, all these capabilities need to be found together or else the ...


2

A grayscale bitmap can be colored just fine. Some other image file formats will have to be re-encoded if they suddenly stop being grayscale. If the user tries to turn your grayscale image into sepia tone you have to decide wether to let them or to tell them no. Similarly, you will have to decide how to react when requested methods are not valid with your ...


0

Your premises are correct. However, what can be considered as a 'valid' state is very subjective. It usually means that the assumptions that the writer of the class has about the structure of the contained data inside instances of that class are correct. The only way you know that these premises are not invalidated by code at another location, is to ensure ...


3

This is just Robert Martin being a bit flowery in his writing. Prior to Martin's work, a simple change in the program meant replacing all 32 EEPROM chips. By using pointers to functions, each of the 32 chips became independent of one another. That's all it means.


2

Premature Over-Engineering For example, I assert that you do not need any of those interfaces. If needed later, make them later. An interface (the C# keyword kind) is for giving common behavior to unrelated classes and then handle objects polymorphically. Think more carefully about what constitutes a more specific class. Think of what a shopping cart IS. ...


5

In most cases, there won't be a noticeable difference (unless you have the obvious case with method parameters named the same as member variables). But beware of templates! template <typename T> struct Base { int i; }; template <typename T> struct Derived : public Base<T> { int get_i() { return i; } }; This will cause a ...


0

If a class has a member variable named data and one of its (non-static) member functions also has a local variable (or parameter) named data, then data is the local variable and this->data is the member variable. class Point { double x, y; // ... }; // Constructor with parameters named the same as the member vars Point::Point(double x, double y) { ...


0

No surprises. They are functionally identical. In order for the compiler to locate the member, the compiler must use the hidden this parameter. Therefore there is no functional difference between accessing a member with or without using this. The reason to use this is to disambiguate other names that may be in scope.


5

There's a couple of ways you can do this: You can use isinstance to determine what the object's class is: if isinstance(foo, bar): do_something() elif isinstance(foo, baz): do_something_else() else: default_behavior() However, this gets unwieldy quickly with a large number of possible classes, and isn't good OOP. The OOP way would be to use ...


2

I don't see where a conceptual object is involved in performing string-to-binary conversions. That's a process, and using an object for it doesn't make sense in the general case. That being said, there are reasons for wrapping a process up in an object. But these primarily have to do with state. For example, if multiple executions of the process will update ...


6

It's not really a question of which is preferred. They are different solutions to different problems. You would do this if a C is an A and a B: public class C implements A, B { ... } You would do this if a C shares some of the behavior of A and B, but is not an A or a B: public class C { private A a; private B b; } This decision should be ...


1

In filesystems there are two different types of links: hard links: which points to anonymous objects (e.g. inode) symbolic link: which can point to the file's real name, or another symbolic link In languages like Python, some objects like classes and functions have canonical name that you access through obj.__name__. Reasigning the object to another name,...


3

Instantiating and collecting small, short-lived, temporary objects, is perfectly fine. It is what modern garbage collectors are good at. Modern (generational) garbage collectors are built on a couple of assumptions: most objects die young, most objects are small, most objects don't escape, most objects are immutable, older objects don't contain references ...


-1

Garbage collection can become a performance issue in games, and might require special approaches. However, before you are sure that garbage collection of temporary Location instances is problematic, you would waste your time by trying to limit the amount of instances: “Premature optimization is the root of all evil.” To decide whether you should go down ...


1

To answer the main question directly : no it is not sensible. Why? Because it exposes the inner working of the class. As an alternative consider this : class CeilingFanPullChain { private State state; public CeilingFanPullChain() { state = new Off(); } private void setState(State newState) { state = newState; } ...


2

If Cycle belongs to a particular ScholarshipProgram only, then it should belong to the ScholarshipProgram aggregate. If a Cycle can be part of two or more ScholarshipProgram, Cycle should be its own aggregate root. In any case the aggregate root is your entry point. In the first case that means that ScholarshipProgram would have the methods to manage Cycles ...


0

I am not very sure about what you want from your question, but here are two methods I can think of, with the objectives to: provide optimum performance maintain flexibility through type abstraction About your method: Why did you create the pageData class? Why couldn't you store them in a dynamic object/associative array? Then create an abstract method ...


1

Your quote is still true today: Dealing with large numbers of interrelated types while still preserving modularity in the design of large systems is very difficult, and is an area of much current research. Programming very large object oriented systems -- thus with more and more interrelated classes and dependencies -- caused mainstream language ...


1

The way I interpret your idea: You have about 200 strings that you want to search for in your target .txt Find any of these given strings Give the user(?) som kind of feedback Replace it with some other string Both strings returned in step 2 and 3 are mapped to the exact content of the string found in step 1, i.e: 'a' found -> print 'a_feedback', ...


1

While RobertHarvey's answer makes an excellent point -- essentially, that the State pattern is overkill for the example you post and that a simplified version using a switch statement is perfectly acceptable and much more concise in this situation -- I assume that you are positing this as either a learning exercise specifically about the use of the State ...


1

Before applying a pattern, clarify what you want to accomplish! Do you want to reduce the side effects of those functions? Make sure your functions have proper input parameters and output their result as a return value. Then let the caller mutate the dictionary. Do you want to reduce duplicate (or similar looking code)? Start with 1, but make sure the ...


5

You could call the class a Facade for the database and key/value dictionary. A facade is a class which encapsulates operations which consist of multiple complex calls to different objects behind a single object with a much simpler interface.


2

While there is some logic in having the methods that do some operations with bill history in the CustomerAccount (or Bill) class, one might argue that having them there breaks the SRP. You could say that CustomerAccount class should be responsible only for maintaining the account data (adding, deleting or modifying that data). Reporting could be seen as a ...


1

Review of your design Your Employee is in reality a kind of proxy for an object managed persistently in the database. I therefore suggest to think to the ID as if it were a reference to your database object. With this logic in mind you can continue your design as you would do for non database objects, the ID allowing you to implement the traditional ...


7

This is a more well-formed transcription of my initial comment under your question. The answers to questions addressed by the OP may be found at the bottom of this answer. Also please check the important note located at the same place. What you are currently describing, Sipo, is a design pattern called Active record. As with everything, even this one has ...


2

First create an employee struct containing the properties of the conceptual employee. Then create a database with matching table structure, say for example mssql Then create a employee repository For that database EmployeeRepoMsSql with the various CRUD operations you require. Then create an IEmployeeRepo interface exposing the CRUD operations Then ...


-1

"One reason to change" depends on who is using the system. Make sure you have you use cases for each actor, and make a list of most likely changes, for each possible change of use case make sure only one class would be affected by that change. If you are adding a entirely new use case, make sure you would only need to extend a class to do so.


0

It depends. If B and C only support A and are useless/meaningless in any other context, hide them (encapsulate them in A). If they are entities that mean something in your top level problem domain already, independent from you use of A, you as the user may want to create them yourself and inject them for added flexibility. Example: class EmailSender. ...


0

There are a few unknowns here to be able to provide a more detalied response, so I will try to suggest a generic solution. First of all, you would have to handle different types of data that the SQL query could return. This can be done by creating a universal type holder class. Next, you could create a struct containing a two-dimensional dynamic array of ...


9

Is it better to expose or hide dependency in OOP? It's best to do both. Before I explain that let me explore the problems with your proposals. Let's say I have an object A, which is too big(having too many methods and variables). So, I break it down to smaller objects. This is good. Always break objects down until they have only one ...


1

What you said make me think why Object A is that big. Instead of thinking about dependencies and injection I'd concentrate about composition over inheritance which allows late just-in-time object creation only if needed. If you're worried about dependency exposition it could be managed by exposing interfaces instead of internal classes.



Top 50 recent answers are included