New answers tagged

0

I really don't see how simpler can it get than this: class StudentDAO { public Student createStudent(Student studentToCreate) { jdbcTemplate.update(INSERT_SQL, .....); auditService.Created(studenToCreate.AuditInfo()): } public Student deleteStudent(Student studentToDelete) { jdbcTemplate.update(DELETE_SQL, .....); ...


0

I need a limited amount of objects = instances from a class, and I don't want to expose the option to create more. I also want easy access to them from everywhere That is an unnecessary constraint that seems motivated by apriori notions of how you can design and implement a game of chess -- be it a two player chess game or a three player chess game. What ...


0

GRASP, which, IMO, is far superior to and more understandable than SOLID, has the concept of an "Information Expert". Using the principle of information expert, a general approach to assigning responsibilities is to look at a given responsibility, determine the information needed to fulfill it, and then determine where that information is stored. ...


1

I have never seen any pattern or variation that wasn't just a shell game. Fundamentally, you have two writes that you are trying to commit An update to the event bus (really, an update to the durable store of the event bus) An history in your own durable store Because these writes are fundamentally using two different locks, there's always going to be ...


6

Both can be useful, but neither is better. Which way this is handled has to be determined by gathering data and making decisions. Making the decision is a complex process that depends on requirements, what assumptions are safe to make and how the functions will be used. Start with your "A" case: function isValid(data) ...Do expensive validity check, ...


1

There is a third option: don't return. In your first example the client using your function is responsible for being sure data is valid before passing it, for dealing with the result of calling the function, and for knowing when to call the function In your second example the client is responsible for dealing with the result and for knowing when to ...


-1

The best option is to make your function incapable of being called 'wrongly' The best way to achieve that is to define the result for all inputs rather than to throw errors for those conditions where a naive approach would be incongruous. For example: Get a customer by id where the id doesn't exist? Return null. Price per item when there are zero items? ...


0

If you follow Bob Martin's ''clean code'', then you might prefer option 2 (as in @David Arno and @casablanca.) Indeed, One function argument is better than two Simple well-named functions are better than complicated, vaguely named Each function should do one and only one thing (ie, single responsibility principle at the basic level) Open-closed principle:...


4

There is no right answer to this. In a general sense, you actually have three options: Add an optional parameter, Add a second function with a different name, Add a second function with the same name, ie overload the function. I don't think JavaScript supports the third option, but I'm out of date with that language so may have that wrong. But many ...


1

I'd choose option 2 for the following reasons: A separately named method reveals the intention better than a boolean parameter that you need to look up to understand what it does. Since you're not modifying any existing behaviour but simply doing something extra at the end, there isn't a good reason to change the original method to take an additional ...


0

"Changing the command at runtime" and "avoiding hard coding invokers to receivers" are just two sides of the same coin: the invoker is only coupled to the command interface and does not know about the specific receiver that is being invoked, which allows a generic invoker to work with any receiver. The classic example for this is implementing undo/redo in ...


0

Just about everywhere you need to make a decision, but that specific point in the program does not have the knowledge to make the decision, yet still needs to take the action and deal with the results. So look at any code you have written, and look for an if statement. Is the same if x then do this else that repeated throughout your code? Is the condition ...


1

I would get rid of the IHandlerCreator all together, and add a CanHandle method to the IHandler interface. My reasoning is that the logic for handling and determining if you CanHandle are closely related, and likely to change at the same time. In your IHandlerFactory, keep an array of IHandler objects, which could be injected in the constructor of the ...


2

What I haven't seen mentioned in the answers above is the following. Using the builder pattern makes for cleaner code. Cleaner code Say you've created a library which exposes a POJO that's essential to the function of your library. The constructor of that POJO has one or two parameters which are essential. Now for a new feature that POJO needs another ...


1

That article has two subtly different general recommendations: 1) "Only applications should have Composition Roots. Libraries and frameworks shouldn't." 2) "A DI Container should only be referenced from the Composition Root. All other modules should have no reference to the container." You said: It seems that to do this correctly, the client ...


0

This is not a good design, although it is probably not uncommon. Here are a few reasons: ProductsController does nothing of consequence. It just calls the service, so it's just another layer to maintain without added logic. Or do you want to "decouple" from HTTP? Because YAGNI. The CreateProduct it tightly coupled to the data in the product and what 'name' ...


1

