New answers tagged

1

The problem is not that you are violating the Open/Closed principle, the problem is that you are violating the Single Responsibility Principle. This is literally a school book example of an SRP problem, or as wikipedia states: As an example, consider a module that compiles and prints a report. Imagine such a module can be changed for two reasons. First, ...


2

Database systems can implement very different approaches. Just compare SQL vs. NoSQL. And for the latter compare key-value stores with graph databases. So you'll not find a silver bullet that will offer a single API with all the benefits of these databases. So you'll have to narrow down your scope. Considering the limits, filtering, ordering, many of ...


2

This is an easy one. If the preconditions are associated with the matchup (i.e. they always hold), then they belong in the constructor. If the preconditions are associated with the event (i.e. the event decides whether they hold or not), then they belong with the event.


2

Whenever I describe something as being an "Implementation Detail," I am saying that the user doesn't need to know how it gets done, so long as it gets done. For example, in C a pointer actually points to a memory address in the computer, but you can't say the same thing about a reference in Java (even though pointers and references both perform essentially ...


1

I'm going to answer my own question after a day of research. In the end this ended up looking more towards cron jobs which support MVC web applications (which isn't exactly the same as my original question but yielded some interesting information none-the-less). Anyway, here's what I found: Q. The concept of routing all requests to one file is a little ...


10

There are some posibilites, how to mock static methods in PHP, the best solution I have used is the AspectMock library, which can be pulled through composer (how to mock static methods is quite understandable from the documentation). However, it's a last-minute fix for a problem which should be fixed in a different way. If you still want to unit test the ...


4

