New answers tagged

0

I can think of two solutions, each of which has its drawbacks. Firstly, you can pass around a big Context object that stores all the required state (i.e. it contains the current Stuff plus something2). This is the accepted solution for this related question. That answer suggests making each stage declare its input requirements by accepting an argument ...


3

Hashing makes only sense in conjunction with an equality comparison. But if types contain double values like in your example, any sensible equality comparison should work with an "epsilon", something like bool Equal(Box b1,Box b2, double epsilon) { return fabs(b1.mins[0]-b2.mins[0])<epsilon && ...


2

If you can generate a guaranteed unique hash, then do so. However this means your box coordinates must be relatively small (eg if a box can be between 0 and 1, in increments of 0.1 then you have 10 steps for each co-ordinate, making a possible 10^4 unique values, assuming no 2 boxes can overlap) In most cases you will not be able to guarantee a unique hash, ...


0

I would do something along the lines of... public class A { public List<B> childern {get;private set;} public A(DataReader dataForA, DataReader dataForBs) { //validate and set A properties from first datareader, ///validate we have at least one B while(dataForBs.Read()) { var parent = this; ...


3

If you have multiple types of Signals that have to be updated in different ways, then the cleanest solution is to create a sub-class for each type of Signal, where the sub-classes only implement the different update behaviours. The proposal for storing a function pointer in the Signal class is just emulating manually what the compiler does for you when you ...


0

I'd call that either a Facade Pattern or an Adapter Pattern. There's very little difference between the two patterns and it really comes down to intent. Facades are usually about simplifying the interface, whereas Adapters are about making the interface match an existing interface\usage.


0

I would suggest to cache them somehow and the simplest way to do it is to use NSURLCache. You can create a simple wrapper above it that conforms to e.x. <Cache> protocol, so you could change your cache provider without breaking any piece of code later. You can set up Apple's NSURLCache like this NSUInteger cacheSizeMemory = 5*1024*1024; // 5 MB ...


3

In general, something like this is a good idea. I'm not very experienced with JavaScript in particular, but have loads of experience testing other languages. And there I have found that exposing callback hooks like this is an extremely valuable technique to allow dependency injection without drastically changing the overall architecture – in fact, I recently ...


3

I'd argue no-ish. I'm not sure it's really the "module pattern" if you return anything other than a singleton. But, you can certainly use the same "pattern" to accomplish other things. The module protects the global scope from the internal variables used to build the return-value; but the return value can itself be a function -- including a constructor. To ...


0

You can return anything with the module pattern, it's just a way to avoid global pollution while instantiating a module. It's quite common to see it used to generate functions or constructors, which can then be used as often as needed: var module = (function (){ ...scoped stuff... return function () { ...do stuff with scoped stuff... }; ...


1

This is more of a comment than an answer, but I can't comment, so... just wanted to mention that this question surprised me because I don't see this as uncommon at all. Actually, in my environment of work (web developer) is very very common. For instance, this is how Symfony's doctrine:generate:entities command auto-generates all setters, by default. ...


1

Load them all in again … but make use of caching more generally in your application. Now you don't have to worry about double-loading. Congratulations: you've just written your first "scalable" application. :)


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; } ...


1

I do not know the pattern name (but it's probably using the Reflection pattern, see below), but many Web frameworks natively implement what your are trying to do here. For example if you look at Ruby on Rails, ActiveRecord and Mongoid are the components used to represent a Database entity, and programmers usually implement their model like this : class ...


6

As other people have said, this is often called a fluent interface. Normally setters are call passing in variables in response to the logic code in an application; your DTO class is a example of this. Conventional code when setters don’t return anything is normal best for this. Other answers have explained way. However there are a few cases where ...


5

That technique is actually used in the Builder pattern. x = ObjectBuilder() .foo(5) .bar(6); However, in general it is avoided because it is ambiguous. It is not obvious whether the return value is the object (so you can call other setters), or if the return object is the value that was just assigned (also a common pattern). Accordingly, ...


0

I think you need to use the State monad from scalaz -> http://eed3si9n.com/learning-scalaz/State.html The data type would be State[Stage, Data] where Stage consists of your stages and data the value that accompanies the current stage. case class Stage(id: String, someStateInfo: String) case class Data(someData: String, anotherData: String) Create a ...


31

Saving a few keystrokes isn't compelling. It might be nice, but OOP conventions care more about concepts and structures, not keystrokes. The return value is meaningless. Even more than being meaningless, the return value is misleading, since users may expect the return value to have meaning. They may expect that it is an "immutable setter" public ...


44

So is there a reason why isn't this a OOP convention? My best guess: because it violates CQS You've got a command (changing the state of the object) and a query (returning a copy of state -- in this case, the object itself) mixed into the same method. That's not necessarily a problem, but it does violate some of the basic guidelines. For instance, ...


5

I think much of the reason it's not a convention to chain one setter after another is because for those cases it's more typical to see an options object or parameters in a constructor. C# has an initializer syntax as well. Instead of: DTO dto = new DTO().setFoo("foo").setBar("bar"); One might write: (in JS) var dto = new DTO({foo: "foo", bar: "bar"}); ...


12

I don't think this is an OOP convention, it's more related to the language design and its conventions. It seems you like to use Java. Java has a JavaBeans specification which specifies the return type of the setter to be void, i.e. it is in conflict with chaining of setters. This spec is widely accepted and implemented in a variety of tools. Of course you ...


1

This sounds like combination of strategy and composite patterns. Individual validators are strategy pattern. Then, composite is used to invoke multiple strategies as single one.


0

Here you can find a short video explaining clearly the difference between those terminologies. https://www.youtube.com/watch?v=C7hkrV1oaSY Separation of concerns (SoC). Divide your application into distinct features with as little overlap in functionality as possible. (Microsoft). “Concern” = “distinct feature” = “distinct section” “Concern” works at both ...


8

In the MVC design pattern, the Controller part is responsible for translating user actions into modifications of the various Model classes that are involved in a piece of functionality. There is no one-to-one relation between Controllers, Views and Models. In particular, if a user action requires changes to multiple Model classes, then it is the ...


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; ...


0

Interfaces that only carry properties should be avoided since : it obfuscates the intent : you solely need a data container it encourages inheritance : probability that someone will mix concerns in the future it prevents serialization Here you are mixing two concerns : summary as a data summary as a contract A summary is made of two strings : an id ...


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. :)


3

I think, what you are referring to here is not a specific design pattern, but a more general software development principle called "separation of concerns". If you constrain these concerns into more specific areas like UI logic, service usage and data processing, you are almost in the MVC/MVP world, which could be indeed seen as a pattern. On the other ...


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

Personally I rather keep patterns as being emergent, as in, the solution you came up with can be identified/recognized as being the 'strategy pattern'. As soon as you start to use or apply patterns they quickly become a solution looking for a problem. Can one type of expense have multiple ways of calculating tax, for instance depending on persona? Then ...


2

A compiler could guarantee that the return this + function chaining pattern has never worse performance than calling multiple methods on the same object, by always rewriting the former pattern into the latter. But I think it would be a relatively complicated rewrite and I'm not sure it would be worth the effort. Especially since I believe the return this ...


3

can it be optimized with no overhead? How? As Telastyn wrote, one approach is to have a compiler providing two function versions. If I were in the role of a compiler designer, I would handle it this way: I would build a compiler with inlining support. Such a tool can obviously optimize the return this statement out when it is not used. and if this ...


1

In theory, yes. C++ has a term for it: copy elision. The C++ standard allows for copy elision. The concept you are asking about, in fact, has its own tla: RVO (return-value optimization). Essentially, the compiler can (but, unfortunately, is not required to) decide on the space where the return value will reside before the function is called. This ...


3

Returning an object of built-in type from a function usually carries little to no overhead, since the object typically fits in a CPU register. The point of this comment from wikipedia isn't that returning the value has no cost. Overhead is additional cost, and the here the cost is in addition to that of the return value mechanism. The article is ...


1

If the implementation uses a calling convention that uses the same register to pass the this pointer to a function that it does to return a value from the function, then return this is a zero-cost operation (because the return value is already there).


3

At least in C#, your desired construct is entirely unnecessary. You can write something like var mylist = new List<string>(new[] {"Hello", "World"}); ... mylist.AddRange(new[] {"Add", "Some", "More", "Items"}); which is about as concise as you can get, while still being perfectly readable. If you really want method chaining in a class, even one ...


10

First off, var list = new List<string>(); list.Add("hello"); list.Add("world"); Is just as, if not more readable than var list = new List<string>().Add("hello").Add("world"); Lines of code is not, in any way a proxy for code's cleanliness or simplicity. Thus my question for this very particular pattern (i.e "return this" for method ...


1

Dart has this feature. So you can do StringList myList = new StringList() ..Add("hello") ..Add("world"); Here we can treat F(expr..m(...)) as syntax sugar for: var _generated_temp = expr; _generated_temp.m(...); F(_generated_temp); You can see Dart also allows setting properties to be chained in the same way: Person myPerson = new Person() ...


-1

My opinion: Services are the preferred way of sharing behaviour/data across modules/directives/controllers. Directives are isolated things that can be nested or not. Controllers should stick to being a viewmodel as much as they can, ideally no business logic should end up in there. So: When you start wiring them together by accessing parent scope ...


0

In an article titled Design Patterns for Dealing with Dual Inheritance Hierarchies in C++, Uncle Bob presents a solution called Stairway to Heaven. It's stated intent: This pattern describes the network of inheritance relationships that is needed when a given hierarchy must be adapted, in its entirety, to another class. And the diagram provided: ...


1

I would argue that, in the case of AngularJS, utilizing callbacks is a code smell. I say this for the pure simple fact that AngularJS includes the notion of promises that you can leverage for the same use-case, and in fact look extremely similar in practice to the code you have already developed. Consider your test method: var testMethod = function() { ...


2

I believe that generics are not the right solution to your problem. Interfaces should be enough. In general, generics should be used on something that can be applied to different - generic - kinds of objects. Here, on the opposite, you want a different behaviour (i.e. interface) depending on the kind of object. When you call new ...


1

The trick here is that when you start a drag operation, the application whose data you're dragging will give the operating system that data in one or more specific formats. Then, the application you drop the data on will ask the OS if it has data in one or more specific formats. Thus, when dropping "the same data" on two different applications results in two ...


0

If a system — might it be a software, an operation system or an organization — deals with roles and permission, there comes a time when it is useful to add roles and manage permissions for them. If this can be archived by altering the source code, it might be ok, to stick with enums. But at some point the system's user wants to be able to manage roles and ...


0

In my experience, trying to make a framework like EF work in a repository pattern is not the best if you really want to bundle transaction and separate functionality out into Repo's like that. I would have the MVC controller instantiate an EF data context, and be responsible for calling "SaveChanges()" after its done any active-record data manipulations. For ...


1

I do not have a definitive answer but here are my points: In favor: I do not like business logic in the controller. They already have a lot of boilerplate code related to the view, format, transformations, bindings, mapping, etc. Three calls with its own error handling (and may be some specials cases) can become complex enough to bring bugs. The logic of ...


4

Is it a good practice to use List of Enum values on User? Short answer: Yes Better short answer: Yes, the enum defines something in the domain. Design-time answer: Make and use classes, structures, etc. that model the domain in terms of the domain itself. Coding time answer: Here's how to code-sling enums ... The inferred questions: ...



Top 50 recent answers are included