Tag Info

New answers tagged

1

As an outsider looking at this code, it is not clear how the "hidden dependencies" get created to begin with. What if there is no "db" dependency registered? Does it throw an exception, return null? If my class doesn't get a "db" dependency, how bad is that? Many times people lean towards this pattern when there are too many dependencies to pass in the ...


0

I'll go against the grain slightly from the advice of "keep coding good/slow" and "find a new job" that you'll be receiving in the other answers, in case neither of those options are desirable for you. Here's the sad truth: Sometimes its better to write crappy code that conforms to the team's style than it is to write good code that goes against the grain. ...


1

I agree with @BobDalgleish and @kiwiron above. Keep serialization out of the model, don't be alarmed that serialization logic of a model object is in a separate class. You can see it as a "view" (presentation) of your model, and views are usually separated from their model counterparts.


0

Should I use DataTable and shove it to gridview just like the rest of my team do? Hell no. That's just bad code. It's ok code for very small uncomplicated projects that are unlikely to change and has a database schema that will rarely if ever change. Or for quick one-off-projects. Otherwise that is bad code practice and it will come back and bite you in ...


1

Automated testing Invest your time in automated testing. It will pay you off very quickly. The basic idea is that if you do manual testing only, you'll be unable to handle the ever increasing number of tests. It is not unusual for even a relatively small application to have thousands of tests, not counting integration, system, functional, load and other ...


-2

How about a CalcAverageStrategy interface that is injected, and you can then have mean/median/mode implementations injected where necessary. Each implementation is easy to test, and also easy to mock for testing.


1

Absolute nonsense. A few thoughts: You should not take OOP and it's principles too seriously. Many times functional or other software paradigms make more sense. Though the objects thing is cool... thinking in concrete components and all that. Testing, and specifically Unit Testing is meant to serve the project, verify it's design, and assure its ...


3

If that common behavior sees frequent use, it will admittedly be executed multiple times during tests for each of the subclasses, but so will it at runtime in production, there's nothing wrong with it. However, that doesn't mean you should specifically test the common logic multiple times. Concrete/abstract superclass If the superclass is not abstract and ...


0

You stumbled on one of the Bigger problems that tends to get swept under the rug in unit testing/TDD discussions. Well designed code from an object oriented perspective is generally hard to unit test, code that is easy to write unit tests for usually is compromising some paradigms of object oriented design. Most approaches to unit testing tend to drive ...


1