First, I would suggest to split this up into separate methods: public function validate($value, Constraint $constraint) { $totalCount = QueryTotal($value); ShowMessageWhenTotalExceedsMaximum($totalCount,$constraint); } private function QueryTotal($value) { $searchEntity = EmailAlertToSearchAdapter::adapt($value); $queryBuilder = ...


1

Here's an example of how you might approach this from a functional perspective, and how it helps avoid the potential pitfalls. I'm working in Haskell, which I'll assume you don't know, so I'll explain it in detail as I go along. data Application = Applied ApplicationDetails | InReview ApplicationDetails | Approved ...


0

Inheritance isn't the only mechanism that can be used to fulfil the requirements of OCP, and in most cases I would argue that it is rarely the best -- there are usually better ways, as long as you plan ahead a little to consider the kind of changes you're likely to need. In this instance, I would argue that if you expect to get frequent format changes to ...


1

You could use the «command» pattern, and then ask to the Invoker to provide a list of valid functions according to the state of the receiver class. I used the same in order to provide functionality to different interfaces that were supposed to call my code, some of the options were not available depending of the current state of the record, so my invoker ...


1

One approach to this problem which has been extremely successful in the wild is hypermedia - the representation of the state of the entity is accompanied by hypermedia controls that describe the kinds of transitions that are currently allowed. The consumer queries the controls to discover what can be done. It's a state machine, with a query in its ...


-1

There are more than 1000 way except MVC some of them are similar to MVC and some totally different for example : Model-Template-View - MTV Model–view–presenter - MVP Hierarchical model–view–controller HMVC Model View ViewModel- MVVM etc


-2

If you can adapt your parser/crawler to click through to each RSS/Atom element's article, most news sources implement some form of structured data for their articles to better facilitate SEO and social network requirements like Facebook's Open Graph. For example, if you look at any article on CNN, you'll find two <meta> tags: <meta content="cannes ...


1

Quite likely, implementing your grammar as multiple interdependent parsers is only going to make your code more complicated. The data flow will become less obvious, and you will duplicate some behaviour. It is OK if a class is large. However, many languages can easily be split into different levels, and handling these separately could be sensible. For ...


4

Create a Scanner or Tokenizer class, which takes the input data (the text to be parsed) and holds the position of the current token or similar state. It can also provide some shared helper functions. Then provide a reference (or a shared pointer) to the Scanner object to all your individual xyzParser objects, so they can all access the same scanner. The ...


1

State design pattern perhaps? It is pretty much straight-forward inheritance, with the parent - abstract - class containing a reference to the current "state" object, i.e. parser. The pattern coupled with delegates, extension methods, etc. should give plenty of flexibility. Be wary of breaking apart a class arbitrarily. These smaller classes also need OO ...


2

Is using __import__('module_name') an antipattern in Python? The api for __import__ is somewhat misleading. I personally would prefer to avoid it where possible. The docs for Python 3 state: Direct use of __import__() is also discouraged in favor of importlib.import_module(). Here's the API for __import__: mod = __import__( module, # string ...


0

Consider: public abstract class Entity { public static abstract class Builder<T extends Entity, B extends Builder<T, B>> { private final T object; private final B thisBuilder; public Builder() { this.object = createObject(); this.thisBuilder = thisBuilder(); } protected ...


0

I would do factory methods in the object where non of the parameters can be null. That is where valadition should be. Those can throw an execption. As for the builder, replace with abstract factory pattern and let it throw an execption. For loading, have a list of the factories. Try build the object and if it's no longer null and no exception thrown, return ...


0

I would make a class to save value objects and another to load each value object. Value objects here mean primitives only. Also, validate and try immutability so no thread locking is needed (can't data data race if immutable). Builder pattern may help. Then for agretes named Foo make a persist Foo class. It holds all value objects in Foo as final and ...


3

According to the collection of embedded system design patterns at http://www.eventhelix.com/RealtimeMantra/Patterns/, what you're talking about is called the Serial Wait State Pattern, which contrasts to the more flexible/efficient but harder to use Parallel Wait State Pattern.


1

I would certainly raise an eyebrow at getters in a builder, and it looks like a violation of the single-responsibility pattern. It sounds like you need a separate validation component prior to the builder. So your chain of processing would be read the file, validate the params, and feed to the builder. The alternative (and this would be a good practise ...


1

This is a common issue when implementing aggregates. It usually gives rise to separating aggregate state onto a another object. That object can be a pure data bucket with public getters/setters for convenience. Outside callers could be aware of the aggregate's state class, but it remains private to the aggregate (as a private field, for instance). The ...


4

I think there is nothing wrong per se to have getters in your builder class allowing to inspect which data was passed in. As Robert Harvey stated, getters are not part of the pattern, but sometimes a pragmatic solution is better than sticking to some doctrine. And there is not "the one and only correct way" to implement a pattern, design pattern always give ...


0

I'm going to do a slight variation on the master-detail template. In the master view, I'm adding a context menu for each row <ListView.ContextMenu> <ContextMenu> <MenuItem Header="Open MultiOrder" Click="MultiOrder_Click"/> <MenuItem Header="Add to MultiOrder" Click="MultiOrder_Add" /> It will ...


1

I wouldn't introduce anything. This seems like something you could break into smaller pieces if it got difficult to manage. But right now, three function calls aren't hard to manage, so leave it simple until you need to make it complicated. In fact, I'd take out some of these levels unless they're used by a different service. So more like; public void ...


2

Getter/setter properties are the way to go. They are very clear, code-wise, and don't involve adding a weird smell to an entire codebase. Also, tools like Entity Framework use getter/setter pairs to do work, so a property should be more discoverable by tools, IDEs, and frameworks than any hand-rolled solution. Generally, if you find yourself wanting to ...


7

Idiomatic C# generally favours properties over accessor methods for simple properties, so just use a property unless there is a good reason not to. If there is complex logic in the getter or setter, it may be better to use accessors to avoid breaking the Principle of Least Surprise. For a canonical example, WPF checkboxes use a property - although a bool? ...


0

In Activity A, you need to specify which task that activity B need to run. To accomplish this, you need to pass variables created from Activity A to activity B. This can be done using putExtra() function inside of your activity A. In activity B, you need to get Activity A's variable using getIntExtra() function. Check tutorial at ...


0

First of all, make everything works out. It's ok if you copied a function and put it in several places. When everything works out, it then will be called early version of your application (v1 or whatever). The next step is beautifying. This is when you see a lot of repetition in your code. You'll see which code block that need to be classified. ...


0

You have a lot of good answers already, but here are a few more suggestions that may allow you to see an alternative solution: Your example shows a Student (clearly a model object) being passed to a Window (apparently a view-level object). An intermediary Controller or Presenter object may be beneficial if you don't already have one, allowing you to ...


1

One common route around this is to insert an interface between the two processes. public class Student { public int id; public String name; public int age; public float score; } interface HasInfo { public String getInfo(); } public class StudentInfo implements HasInfo { final Student student; public StudentInfo(Student ...


0

This is actually a decent question. The real issue here is the use of the generic term "object", which can be a bit ambiguous. Generally, in a classical OOP language, the term "object" has come to mean "class instance". Class instances can be pretty heavy - public and private properties (and those in between), methods, inheritance, dependencies, etc. You ...


1

You should pass what makes sense, some ideas: Easier to test. If the object(s) need to be edited, what requires the least refactoring? Is re-using this function for other purposes useful? What is the least amount of information I need to give this function to do it's purpose? (By breaking it up--it may let you re-use this code--be wary of falling down the ...


2

In Java, enums are designed to be more than just constants. Enum values are objects (like one you could instanciate from any standard class) but with a few restrictions: Instances of an enum are restricted by yourself: when you write enum Number {ONE, TWO, THREE;} you explicitly say that theses 3 instances are the only one allowed to live Java takes care ...


1

It seems as if you're thinking of "values" in a constrained way (perhaps applying a concept from other languages). What if you expanded your idea of the kinds of values that can be enumerated? That opens a great range of possible uses. Your design wisdom will keep you from doing horrible things with that awesome power. Try this: Think of an enum as ...


5

Perhaps it's because I used C/C++ in a previous life but I would argue strongly for keeping the enums simple. In those languages an enum was a glorified integer only. In Java, as you say, they are really a true object. But I feel that the spirt of an enum is not to have a ton of code in there - an enumeration is a complete, ordered listing of all the ...


1

In this case, is it bad practice (that is, will this technique cause any engineering problems) On a technical level, no problem. You're basically adding a layer inside the dependency graph in order to reduce how much branching is going on. It shouldn't cause any technical problems. (If it actually matters for instantiation-speed, something has already ...


21

In layman's terms: What you call a "custom object" is usually simply called an object. You cannot avoid passing objects as parameters when designing any non-trivial program or API, or using any non-trivial API or library. It's perfectly OK to pass objects as parameters. Take a look at the Java API and you will see lots of interfaces that receive objects as ...


3

It is much easier to write and read tests if you pass the whole object: public class AStudentView { @Test public void displays_failing_grade_warning_when_a_student_with_a_failing_grade_is_shown() { StudentView view = aStudentView(); view.show(aStudent().withAFailingGrade().build()); Assert.that(view, ...


3

Steve McConnell in Code Complete addressed this very issue, discussing the benefits and drawbacks of passing objects into methods instead of using properties. Forgive me if I get some of the details wrong, am working from memory as it's been over a year since I had access to the book: He comes to the conclusion that you are better off not using an object, ...


4

In your student example I assume it is trivial to call the Student constructor to create a student to pass in to showInfo. So there is no problem. Assuming the example Student is deliberately trivialised for this question and it is more difficult to construct, then you could use a test double. The are a number of options for test doubles, mocks, stubs etc. ...


2

A multitenant architecture has the benefit of scalability as well as security. When you have all the client data in one table, all customers has access to all customer data, not calculating the code you write to restrict this access. In a multitenant architecture you can set up different users in the db and have a much simpler design of the authentication ...


25

You say it's not quite easy to test individually, because it needs a real Student object to call the function But you can just create a student object to pass to your window: showInfo(new Student(123,"abc",45,6.7)); It doesn't seem much more complex to call.


5

"I think it would add a level of complexity to the app" ... opposed to what - using just one schema for all tenants? Then typically the opposite is true. Implementing multi-tenancy in one schema adds the complexity to each and every table where the data might belong to different tenants, which means this kind of complexity will go also into your app. ...


127

Using a custom object to group related parameters is actually a recommended pattern. As a refactoring, it is called Introduce Parameter Object. Your problem lies elsewhere. First, generic Window should know nothing about Student. Instead, you should have some kind of StudentWindow(or StudentView), that knows about only displaying Students. Second, there is ...


4

This could be solved by using event driven programming and a few observers. How many things does this method do? public void submitThing(Thing thing, SubmitData data) { thing.setStatus(SUBMITTED); thing.setData(data); documentService.doSomething(); mailService.doSomething(); } Three. It does three things. Submits the thing. Does ...


2

So, is the Command design pattern the way to go here or are there better patterns for splitting up a class that has several actions into smaller pieces? It's going to depend somewhat on how tightly the actions are coupled to each other. On possibility is to combine the idea of the Command pattern with that of Composite. Each individual, isolated ...


7

A good pattern is Observer. https://en.wikipedia.org/wiki/Observer_pattern In your algorithm, at each point where you want to output something, you notify some observer(s). They then decide what to do, be it to output your text on the console, or to send it to the HTML engine/Apache etc. Depending on your programming language there may be different ways to ...


4

As a slight improvement to straight logging, create some sort of object that models one execution of the algorithm. Add a "step" to this container object each time your code does something interesting. At the end of the algorithm, log the accumulated steps from the container. This has a few advantages: You can log the full execution as one log entry, ...



Top 50 recent answers are included