Is heavy (slf4j logger) method overloading an anti-pattern? - overloading

slf4j is heavily overloading methods:
Method Summary
void debug(Marker marker, String msg)
Log a message with the specific Marker at the DEBUG level.
void debug(Marker marker, String format, Object... arguments)
This method is similar to debug(String, Object...)
void debug(Marker marker, String format, Object arg)
This method is similar to debug(String, Object) method except that the marker data is also taken into consideration.
void debug(Marker marker, String format, Object arg1, Object arg2)
This method is similar to debug(String, Object, Object) method except that the marker data is also taken into consideration.
void debug(Marker marker, String msg, Throwable t)
This method is similar to debug(String, Throwable) method except that the marker data is also taken into consideration.
void debug(String msg)
is this an antipattern as elegant code specifies?

Each pattern can become antipattern if it is used incorrectly. Some anti patterns can become good if their usage is reasonable.
In case of slf4j and most other logging APIs this overloading seems reasonable. Logging API should be simple yet powerful enough for user and is not being changed frequently. This is the reason that most logging APIs I know are built as Facade to lower level functionality.
Think about logging API like
public void log(Level level, Formatter formatter, LogMessage msg);
Every time when you want to print message like "User John has logged in successfully" you have to create object of formatter and LogMessage and refer to Level.INFO. Is it simpler to call method like
public void info(String message, Object ... args);
that will call lower level method log() with all needed parameters.
This is what slf4j does for you. So it has method for each log level and for each useful scenario:
with and without marker
with and without throwable
with simple message and with format + arguments
IMHO for me sounds reasonable.

Related

getting InvalidUseOfMatchersException in a proper use of matchers

Everything sounds correct but I get org.mockito.exceptions.misusing.InvalidUseOfMatchersException, when I try to mock a protected method.How Can I solve it ?
private Service service;
private System system;
#BeforeMethod
public void setupMocks() throws Exception {
service = powerMock.mock(Service.class);
system = powerMock.mock(System.class);
}
public void sample_Test() {
PowerMockito.doReturn(system).when(service, "getValidatedDto",
Matchers.any(Long.class), Matchers.any(Date.class));
// some code
}
I suspect you are seeing this exception:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
4 matchers expected, 2 recorded:
With this additional context:
This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
If so, then this is because you are mixing parameters in the form of matchers (Matchers.any(Long.class), Matchers.any(Date.class)) with parameters in the form of raw values (service, "getValidatedDto").
The signature of the method under test is unclear to me but I think it might be something like
System getValidatedDto(Long aLong, Date aDate);
If so, then the correct invocation would be:
PowerMockito.doReturn(system).when(service).getValidatedDto(
Matchers.any(Long.class), Matchers.any(Date.class));

c# programmer tries for events in c++

Hi all: I'm an experienced c# programmer trying to do some work in c++, and I'm not sure about the right way to do this:
I am authoring a class that needs to notify a consuming class that something has happened.
If I were writing this in c#, I would define an event on my class.
No events in c++, so I am trying to figure out what is the correct way to do this. I have thought about callback functions, but how do I handle a case where I want to execute a member function (not a static function).
More specifically, what I really need to do is to handle the event, but have access to member state within the object instance that is handling the event.
I have been looking at std::tr1:function, but I am having trouble getting it to work.
I don't suppose that anyone would want to translate the following example c# example into an example of the correct/best practice c++ (I need ANSI c++)?
(please bear in mind that I have almost no c++ experience -- don't assume that I know any long-established c++ conventions -- I don't ;);
A simple c# console app (works on my machine):
using System;
namespace ConsoleApplication1
{
public class EventSource
{
public event EventHandler<EchoEventArgs> EchoEvent;
public void RaiseEvent(int echoId)
{
var echoEvent = this.EchoEvent;
if (echoEvent != null)
echoEvent(this, new EchoEventArgs() {EchoId = echoId});
}
}
public class EchoEventArgs : EventArgs
{
public int EchoId { get; set; }
}
public class EventConsumer
{
public int Id { get; set; }
public EventConsumer(EventSource source)
{
source.EchoEvent += OnEcho;
}
private void OnEcho(object sender, EchoEventArgs args)
{
// handle the echo, and use this.Id to prove that the correct instance data is present.
Console.WriteLine("Echo! My Id: {0} Echo Id: {1}", this.Id, args.EchoId);
}
}
internal class Program
{
private static void Main(string[] args)
{
var source = new EventSource();
var consumer1 = new EventConsumer(source) { Id = 1 };
var consumer2 = new EventConsumer(source) { Id = 2 };
source.RaiseEvent(1);
Console.ReadLine();
}
}
}
The basic idea is to take function objects, e.g., something like std::function<Signature> as the callbacks. These aren't function pointers but can be called. The standard C++ library (for C++ 2011) contains a number of class and functions, e.g., std::mem_fn() and std::bind() which allow using functions, including member functions, to be used as function objects.
The part what is missing is something supporting multiple events be registered: std::function<Signature> represents one function. However, it is easy to put them, e.g., into a std::vector<std::function<Signature>>. What becomes more interesting (and requires variadic templates to be done easily) is creating an event class which encapsulates the abstraction of multiple events begin registered, potentially unregistered, and called.
C++ has a concept of functor: a callable object. You need to read about them.
Think about an object that has overwritten operator(). You pass an instance of such an object. After that you can call it like a regular function. And it can maintain a state.
There's also Signals2 library in Boost, which provides an API very close to real C# events, at least in idiomatic sense.
Qt has something that might help you called Signals and Slots: http://qt-project.org/doc/qt-4.8/signalsandslots.html
It lets you specify what the signals (the events that you want to listen to) and the slots (the receiving side) an object has, and then you can connect them. More than one object can listen to a signal like you mention you needed.
Qt is a large app framework, so I'm not sure how to use only the signals & slots part of it. But if you're building an entire GUI application the rest of the Qt might benefit you too (a lot of the ui event stuff is based on signals and slots).

