Method-level SRP vs. interface bloat - coding-style

I suggested a refactoring a coworker and he countered basically quoting the SRP. Here's the situation.
We have a bunch of helper methods that to me are all a related purpose - html generation. There could be a lot of options to apply, let's call them A B and C, that you can mix and match.
His original code used a separate method for every option, and for the valid combinations. I saw this as bad because the permutations can quickly escalate out of control.
public string MethodWithA() { /* ... */ }
public string MethodWithB() { /* ... */ }
public string MethodWithC() { /* ... */ }
public string MethodWithAandB() { /* ... */ }
public string MethodWithAndC() { /* ... */ }
public string MethodWithBandC() { /* ... */ }
Our situation isn't quite as extreme as this, but I'm asking for the general case.
I said there should be a single method and the options should be passed as parameters or enum flags.
public string Method(SomeOptions flags)
{
/* minimal base processing */
if (/* flag A */)
{
ModifyForA();
}
/* etc for B and C */
}
His response was that switching on flags like that means the method is doing multiple things. I know "Clean Code" does say something about flags or switch statements being a smell, but I don't think it applies to this case. I think that rule is about finding opportunities for polymorphism. In any case, I think that my version is still doing one thing, but I guess it's up to interpretation.
Is there anything not entirely subjective that we can use to resolve which approach is better?

It is hard to tell as your examples are a bit too generic, but I don't like either of these approaches. The first one results in explosion of combinations, as you correctly note, but the alternative will result in a monstrous method which is impossible to test or analyze. I would prefer some kind of builder, or as it is popular now to call it fluent interface. Then you would have something like:
string html = htmlBuilder.WithA().WithC().Build()

Related

How to use glob notation in a Java-style comment?

This is kind of silly, but it's tripping me up and googling has failed me.
Consider the following:
/*
Example commandline parameters for this class:
--job-name MyJob
--output-path /path/to/output
--input-data /path/to/data/2018/08/*.csv
*/
object DataProcessor {
def main(args: Array[String]): Unit = {
// code here
}
}
The general intent is to use glob notation in a long comment; the above shows an example of why you might want to do that. The problem is that the /* in /path/to/data/2018/08/*.csv turns everything into a comment.
Is there a slick way of "capturing" the /*, short of just adding another */ at the end? I tried enclosing the comment with /** and **/ like in doc strings, but the result is the same.

Does Processing 3 have class declarations?

Our school project has us make a game using Processing 3. After some studying with the language, our team is pretty confident we can work with the project, though we do have certain reservations of the chosen language.
However, there is one major question we are wondering and could not find an answer. In C++ and many others, when you create a new class in a new file you also create a header file you can include. Does Processing 3 have something similar? I know you can "include" files by adding more tabs, which is still weird but whatever. We would like to have some sort of declarations in advance so we can comment/describe classes and their methods, rather than force each member go through lots of code to find the proper point.
In short, we want to be able to do something like this:
Example.pde
class Example {
//Description
Example();
//Description
void doSomething(int variable);
}
//Other team members don't have to worry past this,
//as they have already seen the public interface
Example::Example()
{
//Constructor
}
void Example::doSomething(int variable)
{
//Function
}
Or do we have to always to like this:
Example.pde
class Example {
//Description
Example()
{
//Constructor
}
//Description
void doSomething(int variable)
{
//Function
}
}
Processing is written in Java, so you can only do things that Java supports. Java does not support header files, so no, you can't use header files in Processing.
However, it sounds like what you're really looking for is an interface.
interface Example {
void doSomething(int variable);
}
class MyExample implements Example{
public MyExample(){
//Constructor
}
void doSomething(int variable){
//Function
}
}
With this, you would only need to show other team members the interface, not the class. As long as they program to the interface, they don't need to ever see the class implementation.
More info on interfaces can be found in the Processing reference.

Is it good practice for void methods to return?

