Posts

Showing posts with the label OOP

On Dependency Injection

I just read an article about eliminating dependencies whose basic thesis is that instead of having a class that depends on something that can give you a value, just depend on that value directly. His example (which you can read more fully in the article) is that instead of having public InvoiceGenerator(IConfigurationReader configurationReader) { _configurationReader = configurationReader; } and later on calling var watermarkText = _configurationReader.Get<string>("invoiceWatermarkText"); if (!String.IsNullOrEmpty(watermarkText)) to get the text we need, just request the text directly: public Invoice GenerateInvoice(string watermarkText) { if (!String.IsNullOrEmpty(watermarkText)) There are two obvious problems with this, which you will hit extremely quickly in real code. One of them, pointed out by a comment by LeszekP, is that most of the time you will require more than a single value from an interface. ...

Don't expose class internals

I'm going to disagree a bit with Robert Martin, the author of Clean Code . In his G14 "Feature Envy" smell he uses the example of an method on an HourlyPayCalculator class that takes an HourlyEmployee argument and then uses its properties to do its job. That makes the method "envy" the HourlyEmployee class - the method "wishes it was inside the HourlyEmployee class". So far, so good. Unfortunately, Robert continues with a counter-example to the feature envy smell; he uses the following example (Java code): public class HourlyEmployeeReport { private HourlyEmployee employee; public HourlyEmployeeReport(HourlyEmployee e) { this.employee = e; } String reportHours() { return String.format("Name: %s\tHours: %d.%1d\n", employee.getName(), employee.getTenthsWorked()/10, employee.getTenthsWorked()%10); } } Robert says: "Clearly, the reportHours method envies the HourlyEmployee class. On...