Polymorphic Command Parser Design

Would love some opinions on this problem I'm trying to workout. I'm trying to improve my OO experience and fully leverage C++'s polymorphic capabilities. I'm trying to write some code for a basic command parser. They command structure goes as so:
[command name] [arguments]
The command name will just be limited to a one word string. The arguments can be a 0 to N list of strings.
Each command and list of arguments could be directed to any variety of software objects in my system. So for example I could have an rtp statistics command map to my rtp module, the user statistics to my user module. Something like that.
Right now the entry point for my CLI provides the entire command string as a standard string. And it provides a standard output stream for displaying results to the user.
I really want to avoid using a parser function and then doing an if then else kind of deal. So I was thinking something like this:
I would have a base class called command. Its constructor would take the string command, the stdout, and an interface for the object it needs to interact with.
I would create a command factory that would match the command name to the object that handles it. This would instantiate the right command object for the right command.
Each separate command object would parse the given arguments and make the right choices for this command.
What I'm struggling with is how to give the right module to the right command. Is this where I should use a template argument? So that each command can take any interface and I'll let the factory decide which module to pass in to the command object?
I'm also open to other opinions as well. I'm just trying to learn and hoping the community can give me some tips :-).
What you're looking for is a common pattern in OOP. Design Patterns (the Gang of Four book) referred to this as a Command Pattern.
There's generally no need for templates. Everything is parsed and dispatched at runtime, so dynamic polymorphism (virtual functions) is probably a better choice.
In another answer, Rafael Baptista suggested a basic design. Here is how I would modify his design to be more complete:
Command objects and CommandDispatcher
Commands are handled by subclasses of the Command class. Commands are dispatched by a CommandDispatcher object that handles the basic parsing of the command string (basically, splitting at spaces, possibly handling quoted strings, etc.).
The system registers an instance of Command with the CommandDispatcher, and associates each instance of Command with a command name (std::string). The association is handled by a std::map object, although that could be replaced by a hash table (or similar structure to associate key-value pairs).
class Command
{
public:
virtual ~Command(void);
virtual void execute(FILE* in, const std::vector<std::string>& args) = 0;
};
class CommandDispatcher
{
public:
typedef std::map<std::string, Command*> CommandMap;
void registerCommand(const std::string& commandName, Command* command)
{
CommandMap::const_iterator cmdPair = registeredCommands.find(commandName);
if (cmdPair != registeredCommands.end())
{
// handle error: command already registered
}
else
{
registeredCommands[commandName] = command;
}
}
// possibly include isRegistered, unregisterCommand, etc.
void run(FILE* in, const std::string& unparsedCommandLine); // parse arguments, call command
void dispatch(FILE* in, const std::vector<std::string>& args)
{
if (! args.empty())
{
CommandMap::const_iterator cmdPair = registeredCommands.find(args[0]);
if (cmdPair == registeredCommands.end())
{
// handle error: command not found
}
else
{
Command* cmd = cmdPair->second;
cmd->execute(in, args);
}
}
}
private:
CommandMap registeredCommands;
};
I've left the parsing, and other details out, but this is a pretty common structure for command patterns. Notice how the std::map handles associating the command name with the command object.
Registering commands
To make use of this design, you need to register commands in the system. You need to instantiate CommandDispatcher, either using a Singleton pattern, in main, or in another central location.
Then, you need to register the command objects. There are several ways to do this. The way I prefer, because you have more control, is to have each module (set of related commands) provide its own registration function. For example, if you have a 'File IO' module, then you might have a function fileio_register_commands:
void fileio_register_commands(CommandDispatcher* dispatcher)
{
dispatcher->registerCommand( "readfile", new ReadFileCommand );
dispatcher->registerCommand( "writefile", new WriteFileCommand );
// etc.
}
Here ReadFileCommand and WriteFileCommand are subclasses of Command that implement the desired behavior.
You have to make sure to call fileio_register_commands before the commands become available.
This approach can be made to work for dynamically loaded libraries (DLLs or shared libraries). Make sure that the function to register commands has a regular pattern, based on the name of the module: XXX_register_commands, where XXX is, for example, the lower cased module name. After you load the shared library or DLL, your code can determine whether such a function exists, and then call it.
Templates is overkill. I imagine you want something where the command interpreter just figures out what commands are possible from the objects that are available.
For each class that wants to support this CLI, I'd give it a function that registers the class, and the command name that triggers that class.
class CLIObject
{
virtual void registerCli( Cli& cli ) = 0;
virtual bool doCommand( FILE* file, char** args ) = 0;
}
class HelloWorld : public ClIObject
{
void registerCli( Cli& cli ) { cli.register( this, "helloworld" ); }
bool doCommand( FILE* file, char** args )
{
if ( !args[0] ) return false;
fprintf( file, "hello world! %s", args[0] );
return true;
}
}
Now your cli can support any class that derives from CLIObject.