The ProductService is tightly coupled to http. You cant switch hosting without changing the ProductService. I instead let a exception handler deal we this so the domain can be completely separated from the hosting public class ExceptionHandlingMiddleware { private static readonly Dictionary<Type, IExceptionMapping> ExceptionMappings = new ...


0

It's a good design. This is very similar how I did things in ASP.NET MVC and how I my team works in Ruby on Rails. I like how the service model handles orchestration and checsk for errors, how the mapper takes care of converting objects, etc. I do have some questions. I'm curious why you have both a Product and a ProductSM? Why two different models? ...


4

"Too complex" is a common concern for new developers, but consider that this is a working solution for them right now. Working now beats better in six months, nine times out of nine. Also, as a new developer, please consider that re-implementing anything from scratch will take several times longer than you expect, is statistically unlikely to fulfil even the ...


0

One difference that should be noted is JavaFX properties are not Serializable. See @jewelsea answer here.


1

EDIT: Regarding the update: Without knowing more about the system I can only guess, but if the class is actually used in the exact way you've described in the question, then, on the surface, it does look like bad or superfluous design, as there doesn't seem to be a specific reason for it. The more generic answer below was based on the original question ...


-1

[I'll hazard a cheeky answer to the titular question.] Can we completely replace inheritance using strategy pattern and dependency injection? Yes... except the strategy pattern itself uses inheritance. The strategy pattern works on interface inheritance. Replacing inheritance with composition+strategy moves inheritance to a different place. ...


-1

Inheritance is not as important as was once thought. It is still important, and removing it would be a bad mistake. An extreme example is Objective-C where everything is a subclass of NSObject (the compiler actually doesn't allow you to declare a class that doesn't have a baseclass, so everything that isn't built into the compiler must be subclass of ...


7

You can replace almost any methodology with any other methodology and still produce working software. Yet some are a better fit to a particular problem than others. It depends on a lot of things which one is preferable. Prior art in the application, experience in the team, expected future developments, personal preference and how hard it will likely be for ...


-2

No. If a mallard duck requires different parameters to instantiate than some other type of duck, it'd be a nightmare to change. Also should you be able to instantiate a duck? It's more a mallard duck or Mandarin duck or whatever other kind of ducks you have. Also I might want some logic around the types so a type hierarchy might be better. Now if code ...


19

Sure, but we call that composition and delegation. The Strategy Pattern and Dependency Injection might seem structurally similar but their intents are different. The Strategy Pattern allows runtime modification of behavior under the same interface. I could tell a mallard duck to fly and watch it fly-with-wings. Then swap it out for a jet pilot duck and ...


0

Organize your code so events and payloads are easy to find. Add documentation if you'd like so you can find these details if they are important to you. There probably will be some similarity across events and publish and subscribe methods that you can reuse.


2

Breaking down the problem What you've done right is identified that all exporters work the same. As a basic example (which I will expand on), this means something along the lines of: IExporter exporter = GetWhateverExporterYouWant(); exporter.Export("C:\\output.txt"); But you've also noticed that the input value (or rather its type) changes based on the ...


0

My initial take on this is that your classes already violate the SRP and this is making it difficult for you to construct orthogonal interfaces. interface IDataReader { IEnumerable<TSchema> Read<TSchema>(DbContext dbContext, string tableName) } interface IDataWriter { bool Write<TSchema>(IEnumerable<TSchema> data, string ...


1

Do the figures specify the presentation/application/data logics? If so, how? They don't specify them in any precise sense, but they do show a high level logical organization of the system. Presentation logic would be a part of the user-facing tiers (desktop GUIs, web pages, mobile device screens). Most of the application logic would be in what's on both ...


1

If we use your method, this is actually very easy to test. You have an interface that exports database and arrays. Now add a test export class that has a simple mocking implementation that implements the interface so you could use it for tests. Also, could you explain a little more why this makes it hard to test? Also, maybe the export interface is not a ...


0

This is feature envy. The method changeColor should be on the button. The attribute color is part of a button. It is the button class' job to choose how color gets mutated. So you make color private to the button class, and then the only way the color changes is if you call the changeColor method. Also note: It is the not the canvas' job to change the ...


4

You're using subclassing when instances will work fine and actually better — the users should be instances of User (or instances of an more general Person even better) rather than subclasses of User, and, let's also assume that the departments should be instances of Department rather than subclasses of Department. People's roles change but they stay ...


0

My first impulse is that you're really trying to extend IEnumerable, so you should just write an IEnumerable extension similar to LINQ. Not only is it simpler, it's also easy to mock and test! To expand on my suggestion, whether you have a DbSet, an Array, a Dictionary, a List, etc, it should not matter since they are IEnumerable. If your data source is ...


0

Generic Repository interface public interface IRepositoryGeneric<TEntity> where TEntity : class { // CRD void Add(TEntity entity); void Remove(TEntity entity); TEntity Get(object Id); IEnumerable<TEntity> GetAll(); void UpdateState(TEntity entity); void Save(); } Repository generic class public class ...


0

This is essentially a question about which policy to implement, and there's no "best" policy, you need to evaluate the different policies against your use cases and decide which one works best for you. Users of reservation apps are generally aware that they are competing with many others for a limited resource, and that someone who's faster might get it ...


3

Is this a sane approach to this problem? It depends. For many situations, this is sufficient and perfectly ok. If you don't create a new type of exporter every two weeks, or don't want to provide an extensible black-box library for dealing with exporter classes, it is probably better to keep things simple and live with a little bit of "duct tape". It ...


6

One of the most powerful design techniques is to pay attention to what you know when. Following this can help keep your design simple. You might be setting your dependencies in the wrong place. ArrayExporter.Export() depends on both string[] arrayData and string outputPath. But which do you know when? If you don't know outputPath until you know the rest: ...


1

MVC (model-view-controller) is an architectural pattern, but it does not map directly into N-tier architecture: Those are more or less orthogonal, and in principle each layer can have their own (even multiple) MVCs. And of course N-tier architecture can use MVC somewhere or not. For some simplified system, maybe one can somehow put model at some business ...


0

I can see many solution but at first you should separate models. One for the client side and another for the server (and some mapping). Then you can for example have a flag new used for not-saved data. Another option like this written here (hash or Id).


0

Late to the party, but I wanted to give a 'refactoring' example to complement other peoples' answers. I'm going to use the example of a class that decompresses a file: public class FileDecompressor { public void DecompressFile() { string filePath = "/path/to/file/file.gzip"; if (filePath.EndsWith(".gzip")) { unzipGZipFile(...


2

A functions/methods contract is a very real thing. I like to use sqrt(x) as an example: x must be real x must not be null x >= 0 return value not null return value >= 0 Invoking a function not compliant with the contract or using it's return value in a way the contract does not guarantee leads to errors and bugs, inevitably. The next thing to realize is ...


0

There are two conditions for your logger (and for all singletons): 1. The singleton should be callable at any time. 2. The singleton should be callable at any time, from any thread. (1) means that you cannot expect to set the filename before the singleton gets called the first time. You can set it of course while the singleton is being created, from the ...


0

Here's your problem: return button; Once you do that you've exposed the button. Anyone can call it directly. Consider: return new ButtonWrapper(this, button); //"this" representing canvas here The button wrapper only permits changing button color though a method that also calls canvas.foo(). Since button was never exposed directly it can only be used in ...


2

You're absolutely right in questioning whether microservices are a good fit for your problem in the first place. However, I would not rule microservices out based on the reason you've provided. Even if every request goes through a fixed series of steps, the major benefits of microservices may still apply: Independent scaling While you could scale a ...


0

Here's the simple solution (untested): public class ThingFactory { private static final HashMap<UUID, WeakReference<Thing>> things = new HashMap<>(); public static Thing getThing(UUID id) { WeakReference<Thing> ref = things.get(id); Thing thing; if (ref == null || (thing = ref.get()) == null) { thing = new ...


0

Problem with BaseClassParams Using struct BaseClassParams { struct DerivedClass_A_Params { }; struct DerivedClass_B_Params { }; }; to capture the data needed to construct derived clsses is DOA in my book. As soon as you need DerivedClass_C, you'll have to go back to the base class and update it to struct BaseClassParams { ...


-1

The right time to set the file name is any time before the first call to the Log method. Just throw an exception from there if the object has not been initialized yet.


-1

You can change the properties of the singleton object this way. singleton.js export var SingletonTester = (function () { // our instance holder var instance; // an emulation of static variables and methods var _static = { name: "SingletonTester", getInstance: function() { if( instance === undefined ) { ...


Top 50 recent answers are included