The return statement is being used in void methods to break out of the logic here. The problem is the consumers of the method wouldn’t know whether the logic in the method ran completely or not, when we do this. However my architect and teams don't agree with that. The reason is that the current consumer in this case doesn't care about the outcome.
I think this is coding anti-pattern. It is like eating exception with out bubbling it up. What's everyone's opinion on this?
Existing code:
Private void XXX(final String parameter) {
try {
if (parameter==null){
return;
}
....
}
My version
Private boolean XXX(final String parameter) {
try {
if (parameter==null){
return false;
}
....
return true;
}
In general having multiple returns is not necessarily an anti-pattern. At worst there might be many exit points in the method which can be confusing for developers who are reading the code and perhaps make it harder to maintain...maybe but that is not what you seem to be asking.
The code samples you provided appear to me to both be anti-patterns.
The problem is the consumers of the method wouldn’t know whether the logic in the method ran completely or not, when we do this.
First, that is what Exceptions are for. If there is a problem while executing the code in the method, throw an Exception with an intent revealing type and a good message describing the problem.
The first version of your code:
Private void XXX(final String parameter) {
try {
if (parameter==null){
return;
}
....
}
seemed to return instead of throwing an Exception with an invalid argument.
The second version of the code:
Private boolean XXX(final String parameter) {
try {
if (parameter==null){
return false;
}
....
return true;
}
Seems to return a boolean as an exit code of "worked" or "didn't work". This isn't very helpful because if it didn't work, you don't know why. Also it requires the calling code to check the return value which they might forget to do.
There's nothing wrong with having an explicit return for a void method. However, it is good general practice--if possible--to have just one return from a method (although you can have more than one if logic demands it and you write the code as simply as possible--no blocks--so that the overall flow is not obfuscated).
Should you simply return in the case you cite? It all depends on the requirements. Your customers appear to be the programmers who will call this method. Do they consider a null parameter to be a logic error for the method or do they consider it to be valid?
If it's the former then I suggest you use an annotation (#NotNull) to ensure that parameter is not null. Unfortunately, there are several of these to choose from so you will have to figure out which suits your architecture best.
If you really don't want to use an annotation (and null is considered an error) then throw an exception.

How do I name the function which only does something if condition is true

According to clean code laws, we want to have functions which do only one thing and are on the same "level of abstraction". But how to name function, whose work is just to check some condition and do the work if condition is true. For example, how could this function be named?
public void HowToNameThis(){
if(!ComponentIsInstalled()){
DisableCheckbox();
}
}
I thought about naming it like DisableCheckboxIfComponentIsNotInstalled, but then the name just repeats the code, which effectively means I have created a function but did not create any abstraction.
CleanCode also suggest that you stay as positive as you can in your code. If you reverse the logic within your method, then, naming becomes easier.
public void TryEnableComponent() {
if(ComponentIsInstalled()) {
EnableCheckbox();
}
}
I generally think really hard about if the IF is really deserving it's own function.
And then often end up inlining it:
Like this (pseudo):
void SetupInstallerWindow()
{
LoadLicenseAgreement();
if(!ComponentIsInstalled()){
DisableCheckbox();
}
BringWindowTop();
}
If that really gets to messy, here's an idea for a name might provide more context for the reader:
AllowReinstallationOfComponent()

How to take advantage of an auto-property when refactoring this .Net 1.1 sample?

I see a lot of legacy .Net 1.1-style code at work like in example below, which I would like to shrink with the help of an auto-property. This will help many classes shrink by 30-40%, which I think would be good.
public int MyIntThingy
{
get
{
return _myIntThingy;
}
set
{
_myIntThingy = value;
}
} private int _myIntThingy = -1;
This would become:
public int MyIntThingy
{
get;
set;
}
And the only question is - where do I set MyIntThingy = -1;?
If I wrote the class from the start, then I would have a better idea, but I did not. An obvious answer would be: put it in the constructor. Trouble is: there are many constructors in this class. Watching the initialization to -1 in the debugger, I see it happen (I believe) before the constructor gets called. It is almost as if I need to use a static constructor as described here:
http://www.c-sharpcorner.com/uploadfile/cupadhyay/staticconstructors11092005061428am/staticconstructors.aspx
except that my variables are not static. Java's static initializer comes to mind, but again - my variables are not static. http://www.glenmccl.com/tip_003.htm
I want to make stylistic but not functional changes to this class. As crappy as it is, it has been tested and working for a few years now. breaking the functionality would be bad. So ... I am looking for shorter, sweeter, cuter, and yet EQUIVALENT code. Let me know if you have questions.
I'm afraid that you have no option.
If you want to use an auto-property with an initial value that differs from the type's default value then you'll need to set the initial value in the constructor(s).
If you just need a stylistic, non-breaking change, consider changing the format a little:
public int MyIntThingy
{
get { return _myIntThingy; }
set { _myIntThingy = value; }
}
private int _myIntThingy = -1;
Isn't that prettier?
And consider using auto-properties for future code only. It sounds too risky to use them on existing code, unless there are no default values.

Resources