C++ Error Reporting Interface

I'm designing an interface that can be used to report errors in C++. (I'm working with a legacy system where exceptions are out of question.) In my youthful naivety, I started along these lines while designing my API:
bool DoStuff(int amount, string* error);
Return value signals success/failure, while error is used to report a human readable explanation. So far so good. Subroutine calls passed along the error pointer and everything was hunky-dory.
I ran into the following problems with this design (so far):
Cannot report warnings.
Not thread-safe.
Next, I decided to go with the following interface, instead of plain string:
class Issues {
public:
void Error(const string& message);
void Warning(const string& message);
void Merge(const Issues& issues);
}
So that I can change my API like this:
bool DoStuff(int amount, Issues* issues);
I'm wondering, is there a more generic/standard API out there that deals with this problem? If yes, I'd like to take a look.
UPDATE: I'm not looking for a logging library. For those who are curious, imagine you're writing a query engine that includes a compiler. The compiler issues warnings and errors, and those need to be returned to the user, as part of the response. Logging has its place in the design, but this is not it.
I usually use things like boost::signals or .NET delegates to report errors/warning/logging/whatever. You report errors with no changes to the interface, and the library user plugs whatever she wants to the signal to get the error reports (writing to a file, updating a console window, aborting the program, throwing an exception, ignoring warnings, etc).
Something like this, at eg. global scope:
boost::signal<void(std::string const&)> logError;
boost::signal<void(std::string const&)> logWarning;
and then
void routineWhichMayFail()
{
...
if (answer != 42)
{
logError("Universal error");
return;
}
}
and you connect something to logError and logWarning at initialization:
void robustErrorHandler(std::string const& msg)
{
std::cerr << "Error: " << msg << "\n";
std::exit(EXIT_FAILURE);
}
void initializeMyProgram()
{
logError.connect(&robustErrorHandler);
}
You can even throw exceptions in the error handler instead of exiting, and use fancier things than bare functions (logging classes, "delegates" -- pointers to methods with a this object bundled, RPC to a distant server). This way, you decouple the error handling from error reporting, which is good. You can also report to multiple destinations, you can even have your handlers return a boolean telling whether the action should be eg. retried.
From your explanation it sounds like you are trying to implement a logging library for your project. You can look at log4cpp or Boost.Log.

Exception handling aware of execution flow