if any of the methods fails, there is really no point in calling subsequent methods. How should I address those possible method failures? Throw an exception. Should the Carousel class be 'injected' into my class before it is used? Yes, if there is more than one implementation of Carousel (including the possibility of a mock object for unit testing ...


6

I don't agree that you should be sorting your methods by category, or even by visibility. It may seem, at first, like this is a good thing to do, but what you're actually doing is imposing order for the sake of order, but not for any particular reason. Consider ensuring that your address book were sorted by phone number. Certainly, it would be organized, but ...


0

They wont mix up. The function runs seperate on each page(browser). Wherever you declared the $a=1 and $b=2 will provide: 3. Same for the $a=5 and $b=4 will provide: 9. So you dont have to worry about that.


5

Is there a standardized set of categories in OOP that cover what methods can do? No, since by definition, methods can do anything. But you're solving a symptom. I find it easier to find my way through a class when I group its methods by category. This is a sign that your classes are too big, and/or doing too much. It also might be a sign that ...


0

Traditionally, your dependencies would descend downwards in your application. That is, you would have a high level class A, which depends on a lower level class B. Consider a car. In traditional programming, your car object would depend on your steering wheel object, which would depend on your two front wheel objects. This means that if your wheels ...


3

In proprietary software you want to hide implementation details, while in free software you don't care (and you would accept someone extending your library in unexpected ways using the implementation datails). I also think it is related to the notion of leaky abstractions, and since you commented that your library will be free software, I would suggest ...


2

Not that you can't but for me personally it is a code smell in a sense that your base class is supposed to facilitate the creation of its derived classes but not help them with their method implementation. I'm not sure if this assertion is necessarily true. I can think of many examples where it's accepted for base classes to provide functions ...


-3

The boxer punches the punchingbag -> boxer.punch The punchingbag gets punched by the boxer -> punchingbag.get_punch


1

You're already asking yourself the right question: Is a gauge of no specific type useful to anybody? What does it measure? What units does it use? As you've already noticed, it's not. So clearly a gauge isn't something that needs to be instantiated itself. That means a gauge should probably be either an abstract class or an interface. I usually prefer to ...


1

It depends on why you want to prevent instantiation. If you want to have control over instances e.g. the singleton pattern then you would hide/encapsulate the constructor. If the class is a generalisation that in its self could never be an instance then it makes more sense for it to be an abstract class.


0

Having a base class with 6 dependencies is pushing it but acceptable under some circumstances especially if it's rare to have to extend the class. The PHP Symfony 2 framework has a security class with a bunch of dependencies. Extending it is painful but you only need to do so when implementing a completely new authentication system. On the other hand, the ...


2

Both of your designs have the problem that they put the burden of keeping track of the validity of the favoriteColor attribute on the user of the class. Your second design (with the getHasFavoriteColor) has the additional problem that it duplicates the information if there is a valid value for favoriteColor in a way that makes it very easy to create ...


1

The first approach you mentioned is absolutely perfect and there is no need for code refactoring. Dependency Injection is very useful for writing test cases on your class. Because you can easily mock the injected class functionality while you are writing test cases as per your need. The second approach you mentioned is a wrong one. Because, you are passing ...


0

I don't know C++ but I hope my idea helps you to resolve your problem. Create your model class based on your XSD file. class Person { private string name; private string favoritColor; public Person (XmlElement person) { // parse the XML element and assign the values to appropriate element // if the element does not exist, don't assign ...


1

I voted for codingoutloud answer and I'd like to expand on it a little. Wrapping collections in classes is something I've come to try to always do--my rule is "Never pass a naked collection". The biggest failures of OO I've seen is when people are afraid to add methods where they belong. In your case the methods belong on the collection (Totally obviously ...


4

There isn't anything significantly wrong with the first piece of code. Though having more than half a dozen dependencies may indicate a violation of the SRP, there is nothing inherently wrong with having a large constructor. In fact, I would much prefer seeing a constructor with a large number of arguments than a method. Constructors are for getting our ...


-1

It seems like your software could benefit from Dependency Injection. This way, the parent constructor could have its dependencies provided directly to it without having to burden all child classes with constructors that do little more than pass arguments along until they reach the constructor that actually needs them.


2

How is your code easier than the first one? What would Magento constructor look in your example? It would take the same parameters as the actual constructor from the first piece of code, and the only difference would be that instead of one class, you now have two classes. Refactoring should improve code, not move the difficult part to a different class. ...


3

DIP states that Higher level module should depend on Lower level module over abstraction and All variable implementations require Factory Method.Ref: DIP So, creating a Factory Class definitely a good option to resolve your problem. In addition, you could inject both IReader and Iwriter to your Person class. public class Person : IReader, IWriter { ...


1

A third option might involve creating a class to manage the state of your books, then sharing an instance of the class with your Person and IReader implementations. This is conceptually similar to having a book repository or cache. Option 1 or my suggestion are probably the cleaner solutions. Can you provide more information about the overall problem you ...


2

Use of constrained generics for method parameters can allow a method to very its return type based upon that of the thing passed in. In .NET they can have additional advantages as well. Among them: A method which accepts a constrained generic as a ref or out parameter may be passed a variable which satisfies the constraint; by contrast, a non-generic ...


19

Using the parametric version gives More information to the users of the function Constrains the number of programs you can write (free bug checking) As a random example, suppose we have a method which calculates the roots of a quadratic equation int solve(int a, int b, int c) { // My 7th grade math teacher is laughing somewhere } And then you want ...


13

What are the reasons to use actual interface types over types constrained by those interfaces? Because that's what you need... IFoo Fn(IFoo x); T Fn<T>(T x) where T: IFoo; are two decidedly different signatures. The first takes any type implementing the interface and the only guarantee it makes is that the return value satisfies the interface. ...


3

Why is an anemic domain model considered bad in C#/OOP, but very important in F#/FP? Your question has a big problem that will limit the utility of the answers you get: you are implying/assuming that F# and FP are similar. FP is a huge family of languages including symbolic term rewriting, dynamic and static. Even among statically-typed FP languages ...


8

However, everyone who read it, read it like 20 years ago from what it seems. Actually, it was the basis of MIT's 6.001 introduction to programming until fairly recently, and still is used for similar courses in other universities even today. Has it been superseded by another influential book I should be aware of? Not really. There are other books ...


2

Why is the tight coupling an issue? If I create a class containing two integer fields or properties, it is tightly coupled to the implementation of integers. Is this a problem? Only if you need to change the integer to a different type, selecting that type at run time. The premise behind the question (tight coupling is a problem) seems flawed. We can always ...


1

The question is a little unclear, but it sounds like you need to revisit your class design. My analysis is that you are selling Products which belong to a Category and are stored in an Inventory (in your case a flat-file data store). You will also need a ProductStatus class to hold stuff queried from the inventory e.g. Number in stock, isCurrentProduct() ...


0

I'm too lazy to pass around a logger object to each class instance. So, in my code, these kinds of things either sit in a static field or a thread-local variable in a static field. The latter is kind of cool and lets you use a different logger for each thread and lets you add methods to turn logging on and off that do something meaningful and expected in a ...


0

It's worth mentioning, something I have not seen the other answers touch on here, is that by making the logger injected via property or static, it makes it hard(er) to unit test the class. For example, if you make your logger injected via property, you will now have to inject that logger every time you test a method that uses the logger. This means you might ...


1

The trick is to specify the behavior you want in plain language. "A member borrows a book" You have two nouns in that sentence. Each noun it is likely to end up as a class-- in your case Book and Member. There is also the verb "borrows" this will likely end up as a method in one of the classes, and, most likely the subject -- its the member who is doing ...


2

There is a very simple analysis technique in which you write down the use cases in plain text and extract nouns and verbs. The nouns are likely to be essential concepts in your domain (so probably classes), the verbs are likely actions to be taken in the domain (so probably methods). This rule is not written in stone but it can help you get going. When I ...


1

I agree with those suggesting that the logger should be statically accessed rather than passed into classes. However if there is a strong reason you want to pass it in (perhaps different instances want to log to different locations or something) then I would suggest you do not pass it using the constructor but rather make a separate call to do so, e.g. ...


3

You can definitely spend a lot of time over-engineering this problem. For languages with canonical logging implementations, just instantiate the canonical logger directly in every class. For languages without a canonical implementation, try to find a logging facade framework and stick to it. slf4j is a good choice in Java. Personally I'd rather stick to a ...


26

Loggers are what we call a "cross-cutting concern." They yield to techniques such as Aspect-Oriented Programming; if you have a way to decorate your classes with an attribute or perform some code weaving, then that is a good way to get logging capabilities while keeping your objects and parameter lists "pure." The only reason you might want to pass in a ...


7

In languages with function overloading, I'd argue that the more likely an argument is to be optional, the further right it should be. This creates consistency when you create overloads where they're missing: foo(mandatory); foo(mandatory, optional); foo(mandatory, optional, evenMoreOptional); In functional languages the reverse is more useful - the more ...


2

Loggers are a bit of a special case because they have to be available literally everywhere. If you've decided that you want to pass a logger into every class' constructor, then you should definitely set a consistent convention for how you do that (eg, always the first parameter, always passed by reference, the constructor initialization list always starts ...


0

The lesser of two evils, if you are not allowed to refactor the implementing classes, is to not add the method to the interface. There is no reasonable situation where you should break compatibility with the existing interface. The new method belongs in a new interface, and any class that needs to use it will have to implement the new interface. Chances are, ...


1

There are several issues to consider, before deciding how to make the code change. Consider the case when third parties have written code that uses or implements this interface. That would significantly increase the complexity of managing the code changes required, as well as adding a political element to the process - creating work (and cost) for other ...


1

This is a practice that I have seen in the industry. They create a new interface with a number appended, for example Interface2 and make this contain methods in the old interface. Make the old interface deprecated When there is a major overhaul, a new package will most likely be added in (think about the overhaul when Java JDK introduces the new mechanism ...


5

First thing I would try in this situation is to avoid an interface change at all. You could add an extended interface, derived from the original one, with the new method added, and make the code which uses that interface in combination with the new method expecting to get an object of type "ExtendedInterface". If that is not possible, for example because ...


2

The comment is correct, if you really have thousands of classes and no common base class, that's a code smell that should be solved first. Classes that share a common interface but no code whatsoever should be rare. Otherwise, use a tool. Resharper for C# for example will give you an option to actually implement that method in all classes that implement ...



Top 50 recent answers are included