Edit:
For personn interested in a cleaner way to implemenent that, have a look to that answer.
In my job I often need to use third-made API to access remote system.
For instance to create a request and send it to the remote system:
#include "external_lib.h"
void SendRequest(UserRequest user_request)
{
try
{
external_lib::Request my_request;
my_request.SetPrice(user_request.price);
my_request.SetVolume(user_request.quantity);
my_request.SetVisibleVolume(user_request.quantity);
my_request.SetReference(user_request.instrument);
my_request.SetUserID(user_request.user_name);
my_request.SetUserPassword(user_request.user_name);
// Meny other member affectations ...
}
catch(external_lib::out_of_range_error& e)
{
// Price , volume ????
}
catch(external_lib::error_t& e)
{
// Here I need to tell the user what was going wrong
}
}
Each lib's setter do checks the values that the end user has provided, and may thow an exception when the user does not comply with remote system needs. For instance a specific user may be disallowed to send a too big volume. That's an example, and actually many times users tries does not comply: no long valid instrument, the prices is out of the limit, etc, etc.
Conseqently, our end user need an explicit error message to tell him what to modify in its request to get a second chance to compose a valid request. I have to provide hiim such hints
Whatever , external lib's exceptions (mostly) never specifies which field is the source
of aborting the request.
What is the best way, according to you, to handle those exceptions?
My first try at handling those exceptions was to "wrap" the Request class with mine. Each setters are then wrapped in a method which does only one thing : a try/catch block. The catch block then throws a new exceptions of mine : my_out_of_range_volume, or my_out_of_range_price depending on the setter. For instance SetVolume() will be wrapped this way:
My_Request::SetVolume(const int volume)
{
try
{
m_Request.SetVolume(volume);
}
catch(external_lib::out_range_error& e)
{
throw my_out_of_range_volume(volume, e);
}
}
What do you think of it? What do you think about the exception handling overhead it implies? ... :/
Well the question is open, I need new idea to get rid of that lib constraints!
If there really are a lot of methods you need to call, you could cut down on the code using a reflection library, by creating just one method to do the calling and exception handling, and passing in the name of the method/property to call/set as an argument. You'd still have the same amount of try/catch calls, but the code would be simpler and you'd already know the name of the method that failed.
Alternatively, depending on the type of exception object that they throw back, it may contain stack information or you could use another library to walk the stack trace to get the name of the last method that it failed on. This depends on the platform you're using.
I always prefer a wrapper whenever I'm using third party library.
It allows me to define my own exception handling mechanism avoiding users of my class to know about external library.
Also, if later the third party changes the exception handling to return codes then my users need not be affected.
But rather than throwing the exception back to my users I would implement the error codes. Something like this:
class MyRequest
{
enum RequestErrorCode
{
PRICE_OUT_OF_LIMIT,
VOLUME_OUT_OF_LIMIT,
...
...
...
};
bool SetPrice(const int price , RequestErrorCode& ErrorCode_out);
...
private:
external_lib::Request mRequest;
};
bool MyRequest::SetPrice(const int price , RequestErrorCode& ErrorCode_out)
{
bool bReturn = true;
try
{
bReturn = mRequest.SetPrice(price);
}
catch(external_lib::out_of_range_error& e)
{
ErrorCode_out = PRICE_OUT_OF_LIMIT;
bReturn = false;
}
return bReturn;
}
bool SendRequest(UserRequest user_request)
{
MyRequest my_request;
MyRequest::RequestErrorCode anErrorCode;
bool bReturn = my_request.SetPrice(user_request.price, anErrorCode);
if( false == bReturn)
{
//Get the error code and process
//ex:PRICE_OUT_OF_LIMIT
}
}
I think in this case I might dare a macro. Something like (not tested, backslashes omitted):
#define SET( ins, setfun, value, msg )
try {
ins.setfun( value );
}
catch( external::error & ) {
throw my_explanation( msg, value );
}
and in use:
Instrument i;
SET( i, SetExpiry, "01-01-2010", "Invalid expiry date" );
SET( i, SetPeriod, 6, "Period out of range" );
You get the idea.
Although this is not really the answer you are looking for, but i think that your external lib, or you usage of it, somehow abuses exceptions. An exception should not be used to alter the general process flow. If it is the general case, that the input does not match the specification, than it is up to your app to valid the parameter before passing it to the external lib. Exceptions should only be thrown if an "exceptional" case occurrs, and i think whenever it comes to doing something with user input, you usually have to deal with everything and not rely on 'the user has to provide the correct data, otherwise we handle it with exceptions'.
nevertheless, an alternative to Neil's suggestions could be using boost::lambda, if you want to avoid macros.
In your first version, you could report the number of operations that succeeded provided the SetXXX functions return some value. You could also keep a counter (which increases after every SetXXX call in that try block) to note what all calls succeeded and based on that counter value, return an appropriate error message.
The major problem with validating each and every step is, in a real-time system -- you are probably introducing too much latency.
Otherwise, your second option looks like the only way. Now, if you have to write a wrapper for every library function and why not add the validation logic, if you can, instead of making the actual call to the said library? This IMO, is more efficient.